bokehRequire = (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: {}};
            modules[name][0].call(m.exports, function(x) {
                var id = modules[name][1][x];
                return newRequire(id ? id : x);
            }, m, m.exports, outer, modules, cache, entry);
        }

        return cache[name].exports;
    }

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

    return newRequire;
})
({"backbone":[function(require,module,exports){
(function (global){
//     Backbone.js 1.2.3

//     (c) 2010-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
//     Backbone may be freely distributed under the MIT license.
//     For all details and documentation:
//     http://backbonejs.org

(function(factory) {

  // Establish the root object, `window` (`self`) in the browser, or `global` on the server.
  // We use `self` instead of `window` for `WebWorker` support.
  var root = (typeof self == 'object' && self.self == self && self) ||
            (typeof global == 'object' && global.global == global && global);

  // Set up Backbone appropriately for the environment. Start with AMD.
  if (typeof define === 'function' && define.amd) {
    define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
      // Export global even in AMD case in case this script is loaded with
      // others that may still expect a global Backbone.
      root.Backbone = factory(root, exports, _, $);
    });

  // Next for Node.js or CommonJS. jQuery may not be needed as a module.
  } else if (typeof exports !== 'undefined') {
    var _ = require('underscore'), $;
    try { $ = require('jquery'); } catch(e) {}
    factory(root, exports, _, $);

  // Finally, as a browser global.
  } else {
    root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$));
  }

}(function(root, Backbone, _, $) {

  // Initial Setup
  // -------------

  // Save the previous value of the `Backbone` variable, so that it can be
  // restored later on, if `noConflict` is used.
  var previousBackbone = root.Backbone;

  // Create a local reference to a common array method we'll want to use later.
  var slice = Array.prototype.slice;

  // Current version of the library. Keep in sync with `package.json`.
  Backbone.VERSION = '1.2.3';

  // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns
  // the `$` variable.
  Backbone.$ = $;

  // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
  // to its previous owner. Returns a reference to this Backbone object.
  Backbone.noConflict = function() {
    root.Backbone = previousBackbone;
    return this;
  };

  // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
  // will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and
  // set a `X-Http-Method-Override` header.
  Backbone.emulateHTTP = false;

  // Turn on `emulateJSON` to support legacy servers that can't deal with direct
  // `application/json` requests ... this will encode the body as
  // `application/x-www-form-urlencoded` instead and will send the model in a
  // form param named `model`.
  Backbone.emulateJSON = false;

  // Proxy Backbone class methods to Underscore functions, wrapping the model's
  // `attributes` object or collection's `models` array behind the scenes.
  //
  // collection.filter(function(model) { return model.get('age') > 10 });
  // collection.each(this.addView);
  //
  // `Function#apply` can be slow so we use the method's arg count, if we know it.
  var addMethod = function(length, method, attribute) {
    switch (length) {
      case 1: return function() {
        return _[method](this[attribute]);
      };
      case 2: return function(value) {
        return _[method](this[attribute], value);
      };
      case 3: return function(iteratee, context) {
        return _[method](this[attribute], cb(iteratee, this), context);
      };
      case 4: return function(iteratee, defaultVal, context) {
        return _[method](this[attribute], cb(iteratee, this), defaultVal, context);
      };
      default: return function() {
        var args = slice.call(arguments);
        args.unshift(this[attribute]);
        return _[method].apply(_, args);
      };
    }
  };
  var addUnderscoreMethods = function(Class, methods, attribute) {
    _.each(methods, function(length, method) {
      if (_[method]) Class.prototype[method] = addMethod(length, method, attribute);
    });
  };

  // Support `collection.sortBy('attr')` and `collection.findWhere({id: 1})`.
  var cb = function(iteratee, instance) {
    if (_.isFunction(iteratee)) return iteratee;
    if (_.isObject(iteratee) && !instance._isModel(iteratee)) return modelMatcher(iteratee);
    if (_.isString(iteratee)) return function(model) { return model.get(iteratee); };
    return iteratee;
  };
  var modelMatcher = function(attrs) {
    var matcher = _.matches(attrs);
    return function(model) {
      return matcher(model.attributes);
    };
  };

  // Backbone.Events
  // ---------------

  // A module that can be mixed in to *any object* in order to provide it with
  // a custom event channel. You may bind a callback to an event with `on` or
  // remove with `off`; `trigger`-ing an event fires all callbacks in
  // succession.
  //
  //     var object = {};
  //     _.extend(object, Backbone.Events);
  //     object.on('expand', function(){ alert('expanded'); });
  //     object.trigger('expand');
  //
  var Events = Backbone.Events = {};

  // Regular expression used to split event strings.
  var eventSplitter = /\s+/;

  // Iterates over the standard `event, callback` (as well as the fancy multiple
  // space-separated events `"change blur", callback` and jQuery-style event
  // maps `{event: callback}`).
  var eventsApi = function(iteratee, events, name, callback, opts) {
    var i = 0, names;
    if (name && typeof name === 'object') {
      // Handle event maps.
      if (callback !== void 0 && 'context' in opts && opts.context === void 0) opts.context = callback;
      for (names = _.keys(name); i < names.length ; i++) {
        events = eventsApi(iteratee, events, names[i], name[names[i]], opts);
      }
    } else if (name && eventSplitter.test(name)) {
      // Handle space separated event names by delegating them individually.
      for (names = name.split(eventSplitter); i < names.length; i++) {
        events = iteratee(events, names[i], callback, opts);
      }
    } else {
      // Finally, standard events.
      events = iteratee(events, name, callback, opts);
    }
    return events;
  };

  // Bind an event to a `callback` function. Passing `"all"` will bind
  // the callback to all events fired.
  Events.on = function(name, callback, context) {
    return internalOn(this, name, callback, context);
  };

  // Guard the `listening` argument from the public API.
  var internalOn = function(obj, name, callback, context, listening) {
    obj._events = eventsApi(onApi, obj._events || {}, name, callback, {
        context: context,
        ctx: obj,
        listening: listening
    });

    if (listening) {
      var listeners = obj._listeners || (obj._listeners = {});
      listeners[listening.id] = listening;
    }

    return obj;
  };

  // Inversion-of-control versions of `on`. Tell *this* object to listen to
  // an event in another object... keeping track of what it's listening to
  // for easier unbinding later.
  Events.listenTo =  function(obj, name, callback) {
    if (!obj) return this;
    var id = obj._listenId || (obj._listenId = _.uniqueId('l'));
    var listeningTo = this._listeningTo || (this._listeningTo = {});
    var listening = listeningTo[id];

    // This object is not listening to any other events on `obj` yet.
    // Setup the necessary references to track the listening callbacks.
    if (!listening) {
      var thisId = this._listenId || (this._listenId = _.uniqueId('l'));
      listening = listeningTo[id] = {obj: obj, objId: id, id: thisId, listeningTo: listeningTo, count: 0};
    }

    // Bind callbacks on obj, and keep track of them on listening.
    internalOn(obj, name, callback, this, listening);
    return this;
  };

  // The reducing API that adds a callback to the `events` object.
  var onApi = function(events, name, callback, options) {
    if (callback) {
      var handlers = events[name] || (events[name] = []);
      var context = options.context, ctx = options.ctx, listening = options.listening;
      if (listening) listening.count++;

      handlers.push({ callback: callback, context: context, ctx: context || ctx, listening: listening });
    }
    return events;
  };

  // Remove one or many callbacks. If `context` is null, removes all
  // callbacks with that function. If `callback` is null, removes all
  // callbacks for the event. If `name` is null, removes all bound
  // callbacks for all events.
  Events.off =  function(name, callback, context) {
    if (!this._events) return this;
    this._events = eventsApi(offApi, this._events, name, callback, {
        context: context,
        listeners: this._listeners
    });
    return this;
  };

  // Tell this object to stop listening to either specific events ... or
  // to every object it's currently listening to.
  Events.stopListening =  function(obj, name, callback) {
    var listeningTo = this._listeningTo;
    if (!listeningTo) return this;

    var ids = obj ? [obj._listenId] : _.keys(listeningTo);

    for (var i = 0; i < ids.length; i++) {
      var listening = listeningTo[ids[i]];

      // If listening doesn't exist, this object is not currently
      // listening to obj. Break out early.
      if (!listening) break;

      listening.obj.off(name, callback, this);
    }
    if (_.isEmpty(listeningTo)) this._listeningTo = void 0;

    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];
      }
    }
    if (_.size(events)) 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));
    return this.on(events, void 0, 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, cb, args) {
    if (objEvents) {
      var events = objEvents[name];
      var allEvents = objEvents.all;
      if (events && allEvents) allEvents = allEvents.slice();
      if (events) triggerEvents(events, args);
      if (allEvents) triggerEvents(allEvents, [name].concat(args));
    }
    return objEvents;
  };

  // A difficult-to-believe, but optimized internal dispatch function for
  // triggering events. Tries to keep the usual cases speedy (most internal
  // Backbone events have 3 arguments).
  var triggerEvents = function(events, args) {
    var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
    switch (args.length) {
      case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
      case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
      case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
      case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
      default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return;
    }
  };

  // Aliases for backwards compatibility.
  Events.bind   = Events.on;
  Events.unbind = Events.off;

  // Allow the `Backbone` object to serve as a global event bus, for folks who
  // want global "pubsub" in a convenient place.
  _.extend(Backbone, Events);

  // Backbone.Model
  // --------------

  // Backbone **Models** are the basic data object in the framework --
  // frequently representing a row in a table in a database on your server.
  // A discrete chunk of data and a bunch of useful, related methods for
  // performing computations and transformations on that data.

  // Create a new model with the specified attributes. A client id (`cid`)
  // is automatically generated and assigned for you.
  var Model = Backbone.Model = function(attributes, options) {
    var attrs = attributes || {};
    options || (options = {});
    this.cid = _.uniqueId(this.cidPrefix);
    this.attributes = {};
    if (options.collection) this.collection = options.collection;
    if (options.parse) attrs = this.parse(attrs, options) || {};
    attrs = _.defaults({}, attrs, _.result(this, 'defaults'));
    this.set(attrs, options);
    this.changed = {};
    this.initialize.apply(this, arguments);
  };

  // Attach all inheritable methods to the Model prototype.
  _.extend(Model.prototype, Events, {

    // A hash of attributes whose current and previous value differ.
    changed: null,

    // The value returned during the last failed validation.
    validationError: null,

    // The default name for the JSON `id` attribute is `"id"`. MongoDB and
    // CouchDB users may want to set this to `"_id"`.
    idAttribute: 'id',

    // The prefix is used to create the client id which is used to identify models locally.
    // You may want to override this if you're experiencing name clashes with model ids.
    cidPrefix: 'c',

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

    // Return a copy of the model's `attributes` object.
    toJSON: function(options) {
      return _.clone(this.attributes);
    },

    // Proxy `Backbone.sync` by default -- but override this if you need
    // custom syncing semantics for *this* particular model.
    sync: function() {
      return Backbone.sync.apply(this, arguments);
    },

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

    // Get the HTML-escaped value of an attribute.
    escape: function(attr) {
      return _.escape(this.get(attr));
    },

    // Returns `true` if the attribute contains a value that is not null
    // or undefined.
    has: function(attr) {
      return this.get(attr) != null;
    },

    // Special-cased proxy to underscore's `_.matches` method.
    matches: function(attrs) {
      return !!_.iteratee(attrs, this)(this.attributes);
    },

    // Set a hash of model attributes on the object, firing `"change"`. This is
    // the core primitive operation of a model, updating the data and notifying
    // anyone who needs to know about the change in state. The heart of the beast.
    set: function(key, val, options) {
      if (key == null) return this;

      // Handle both `"key", value` and `{key: value}` -style arguments.
      var attrs;
      if (typeof key === 'object') {
        attrs = key;
        options = val;
      } else {
        (attrs = {})[key] = val;
      }

      options || (options = {});

      // Run validation.
      if (!this._validate(attrs, options)) return false;

      // Extract attributes and options.
      var unset      = options.unset;
      var silent     = options.silent;
      var changes    = [];
      var changing   = this._changing;
      this._changing = true;

      if (!changing) {
        this._previousAttributes = _.clone(this.attributes);
        this.changed = {};
      }

      var current = this.attributes;
      var changed = this.changed;
      var prev    = this._previousAttributes;

      // For each `set` attribute, update or delete the current value.
      for (var attr in attrs) {
        val = attrs[attr];
        if (!_.isEqual(current[attr], val)) changes.push(attr);
        if (!_.isEqual(prev[attr], val)) {
          changed[attr] = val;
        } else {
          delete changed[attr];
        }
        unset ? delete current[attr] : current[attr] = val;
      }

      // Update the `id`.
      this.id = this.get(this.idAttribute);

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

      // You might be wondering why there's a `while` loop here. Changes can
      // be recursively nested within `"change"` events.
      if (changing) return this;
      if (!silent) {
        while (this._pending) {
          options = this._pending;
          this._pending = false;
          this.trigger('change', this, options);
        }
      }
      this._pending = false;
      this._changing = false;
      return this;
    },

    // Remove an attribute from the model, firing `"change"`. `unset` is a noop
    // if the attribute doesn't exist.
    unset: function(attr, options) {
      return this.set(attr, void 0, _.extend({}, options, {unset: true}));
    },

    // Clear all attributes on the model, firing `"change"`.
    clear: function(options) {
      var attrs = {};
      for (var key in this.attributes) attrs[key] = void 0;
      return this.set(attrs, _.extend({}, options, {unset: true}));
    },

    // Determine if the model has changed since the last `"change"` event.
    // If you specify an attribute name, determine if that attribute has changed.
    hasChanged: function(attr) {
      if (attr == null) return !_.isEmpty(this.changed);
      return _.has(this.changed, attr);
    },

    // Return an object containing all the attributes that have changed, or
    // false if there are no changed attributes. Useful for determining what
    // parts of a view need to be updated and/or what attributes need to be
    // persisted to the server. Unset attributes will be set to undefined.
    // You can also pass an attributes object to diff against the model,
    // determining if there *would be* a change.
    changedAttributes: function(diff) {
      if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
      var old = this._changing ? this._previousAttributes : this.attributes;
      var changed = {};
      for (var attr in diff) {
        var val = diff[attr];
        if (_.isEqual(old[attr], val)) continue;
        changed[attr] = val;
      }
      return _.size(changed) ? changed : false;
    },

    // Get the previous value of an attribute, recorded at the time the last
    // `"change"` event was fired.
    previous: function(attr) {
      if (attr == null || !this._previousAttributes) return null;
      return this._previousAttributes[attr];
    },

    // Get all of the attributes of the model at the time of the previous
    // `"change"` event.
    previousAttributes: function() {
      return _.clone(this._previousAttributes);
    },

    // Fetch the model from the server, merging the response with the model's
    // local attributes. Any changed attributes will trigger a "change" event.
    fetch: function(options) {
      options = _.extend({parse: true}, options);
      var model = this;
      var success = options.success;
      options.success = function(resp) {
        var serverAttrs = options.parse ? model.parse(resp, options) : resp;
        if (!model.set(serverAttrs, options)) return false;
        if (success) success.call(options.context, model, resp, options);
        model.trigger('sync', model, resp, options);
      };
      wrapError(this, options);
      return this.sync('read', this, options);
    },

    // Set a hash of model attributes, and sync the model to the server.
    // If the server returns an attributes hash that differs, the model's
    // state will be `set` again.
    save: function(key, val, options) {
      // Handle both `"key", value` and `{key: value}` -style arguments.
      var attrs;
      if (key == null || typeof key === 'object') {
        attrs = key;
        options = val;
      } else {
        (attrs = {})[key] = val;
      }

      options = _.extend({validate: true, parse: true}, options);
      var wait = options.wait;

      // If we're not waiting and attributes exist, save acts as
      // `set(attr).save(null, opts)` with validation. Otherwise, check if
      // the model will be valid when the attributes, if any, are set.
      if (attrs && !wait) {
        if (!this.set(attrs, options)) return false;
      } else {
        if (!this._validate(attrs, options)) return false;
      }

      // After a successful server-side save, the client is (optionally)
      // updated with the server-side state.
      var model = this;
      var success = options.success;
      var attributes = this.attributes;
      options.success = function(resp) {
        // Ensure attributes are restored during synchronous saves.
        model.attributes = attributes;
        var serverAttrs = options.parse ? model.parse(resp, options) : resp;
        if (wait) serverAttrs = _.extend({}, attrs, serverAttrs);
        if (serverAttrs && !model.set(serverAttrs, options)) return false;
        if (success) success.call(options.context, model, resp, options);
        model.trigger('sync', model, resp, options);
      };
      wrapError(this, options);

      // Set temporary attributes if `{wait: true}` to properly find new ids.
      if (attrs && wait) this.attributes = _.extend({}, attributes, attrs);

      var method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
      if (method === 'patch' && !options.attrs) options.attrs = attrs;
      var xhr = this.sync(method, this, options);

      // Restore attributes.
      this.attributes = attributes;

      return xhr;
    },

    // Destroy this model on the server if it was already persisted.
    // Optimistically removes the model from its collection, if it has one.
    // If `wait: true` is passed, waits for the server to respond before removal.
    destroy: function(options) {
      options = options ? _.clone(options) : {};
      var model = this;
      var success = options.success;
      var wait = options.wait;

      var destroy = function() {
        model.stopListening();
        model.trigger('destroy', model, model.collection, options);
      };

      options.success = function(resp) {
        if (wait) destroy();
        if (success) success.call(options.context, model, resp, options);
        if (!model.isNew()) model.trigger('sync', model, resp, options);
      };

      var xhr = false;
      if (this.isNew()) {
        _.defer(options.success);
      } else {
        wrapError(this, options);
        xhr = this.sync('delete', this, options);
      }
      if (!wait) destroy();
      return xhr;
    },

    // Default URL for the model's representation on the server -- if you're
    // using Backbone's restful methods, override this to change the endpoint
    // that will be called.
    url: function() {
      var base =
        _.result(this, 'urlRoot') ||
        _.result(this.collection, 'url') ||
        urlError();
      if (this.isNew()) return base;
      var id = this.get(this.idAttribute);
      return base.replace(/[^\/]$/, '$&/') + encodeURIComponent(id);
    },

    // **parse** converts a response into the hash of attributes to be `set` on
    // the model. The default implementation is just to pass the response along.
    parse: function(resp, options) {
      return resp;
    },

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

    // A model is new if it has never been saved to the server, and lacks an id.
    isNew: function() {
      return !this.has(this.idAttribute);
    },

    // Check if the model is currently in a valid state.
    isValid: function(options) {
      return this._validate({}, _.defaults({validate: true}, options));
    },

    // Run validation against the next complete set of model attributes,
    // returning `true` if all is well. Otherwise, fire an `"invalid"` event.
    _validate: function(attrs, options) {
      if (!options.validate || !this.validate) return true;
      attrs = _.extend({}, this.attributes, attrs);
      var error = this.validationError = this.validate(attrs, options) || null;
      if (!error) return true;
      this.trigger('invalid', this, error, _.extend(options, {validationError: error}));
      return false;
    }

  });

  // Underscore methods that we want to implement on the Model, mapped to the
  // number of arguments they take.
  var modelMethods = { keys: 1, values: 1, pairs: 1, invert: 1, pick: 0,
      omit: 0, chain: 1, isEmpty: 1 };

  // Mix in each Underscore method as a proxy to `Model#attributes`.
  addUnderscoreMethods(Model, modelMethods, 'attributes');

  // Backbone.Collection
  // -------------------

  // If models tend to represent a single row of data, a Backbone Collection is
  // more analogous to a table full of data ... or a small slice or page of that
  // table, or a collection of rows that belong together for a particular reason
  // -- all of the messages in this particular folder, all of the documents
  // belonging to this particular author, and so on. Collections maintain
  // indexes of their models, both in order, and for lookup by `id`.

  // Create a new **Collection**, perhaps to contain a specific type of `model`.
  // If a `comparator` is specified, the Collection will maintain
  // its models in sort order, as they're added and removed.
  var Collection = Backbone.Collection = function(models, options) {
    options || (options = {});
    if (options.model) this.model = options.model;
    if (options.comparator !== void 0) this.comparator = options.comparator;
    this._reset();
    this.initialize.apply(this, arguments);
    if (models) this.reset(models, _.extend({silent: true}, options));
  };

  // Default options for `Collection#set`.
  var setOptions = {add: true, remove: true, merge: true};
  var addOptions = {add: true, remove: false};

  // Splices `insert` into `array` at index `at`.
  var splice = function(array, insert, at) {
    at = Math.min(Math.max(at, 0), array.length);
    var tail = Array(array.length - at);
    var length = insert.length;
    for (var i = 0; i < tail.length; i++) tail[i] = array[i + at];
    for (i = 0; i < length; i++) array[i + at] = insert[i];
    for (i = 0; i < tail.length; i++) array[i + length + at] = tail[i];
  };

  // Define the Collection's inheritable methods.
  _.extend(Collection.prototype, Events, {

    // The default model for a collection is just a **Backbone.Model**.
    // This should be overridden in most cases.
    model: Model,

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

    // The JSON representation of a Collection is an array of the
    // models' attributes.
    toJSON: function(options) {
      return this.map(function(model) { return model.toJSON(options); });
    },

    // Proxy `Backbone.sync` by default.
    sync: function() {
      return Backbone.sync.apply(this, arguments);
    },

    // Add a model, or list of models to the set. `models` may be Backbone
    // Models or raw JavaScript objects to be converted to Models, or any
    // combination of the two.
    add: function(models, options) {
      return this.set(models, _.extend({merge: false}, options, addOptions));
    },

    // Remove a model, or a list of models from the set.
    remove: function(models, options) {
      options = _.extend({}, options);
      var singular = !_.isArray(models);
      models = singular ? [models] : _.clone(models);
      var removed = this._removeModels(models, options);
      if (!options.silent && removed) this.trigger('update', this, options);
      return singular ? removed[0] : removed;
    },

    // Update a collection by `set`-ing a new list of models, adding new ones,
    // removing models that are no longer present, and merging models that
    // already exist in the collection, as necessary. Similar to **Model#set**,
    // the core operation for updating the data contained by the collection.
    set: function(models, options) {
      if (models == null) return;

      options = _.defaults({}, options, setOptions);
      if (options.parse && !this._isModel(models)) models = this.parse(models, options);

      var singular = !_.isArray(models);
      models = singular ? [models] : models.slice();

      var at = options.at;
      if (at != null) at = +at;
      if (at < 0) at += this.length + 1;

      var set = [];
      var toAdd = [];
      var toRemove = [];
      var modelMap = {};

      var add = options.add;
      var merge = options.merge;
      var remove = options.remove;

      var sort = false;
      var sortable = this.comparator && (at == null) && options.sort !== false;
      var sortAttr = _.isString(this.comparator) ? this.comparator : null;

      // Turn bare objects into model references, and prevent invalid models
      // from being added.
      var model;
      for (var i = 0; i < models.length; i++) {
        model = models[i];

        // If a duplicate is found, prevent it from being added and
        // optionally merge it into the existing model.
        var existing = this.get(model);
        if (existing) {
          if (merge && model !== existing) {
            var attrs = this._isModel(model) ? model.attributes : model;
            if (options.parse) attrs = existing.parse(attrs, options);
            existing.set(attrs, options);
            if (sortable && !sort) sort = existing.hasChanged(sortAttr);
          }
          if (!modelMap[existing.cid]) {
            modelMap[existing.cid] = true;
            set.push(existing);
          }
          models[i] = existing;

        // If this is a new, valid model, push it to the `toAdd` list.
        } else if (add) {
          model = models[i] = this._prepareModel(model, options);
          if (model) {
            toAdd.push(model);
            this._addReference(model, options);
            modelMap[model.cid] = true;
            set.push(model);
          }
        }
      }

      // Remove stale models.
      if (remove) {
        for (i = 0; i < this.length; i++) {
          model = this.models[i];
          if (!modelMap[model.cid]) toRemove.push(model);
        }
        if (toRemove.length) this._removeModels(toRemove, options);
      }

      // See if sorting is needed, update `length` and splice in new models.
      var orderChanged = false;
      var replace = !sortable && add && remove;
      if (set.length && replace) {
        orderChanged = this.length != set.length || _.some(this.models, function(model, index) {
          return model !== set[index];
        });
        this.models.length = 0;
        splice(this.models, set, 0);
        this.length = this.models.length;
      } else if (toAdd.length) {
        if (sortable) sort = true;
        splice(this.models, toAdd, at == null ? this.length : at);
        this.length = this.models.length;
      }

      // Silently sort the collection if appropriate.
      if (sort) this.sort({silent: true});

      // Unless silenced, it's time to fire all appropriate add/sort events.
      if (!options.silent) {
        for (i = 0; i < toAdd.length; i++) {
          if (at != null) options.index = at + i;
          model = toAdd[i];
          model.trigger('add', model, this, options);
        }
        if (sort || orderChanged) this.trigger('sort', this, options);
        if (toAdd.length || toRemove.length) this.trigger('update', this, options);
      }

      // Return the added (or merged) model (or models).
      return singular ? models[0] : models;
    },

    // When you have more items than you want to add or remove individually,
    // you can reset the entire set with a new list of models, without firing
    // any granular `add` or `remove` events. Fires `reset` when finished.
    // Useful for bulk operations and optimizations.
    reset: function(models, options) {
      options = options ? _.clone(options) : {};
      for (var i = 0; i < this.models.length; i++) {
        this._removeReference(this.models[i], options);
      }
      options.previousModels = this.models;
      this._reset();
      models = this.add(models, _.extend({silent: true}, options));
      if (!options.silent) this.trigger('reset', this, options);
      return models;
    },

    // Add a model to the end of the collection.
    push: function(model, options) {
      return this.add(model, _.extend({at: this.length}, options));
    },

    // Remove a model from the end of the collection.
    pop: function(options) {
      var model = this.at(this.length - 1);
      return this.remove(model, options);
    },

    // Add a model to the beginning of the collection.
    unshift: function(model, options) {
      return this.add(model, _.extend({at: 0}, options));
    },

    // Remove a model from the beginning of the collection.
    shift: function(options) {
      var model = this.at(0);
      return this.remove(model, options);
    },

    // Slice out a sub-array of models from the collection.
    slice: function() {
      return slice.apply(this.models, arguments);
    },

    // Get a model from the set by id.
    get: function(obj) {
      if (obj == null) return void 0;
      var id = this.modelId(this._isModel(obj) ? obj.attributes : obj);
      return this._byId[obj] || this._byId[id] || this._byId[obj.cid];
    },

    // Get the model at the given index.
    at: function(index) {
      if (index < 0) index += this.length;
      return this.models[index];
    },

    // Return models with matching attributes. Useful for simple cases of
    // `filter`.
    where: function(attrs, first) {
      return this[first ? 'find' : 'filter'](attrs);
    },

    // Return the first model with matching attributes. Useful for simple cases
    // of `find`.
    findWhere: function(attrs) {
      return this.where(attrs, true);
    },

    // Force the collection to re-sort itself. You don't need to call this under
    // normal circumstances, as the set will maintain sort order as each item
    // is added.
    sort: function(options) {
      var comparator = this.comparator;
      if (!comparator) throw new Error('Cannot sort a set without a comparator');
      options || (options = {});

      var length = comparator.length;
      if (_.isFunction(comparator)) comparator = _.bind(comparator, this);

      // Run sort based on type of `comparator`.
      if (length === 1 || _.isString(comparator)) {
        this.models = this.sortBy(comparator);
      } else {
        this.models.sort(comparator);
      }
      if (!options.silent) this.trigger('sort', this, options);
      return this;
    },

    // Pluck an attribute from each model in the collection.
    pluck: function(attr) {
      return _.invoke(this.models, 'get', attr);
    },

    // Fetch the default set of models for this collection, resetting the
    // collection when they arrive. If `reset: true` is passed, the response
    // data will be passed through the `reset` method instead of `set`.
    fetch: function(options) {
      options = _.extend({parse: true}, options);
      var success = options.success;
      var collection = this;
      options.success = function(resp) {
        var method = options.reset ? 'reset' : 'set';
        collection[method](resp, options);
        if (success) success.call(options.context, collection, resp, options);
        collection.trigger('sync', collection, resp, options);
      };
      wrapError(this, options);
      return this.sync('read', this, options);
    },

    // Create a new instance of a model in this collection. Add the model to the
    // collection immediately, unless `wait: true` is passed, in which case we
    // wait for the server to agree.
    create: function(model, options) {
      options = options ? _.clone(options) : {};
      var wait = options.wait;
      model = this._prepareModel(model, options);
      if (!model) return false;
      if (!wait) this.add(model, options);
      var collection = this;
      var success = options.success;
      options.success = function(model, resp, callbackOpts) {
        if (wait) collection.add(model, callbackOpts);
        if (success) success.call(callbackOpts.context, model, resp, callbackOpts);
      };
      model.save(null, options);
      return model;
    },

    // **parse** converts a response into a list of models to be added to the
    // collection. The default implementation is just to pass it through.
    parse: function(resp, options) {
      return resp;
    },

    // Create a new collection with an identical list of models as this one.
    clone: function() {
      return new this.constructor(this.models, {
        model: this.model,
        comparator: this.comparator
      });
    },

    // Define how to uniquely identify models in the collection.
    modelId: function (attrs) {
      return attrs[this.model.prototype.idAttribute || 'id'];
    },

    // Private method to reset all internal state. Called when the collection
    // is first initialized or reset.
    _reset: function() {
      this.length = 0;
      this.models = [];
      this._byId  = {};
    },

    // Prepare a hash of attributes (or other model) to be added to this
    // collection.
    _prepareModel: function(attrs, options) {
      if (this._isModel(attrs)) {
        if (!attrs.collection) attrs.collection = this;
        return attrs;
      }
      options = options ? _.clone(options) : {};
      options.collection = this;
      var model = new this.model(attrs, options);
      if (!model.validationError) return model;
      this.trigger('invalid', this, model.validationError, options);
      return false;
    },

    // Internal method called by both remove and set.
    _removeModels: function(models, options) {
      var removed = [];
      for (var i = 0; i < models.length; i++) {
        var model = this.get(models[i]);
        if (!model) continue;

        var index = this.indexOf(model);
        this.models.splice(index, 1);
        this.length--;

        if (!options.silent) {
          options.index = index;
          model.trigger('remove', model, this, options);
        }

        removed.push(model);
        this._removeReference(model, options);
      }
      return removed.length ? removed : false;
    },

    // Method for checking whether an object should be considered a model for
    // the purposes of adding to the collection.
    _isModel: function (model) {
      return model instanceof Model;
    },

    // Internal method to create a model's ties to a collection.
    _addReference: function(model, options) {
      this._byId[model.cid] = model;
      var id = this.modelId(model.attributes);
      if (id != null) this._byId[id] = model;
      model.on('all', this._onModelEvent, this);
    },

    // Internal method to sever a model's ties to a collection.
    _removeReference: function(model, options) {
      delete this._byId[model.cid];
      var id = this.modelId(model.attributes);
      if (id != null) delete this._byId[id];
      if (this === model.collection) delete model.collection;
      model.off('all', this._onModelEvent, this);
    },

    // Internal method called every time a model in the set fires an event.
    // Sets need to update their indexes when models change ids. All other
    // events simply proxy through. "add" and "remove" events that originate
    // in other collections are ignored.
    _onModelEvent: function(event, model, collection, options) {
      if ((event === 'add' || event === 'remove') && collection !== this) return;
      if (event === 'destroy') this.remove(model, options);
      if (event === 'change') {
        var prevId = this.modelId(model.previousAttributes());
        var id = this.modelId(model.attributes);
        if (prevId !== id) {
          if (prevId != null) delete this._byId[prevId];
          if (id != null) this._byId[id] = model;
        }
      }
      this.trigger.apply(this, arguments);
    }

  });

  // Underscore methods that we want to implement on the Collection.
  // 90% of the core usefulness of Backbone Collections is actually implemented
  // right here:
  var collectionMethods = { forEach: 3, each: 3, map: 3, collect: 3, reduce: 4,
      foldl: 4, inject: 4, reduceRight: 4, foldr: 4, find: 3, detect: 3, filter: 3,
      select: 3, reject: 3, every: 3, all: 3, some: 3, any: 3, include: 3, includes: 3,
      contains: 3, invoke: 0, max: 3, min: 3, toArray: 1, size: 1, first: 3,
      head: 3, take: 3, initial: 3, rest: 3, tail: 3, drop: 3, last: 3,
      without: 0, difference: 0, indexOf: 3, shuffle: 1, lastIndexOf: 3,
      isEmpty: 1, chain: 1, sample: 3, partition: 3, groupBy: 3, countBy: 3,
      sortBy: 3, indexBy: 3};

  // Mix in each Underscore method as a proxy to `Collection#models`.
  addUnderscoreMethods(Collection, collectionMethods, 'models');

  // Backbone.View
  // -------------

  // Backbone Views are almost more convention than they are actual code. A View
  // is simply a JavaScript object that represents a logical chunk of UI in the
  // DOM. This might be a single item, an entire list, a sidebar or panel, or
  // even the surrounding frame which wraps your whole app. Defining a chunk of
  // UI as a **View** allows you to define your DOM events declaratively, without
  // having to worry about render order ... and makes it easy for the view to
  // react to specific changes in the state of your models.

  // Creating a Backbone.View creates its initial element outside of the DOM,
  // if an existing element is not provided...
  var View = Backbone.View = function(options) {
    this.cid = _.uniqueId('view');
    _.extend(this, _.pick(options, viewOptions));
    this._ensureElement();
    this.initialize.apply(this, arguments);
  };

  // Cached regex to split keys for `delegate`.
  var delegateEventSplitter = /^(\S+)\s*(.*)$/;

  // List of view options to be set as properties.
  var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];

  // Set up all inheritable **Backbone.View** properties and methods.
  _.extend(View.prototype, Events, {

    // The default `tagName` of a View's element is `"div"`.
    tagName: 'div',

    // jQuery delegate for element lookup, scoped to DOM elements within the
    // current view. This should be preferred to global lookups where possible.
    $: function(selector) {
      return this.$el.find(selector);
    },

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

    // **render** is the core function that your view should override, in order
    // to populate its element (`this.el`), with the appropriate HTML. The
    // convention is for **render** to always return `this`.
    render: function() {
      return this;
    },

    // Remove this view by taking the element out of the DOM, and removing any
    // applicable Backbone.Events listeners.
    remove: function() {
      this._removeElement();
      this.stopListening();
      return this;
    },

    // Remove this view's element from the document and all event listeners
    // attached to it. Exposed for subclasses using an alternative DOM
    // manipulation API.
    _removeElement: function() {
      this.$el.remove();
    },

    // Change the view's element (`this.el` property) and re-delegate the
    // view's events on the new element.
    setElement: function(element) {
      this.undelegateEvents();
      this._setElement(element);
      this.delegateEvents();
      return this;
    },

    // Creates the `this.el` and `this.$el` references for this view using the
    // given `el`. `el` can be a CSS selector or an HTML string, a jQuery
    // context or an element. Subclasses can override this to utilize an
    // alternative DOM manipulation API and are only required to set the
    // `this.el` property.
    _setElement: function(el) {
      this.$el = el instanceof Backbone.$ ? el : Backbone.$(el);
      this.el = this.$el[0];
    },

    // Set callbacks, where `this.events` is a hash of
    //
    // *{"event selector": "callback"}*
    //
    //     {
    //       'mousedown .title':  'edit',
    //       'click .button':     'save',
    //       'click .open':       function(e) { ... }
    //     }
    //
    // pairs. Callbacks will be bound to the view, with `this` set properly.
    // Uses event delegation for efficiency.
    // Omitting the selector binds the event to `this.el`.
    delegateEvents: function(events) {
      events || (events = _.result(this, 'events'));
      if (!events) return this;
      this.undelegateEvents();
      for (var key in events) {
        var method = events[key];
        if (!_.isFunction(method)) method = this[method];
        if (!method) continue;
        var match = key.match(delegateEventSplitter);
        this.delegate(match[1], match[2], _.bind(method, this));
      }
      return this;
    },

    // Add a single event listener to the view's element (or a child element
    // using `selector`). This only works for delegate-able events: not `focus`,
    // `blur`, and not `change`, `submit`, and `reset` in Internet Explorer.
    delegate: function(eventName, selector, listener) {
      this.$el.on(eventName + '.delegateEvents' + this.cid, selector, listener);
      return this;
    },

    // Clears all callbacks previously bound to the view by `delegateEvents`.
    // You usually don't need to use this, but may wish to if you have multiple
    // Backbone views attached to the same DOM element.
    undelegateEvents: function() {
      if (this.$el) this.$el.off('.delegateEvents' + this.cid);
      return this;
    },

    // A finer-grained `undelegateEvents` for removing a single delegated event.
    // `selector` and `listener` are both optional.
    undelegate: function(eventName, selector, listener) {
      this.$el.off(eventName + '.delegateEvents' + this.cid, selector, listener);
      return this;
    },

    // Produces a DOM element to be assigned to your view. Exposed for
    // subclasses using an alternative DOM manipulation API.
    _createElement: function(tagName) {
      return document.createElement(tagName);
    },

    // Ensure that the View has a DOM element to render into.
    // If `this.el` is a string, pass it through `$()`, take the first
    // matching element, and re-assign it to `el`. Otherwise, create
    // an element from the `id`, `className` and `tagName` properties.
    _ensureElement: function() {
      if (!this.el) {
        var attrs = _.extend({}, _.result(this, 'attributes'));
        if (this.id) attrs.id = _.result(this, 'id');
        if (this.className) attrs['class'] = _.result(this, 'className');
        this.setElement(this._createElement(_.result(this, 'tagName')));
        this._setAttributes(attrs);
      } else {
        this.setElement(_.result(this, 'el'));
      }
    },

    // Set attributes from a hash on this view's element.  Exposed for
    // subclasses using an alternative DOM manipulation API.
    _setAttributes: function(attributes) {
      this.$el.attr(attributes);
    }

  });

  // Backbone.sync
  // -------------

  // Override this function to change the manner in which Backbone persists
  // models to the server. You will be passed the type of request, and the
  // model in question. By default, makes a RESTful Ajax request
  // to the model's `url()`. Some possible customizations could be:
  //
  // * Use `setTimeout` to batch rapid-fire updates into a single request.
  // * Send up the models as XML instead of JSON.
  // * Persist models via WebSockets instead of Ajax.
  //
  // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
  // as `POST`, with a `_method` parameter containing the true HTTP method,
  // as well as all requests with the body as `application/x-www-form-urlencoded`
  // instead of `application/json` with the model in a param named `model`.
  // Useful when interfacing with server-side languages like **PHP** that make
  // it difficult to read the body of `PUT` requests.
  Backbone.sync = function(method, model, options) {
    var type = methodMap[method];

    // Default options, unless specified.
    _.defaults(options || (options = {}), {
      emulateHTTP: Backbone.emulateHTTP,
      emulateJSON: Backbone.emulateJSON
    });

    // Default JSON-request options.
    var params = {type: type, dataType: 'json'};

    // Ensure that we have a URL.
    if (!options.url) {
      params.url = _.result(model, 'url') || urlError();
    }

    // Ensure that we have the appropriate request data.
    if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
      params.contentType = 'application/json';
      params.data = JSON.stringify(options.attrs || model.toJSON(options));
    }

    // For older servers, emulate JSON by encoding the request into an HTML-form.
    if (options.emulateJSON) {
      params.contentType = 'application/x-www-form-urlencoded';
      params.data = params.data ? {model: params.data} : {};
    }

    // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
    // And an `X-HTTP-Method-Override` header.
    if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
      params.type = 'POST';
      if (options.emulateJSON) params.data._method = type;
      var beforeSend = options.beforeSend;
      options.beforeSend = function(xhr) {
        xhr.setRequestHeader('X-HTTP-Method-Override', type);
        if (beforeSend) return beforeSend.apply(this, arguments);
      };
    }

    // Don't process data on a non-GET request.
    if (params.type !== 'GET' && !options.emulateJSON) {
      params.processData = false;
    }

    // Pass along `textStatus` and `errorThrown` from jQuery.
    var error = options.error;
    options.error = function(xhr, textStatus, errorThrown) {
      options.textStatus = textStatus;
      options.errorThrown = errorThrown;
      if (error) error.call(options.context, xhr, textStatus, errorThrown);
    };

    // Make the request, allowing the user to override any Ajax options.
    var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
    model.trigger('request', model, xhr, options);
    return xhr;
  };

  // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
  var methodMap = {
    'create': 'POST',
    'update': 'PUT',
    'patch':  'PATCH',
    'delete': 'DELETE',
    'read':   'GET'
  };

  // Set the default implementation of `Backbone.ajax` to proxy through to `$`.
  // Override this if you'd like to use a different library.
  Backbone.ajax = function() {
    return Backbone.$.ajax.apply(Backbone.$, arguments);
  };

  // Backbone.Router
  // ---------------

  // Routers map faux-URLs to actions, and fire events when routes are
  // matched. Creating a new one sets its `routes` hash, if not set statically.
  var Router = Backbone.Router = function(options) {
    options || (options = {});
    if (options.routes) this.routes = options.routes;
    this._bindRoutes();
    this.initialize.apply(this, arguments);
  };

  // Cached regular expressions for matching named param parts and splatted
  // parts of route strings.
  var optionalParam = /\((.*?)\)/g;
  var namedParam    = /(\(\?)?:\w+/g;
  var splatParam    = /\*\w+/g;
  var escapeRegExp  = /[\-{}\[\]+?.,\\\^$|#\s]/g;

  // Set up all inheritable **Backbone.Router** properties and methods.
  _.extend(Router.prototype, Events, {

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

    // Manually bind a single named route to a callback. For example:
    //
    //     this.route('search/:query/p:num', 'search', function(query, num) {
    //       ...
    //     });
    //
    route: function(route, name, callback) {
      if (!_.isRegExp(route)) route = this._routeToRegExp(route);
      if (_.isFunction(name)) {
        callback = name;
        name = '';
      }
      if (!callback) callback = this[name];
      var router = this;
      Backbone.history.route(route, function(fragment) {
        var args = router._extractParameters(route, fragment);
        if (router.execute(callback, args, name) !== false) {
          router.trigger.apply(router, ['route:' + name].concat(args));
          router.trigger('route', name, args);
          Backbone.history.trigger('route', router, name, args);
        }
      });
      return this;
    },

    // Execute a route handler with the provided parameters.  This is an
    // excellent place to do pre-route setup or post-route cleanup.
    execute: function(callback, args, name) {
      if (callback) callback.apply(this, args);
    },

    // Simple proxy to `Backbone.history` to save a fragment into the history.
    navigate: function(fragment, options) {
      Backbone.history.navigate(fragment, options);
      return this;
    },

    // Bind all defined routes to `Backbone.history`. We have to reverse the
    // order of the routes here to support behavior where the most general
    // routes can be defined at the bottom of the route map.
    _bindRoutes: function() {
      if (!this.routes) return;
      this.routes = _.result(this, 'routes');
      var route, routes = _.keys(this.routes);
      while ((route = routes.pop()) != null) {
        this.route(route, this.routes[route]);
      }
    },

    // Convert a route string into a regular expression, suitable for matching
    // against the current location hash.
    _routeToRegExp: function(route) {
      route = route.replace(escapeRegExp, '\\$&')
                   .replace(optionalParam, '(?:$1)?')
                   .replace(namedParam, function(match, optional) {
                     return optional ? match : '([^/?]+)';
                   })
                   .replace(splatParam, '([^?]*?)');
      return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$');
    },

    // Given a route, and a URL fragment that it matches, return the array of
    // extracted decoded parameters. Empty or unmatched parameters will be
    // treated as `null` to normalize cross-browser behavior.
    _extractParameters: function(route, fragment) {
      var params = route.exec(fragment).slice(1);
      return _.map(params, function(param, i) {
        // Don't decode the search params.
        if (i === params.length - 1) return param || null;
        return param ? decodeURIComponent(param) : null;
      });
    }

  });

  // Backbone.History
  // ----------------

  // Handles cross-browser history management, based on either
  // [pushState](http://diveintohtml5.info/history.html) and real URLs, or
  // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
  // and URL fragments. If the browser supports neither (old IE, natch),
  // falls back to polling.
  var History = Backbone.History = function() {
    this.handlers = [];
    this.checkUrl = _.bind(this.checkUrl, this);

    // Ensure that `History` can be used outside of the browser.
    if (typeof window !== 'undefined') {
      this.location = window.location;
      this.history = window.history;
    }
  };

  // Cached regex for stripping a leading hash/slash and trailing space.
  var routeStripper = /^[#\/]|\s+$/g;

  // Cached regex for stripping leading and trailing slashes.
  var rootStripper = /^\/+|\/+$/g;

  // Cached regex for stripping urls of hash.
  var pathStripper = /#.*$/;

  // Has the history handling already been started?
  History.started = false;

  // Set up all inheritable **Backbone.History** properties and methods.
  _.extend(History.prototype, Events, {

    // The default interval to poll for hash changes, if necessary, is
    // twenty times a second.
    interval: 50,

    // Are we at the app root?
    atRoot: function() {
      var path = this.location.pathname.replace(/[^\/]$/, '$&/');
      return path === this.root && !this.getSearch();
    },

    // Does the pathname match the root?
    matchRoot: function() {
      var path = this.decodeFragment(this.location.pathname);
      var root = path.slice(0, this.root.length - 1) + '/';
      return root === this.root;
    },

    // Unicode characters in `location.pathname` are percent encoded so they're
    // decoded for comparison. `%25` should not be decoded since it may be part
    // of an encoded parameter.
    decodeFragment: function(fragment) {
      return decodeURI(fragment.replace(/%25/g, '%2525'));
    },

    // In IE6, the hash fragment and search params are incorrect if the
    // fragment contains `?`.
    getSearch: function() {
      var match = this.location.href.replace(/#.*/, '').match(/\?.+/);
      return match ? match[0] : '';
    },

    // Gets the true hash value. Cannot use location.hash directly due to bug
    // in Firefox where location.hash will always be decoded.
    getHash: function(window) {
      var match = (window || this).location.href.match(/#(.*)$/);
      return match ? match[1] : '';
    },

    // Get the pathname and search params, without the root.
    getPath: function() {
      var path = this.decodeFragment(
        this.location.pathname + this.getSearch()
      ).slice(this.root.length - 1);
      return path.charAt(0) === '/' ? path.slice(1) : path;
    },

    // Get the cross-browser normalized URL fragment from the path or hash.
    getFragment: function(fragment) {
      if (fragment == null) {
        if (this._usePushState || !this._wantsHashChange) {
          fragment = this.getPath();
        } else {
          fragment = this.getHash();
        }
      }
      return fragment.replace(routeStripper, '');
    },

    // Start the hash change handling, returning `true` if the current URL matches
    // an existing route, and `false` otherwise.
    start: function(options) {
      if (History.started) throw new Error('Backbone.history has already been started');
      History.started = true;

      // Figure out the initial configuration. Do we need an iframe?
      // Is pushState desired ... is it available?
      this.options          = _.extend({root: '/'}, this.options, options);
      this.root             = this.options.root;
      this._wantsHashChange = this.options.hashChange !== false;
      this._hasHashChange   = 'onhashchange' in window && (document.documentMode === void 0 || document.documentMode > 7);
      this._useHashChange   = this._wantsHashChange && this._hasHashChange;
      this._wantsPushState  = !!this.options.pushState;
      this._hasPushState    = !!(this.history && this.history.pushState);
      this._usePushState    = this._wantsPushState && this._hasPushState;
      this.fragment         = this.getFragment();

      // Normalize root to always include a leading and trailing slash.
      this.root = ('/' + this.root + '/').replace(rootStripper, '/');

      // Transition from hashChange to pushState or vice versa if both are
      // requested.
      if (this._wantsHashChange && this._wantsPushState) {

        // If we've started off with a route from a `pushState`-enabled
        // browser, but we're currently in a browser that doesn't support it...
        if (!this._hasPushState && !this.atRoot()) {
          var root = this.root.slice(0, -1) || '/';
          this.location.replace(root + '#' + this.getPath());
          // Return immediately as browser will do redirect to new url
          return true;

        // Or if we've started out with a hash-based route, but we're currently
        // in a browser where it could be `pushState`-based instead...
        } else if (this._hasPushState && this.atRoot()) {
          this.navigate(this.getHash(), {replace: true});
        }

      }

      // Proxy an iframe to handle location events if the browser doesn't
      // support the `hashchange` event, HTML5 history, or the user wants
      // `hashChange` but not `pushState`.
      if (!this._hasHashChange && this._wantsHashChange && !this._usePushState) {
        this.iframe = document.createElement('iframe');
        this.iframe.src = 'javascript:0';
        this.iframe.style.display = 'none';
        this.iframe.tabIndex = -1;
        var body = document.body;
        // Using `appendChild` will throw on IE < 9 if the document is not ready.
        var iWindow = body.insertBefore(this.iframe, body.firstChild).contentWindow;
        iWindow.document.open();
        iWindow.document.close();
        iWindow.location.hash = '#' + this.fragment;
      }

      // Add a cross-platform `addEventListener` shim for older browsers.
      var addEventListener = window.addEventListener || function (eventName, listener) {
        return attachEvent('on' + eventName, listener);
      };

      // Depending on whether we're using pushState or hashes, and whether
      // 'onhashchange' is supported, determine how we check the URL state.
      if (this._usePushState) {
        addEventListener('popstate', this.checkUrl, false);
      } else if (this._useHashChange && !this.iframe) {
        addEventListener('hashchange', this.checkUrl, false);
      } else if (this._wantsHashChange) {
        this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
      }

      if (!this.options.silent) return this.loadUrl();
    },

    // Disable Backbone.history, perhaps temporarily. Not useful in a real app,
    // but possibly useful for unit testing Routers.
    stop: function() {
      // Add a cross-platform `removeEventListener` shim for older browsers.
      var removeEventListener = window.removeEventListener || function (eventName, listener) {
        return detachEvent('on' + eventName, listener);
      };

      // Remove window listeners.
      if (this._usePushState) {
        removeEventListener('popstate', this.checkUrl, false);
      } else if (this._useHashChange && !this.iframe) {
        removeEventListener('hashchange', this.checkUrl, false);
      }

      // Clean up the iframe if necessary.
      if (this.iframe) {
        document.body.removeChild(this.iframe);
        this.iframe = null;
      }

      // Some environments will throw when clearing an undefined interval.
      if (this._checkUrlInterval) clearInterval(this._checkUrlInterval);
      History.started = false;
    },

    // Add a route to be tested when the fragment changes. Routes added later
    // may override previous routes.
    route: function(route, callback) {
      this.handlers.unshift({route: route, callback: callback});
    },

    // Checks the current URL to see if it has changed, and if it has,
    // calls `loadUrl`, normalizing across the hidden iframe.
    checkUrl: function(e) {
      var current = this.getFragment();

      // If the user pressed the back button, the iframe's hash will have
      // changed and we should use that for comparison.
      if (current === this.fragment && this.iframe) {
        current = this.getHash(this.iframe.contentWindow);
      }

      if (current === this.fragment) return false;
      if (this.iframe) this.navigate(current);
      this.loadUrl();
    },

    // Attempt to load the current URL fragment. If a route succeeds with a
    // match, returns `true`. If no defined routes matches the fragment,
    // returns `false`.
    loadUrl: function(fragment) {
      // If the root doesn't match, no routes can match either.
      if (!this.matchRoot()) return false;
      fragment = this.fragment = this.getFragment(fragment);
      return _.some(this.handlers, function(handler) {
        if (handler.route.test(fragment)) {
          handler.callback(fragment);
          return true;
        }
      });
    },

    // Save a fragment into the hash history, or replace the URL state if the
    // 'replace' option is passed. You are responsible for properly URL-encoding
    // the fragment in advance.
    //
    // The options object can contain `trigger: true` if you wish to have the
    // route callback be fired (not usually desirable), or `replace: true`, if
    // you wish to modify the current URL without adding an entry to the history.
    navigate: function(fragment, options) {
      if (!History.started) return false;
      if (!options || options === true) options = {trigger: !!options};

      // Normalize the fragment.
      fragment = this.getFragment(fragment || '');

      // Don't include a trailing slash on the root.
      var root = this.root;
      if (fragment === '' || fragment.charAt(0) === '?') {
        root = root.slice(0, -1) || '/';
      }
      var url = root + fragment;

      // Strip the hash and decode for matching.
      fragment = this.decodeFragment(fragment.replace(pathStripper, ''));

      if (this.fragment === fragment) return;
      this.fragment = fragment;

      // If pushState is available, we use it to set the fragment as a real URL.
      if (this._usePushState) {
        this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);

      // If hash changes haven't been explicitly disabled, update the hash
      // fragment to store history.
      } else if (this._wantsHashChange) {
        this._updateHash(this.location, fragment, options.replace);
        if (this.iframe && (fragment !== this.getHash(this.iframe.contentWindow))) {
          var iWindow = this.iframe.contentWindow;

          // Opening and closing the iframe tricks IE7 and earlier to push a
          // history entry on hash-tag change.  When replace is true, we don't
          // want this.
          if (!options.replace) {
            iWindow.document.open();
            iWindow.document.close();
          }

          this._updateHash(iWindow.location, fragment, options.replace);
        }

      // If you've told us that you explicitly don't want fallback hashchange-
      // based history, then `navigate` becomes a page refresh.
      } else {
        return this.location.assign(url);
      }
      if (options.trigger) return this.loadUrl(fragment);
    },

    // Update the hash location, either replacing the current entry, or adding
    // a new one to the browser history.
    _updateHash: function(location, fragment, replace) {
      if (replace) {
        var href = location.href.replace(/(javascript:|#).*$/, '');
        location.replace(href + '#' + fragment);
      } else {
        // Some browsers require that `hash` contains a leading #.
        location.hash = '#' + fragment;
      }
    }

  });

  // Create the default Backbone.history.
  Backbone.history = new History;

  // Helpers
  // -------

  // Helper function to correctly set up the prototype chain for subclasses.
  // Similar to `goog.inherits`, but uses a hash of prototype properties and
  // class properties to be extended.
  var extend = function(protoProps, staticProps) {
    var parent = this;
    var child;

    // The constructor function for the new subclass is either defined by you
    // (the "constructor" property in your `extend` definition), or defaulted
    // by us to simply call the parent constructor.
    if (protoProps && _.has(protoProps, 'constructor')) {
      child = protoProps.constructor;
    } else {
      child = function(){ return parent.apply(this, arguments); };
    }

    // Add static properties to the constructor function, if supplied.
    _.extend(child, parent, staticProps);

    // Set the prototype chain to inherit from `parent`, without calling
    // `parent` constructor function.
    var Surrogate = function(){ this.constructor = child; };
    Surrogate.prototype = parent.prototype;
    child.prototype = new Surrogate;

    // Add prototype properties (instance properties) to the subclass,
    // if supplied.
    if (protoProps) _.extend(child.prototype, protoProps);

    // Set a convenience property in case the parent's prototype is needed
    // later.
    child.__super__ = parent.prototype;

    return child;
  };

  // Set up inheritance for the model, collection, router, view and history.
  Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;

  // Throw an error when a URL is needed, and none is supplied.
  var urlError = function() {
    throw new Error('A "url" property or function must be specified');
  };

  // Wrap an optional error callback with a fallback error event.
  var wrapError = function(model, options) {
    var error = options.error;
    options.error = function(resp) {
      if (error) error.call(options.context, model, resp, options);
      model.trigger('error', model, resp, options);
    };
  };

  return Backbone;

}));

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})

},{"jquery":"jquery","underscore":"underscore"}],"browserify/lib/_empty":[function(require,module,exports){

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

// resolves . and .. elements in a path array with directory names there
// must be no slashes, empty elements, or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
  // if the path tries to go above the root, `up` ends up > 0
  var up = 0;
  for (var i = parts.length - 1; i >= 0; i--) {
    var last = parts[i];
    if (last === '.') {
      parts.splice(i, 1);
    } else if (last === '..') {
      parts.splice(i, 1);
      up++;
    } else if (up) {
      parts.splice(i, 1);
      up--;
    }
  }

  // if the path is allowed to go above the root, restore leading ..s
  if (allowAboveRoot) {
    for (; up--; up) {
      parts.unshift('..');
    }
  }

  return parts;
}

// Split a filename into [root, dir, basename, ext], unix version
// 'root' is just a slash, or nothing.
var splitPathRe =
    /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
var splitPath = function(filename) {
  return splitPathRe.exec(filename).slice(1);
};

// path.resolve([from ...], to)
// posix version
exports.resolve = function() {
  var resolvedPath = '',
      resolvedAbsolute = false;

  for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
    var path = (i >= 0) ? arguments[i] : process.cwd();

    // Skip empty and invalid entries
    if (typeof path !== 'string') {
      throw new TypeError('Arguments to path.resolve must be strings');
    } else if (!path) {
      continue;
    }

    resolvedPath = path + '/' + resolvedPath;
    resolvedAbsolute = path.charAt(0) === '/';
  }

  // At this point the path should be resolved to a full absolute path, but
  // handle relative paths to be safe (might happen when process.cwd() fails)

  // Normalize the path
  resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
    return !!p;
  }), !resolvedAbsolute).join('/');

  return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
};

// path.normalize(path)
// posix version
exports.normalize = function(path) {
  var isAbsolute = exports.isAbsolute(path),
      trailingSlash = substr(path, -1) === '/';

  // Normalize the path
  path = normalizeArray(filter(path.split('/'), function(p) {
    return !!p;
  }), !isAbsolute).join('/');

  if (!path && !isAbsolute) {
    path = '.';
  }
  if (path && trailingSlash) {
    path += '/';
  }

  return (isAbsolute ? '/' : '') + path;
};

// posix version
exports.isAbsolute = function(path) {
  return path.charAt(0) === '/';
};

// posix version
exports.join = function() {
  var paths = Array.prototype.slice.call(arguments, 0);
  return exports.normalize(filter(paths, function(p, index) {
    if (typeof p !== 'string') {
      throw new TypeError('Arguments to path.join must be strings');
    }
    return p;
  }).join('/'));
};


// path.relative(from, to)
// posix version
exports.relative = function(from, to) {
  from = exports.resolve(from).substr(1);
  to = exports.resolve(to).substr(1);

  function trim(arr) {
    var start = 0;
    for (; start < arr.length; start++) {
      if (arr[start] !== '') break;
    }

    var end = arr.length - 1;
    for (; end >= 0; end--) {
      if (arr[end] !== '') break;
    }

    if (start > end) return [];
    return arr.slice(start, end - start + 1);
  }

  var fromParts = trim(from.split('/'));
  var toParts = trim(to.split('/'));

  var length = Math.min(fromParts.length, toParts.length);
  var samePartsLength = length;
  for (var i = 0; i < length; i++) {
    if (fromParts[i] !== toParts[i]) {
      samePartsLength = i;
      break;
    }
  }

  var outputParts = [];
  for (var i = samePartsLength; i < fromParts.length; i++) {
    outputParts.push('..');
  }

  outputParts = outputParts.concat(toParts.slice(samePartsLength));

  return outputParts.join('/');
};

exports.sep = '/';
exports.delimiter = ':';

exports.dirname = function(path) {
  var result = splitPath(path),
      root = result[0],
      dir = result[1];

  if (!root && !dir) {
    // No dirname whatsoever
    return '.';
  }

  if (dir) {
    // It has a dirname, strip trailing slash
    dir = dir.substr(0, dir.length - 1);
  }

  return root + dir;
};


exports.basename = function(path, ext) {
  var f = splitPath(path)[2];
  // TODO: make this comparison case-insensitive on windows?
  if (ext && f.substr(-1 * ext.length) === ext) {
    f = f.substr(0, f.length - ext.length);
  }
  return f;
};


exports.extname = function(path) {
  return splitPath(path)[3];
};

function filter (xs, f) {
    if (xs.filter) return xs.filter(f);
    var res = [];
    for (var i = 0; i < xs.length; i++) {
        if (f(xs[i], i, xs)) res.push(xs[i]);
    }
    return res;
}

// String.prototype.substr - negative index don't work in IE8
var substr = 'ab'.substr(-1) === 'b'
    ? function (str, start, len) { return str.substr(start, len) }
    : function (str, start, len) {
        if (start < 0) start = str.length + start;
        return str.substr(start, len);
    }
;

}).call(this,require('_process'))

},{"_process":"browserify/node_modules/process/browser"}],"browserify/node_modules/process/browser":[function(require,module,exports){
// shim for using process in browser

var process = module.exports = {};
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;

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

function drainQueue() {
    if (draining) {
        return;
    }
    var timeout = setTimeout(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;
    clearTimeout(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) {
        setTimeout(drainQueue, 0);
    }
};

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

function noop() {}

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

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

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

},{}],"browserify/node_modules/vm-browserify/index":[function(require,module,exports){
var indexOf = require('indexof');

var Object_keys = function (obj) {
    if (Object.keys) return Object.keys(obj)
    else {
        var res = [];
        for (var key in obj) res.push(key)
        return res;
    }
};

var forEach = function (xs, fn) {
    if (xs.forEach) return xs.forEach(fn)
    else for (var i = 0; i < xs.length; i++) {
        fn(xs[i], i, xs);
    }
};

var defineProp = (function() {
    try {
        Object.defineProperty({}, '_', {});
        return function(obj, name, value) {
            Object.defineProperty(obj, name, {
                writable: true,
                enumerable: false,
                configurable: true,
                value: value
            })
        };
    } catch(e) {
        return function(obj, name, value) {
            obj[name] = value;
        };
    }
}());

var globals = ['Array', 'Boolean', 'Date', 'Error', 'EvalError', 'Function',
'Infinity', 'JSON', 'Math', 'NaN', 'Number', 'Object', 'RangeError',
'ReferenceError', 'RegExp', 'String', 'SyntaxError', 'TypeError', 'URIError',
'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'escape',
'eval', 'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'undefined', 'unescape'];

function Context() {}
Context.prototype = {};

var Script = exports.Script = function NodeScript (code) {
    if (!(this instanceof Script)) return new Script(code);
    this.code = code;
};

Script.prototype.runInContext = function (context) {
    if (!(context instanceof Context)) {
        throw new TypeError("needs a 'context' argument.");
    }
    
    var iframe = document.createElement('iframe');
    if (!iframe.style) iframe.style = {};
    iframe.style.display = 'none';
    
    document.body.appendChild(iframe);
    
    var win = iframe.contentWindow;
    var wEval = win.eval, wExecScript = win.execScript;

    if (!wEval && wExecScript) {
        // win.eval() magically appears when this is called in IE:
        wExecScript.call(win, 'null');
        wEval = win.eval;
    }
    
    forEach(Object_keys(context), function (key) {
        win[key] = context[key];
    });
    forEach(globals, function (key) {
        if (context[key]) {
            win[key] = context[key];
        }
    });
    
    var winKeys = Object_keys(win);

    var res = wEval.call(win, this.code);
    
    forEach(Object_keys(win), function (key) {
        // Avoid copying circular objects like `top` and `window` by only
        // updating existing context properties or new properties in the `win`
        // that was only introduced after the eval.
        if (key in context || indexOf(winKeys, key) === -1) {
            context[key] = win[key];
        }
    });

    forEach(globals, function (key) {
        if (!(key in context)) {
            defineProp(context, key, win[key]);
        }
    });
    
    document.body.removeChild(iframe);
    
    return res;
};

Script.prototype.runInThisContext = function () {
    return eval(this.code); // maybe...
};

Script.prototype.runInNewContext = function (context) {
    var ctx = Script.createContext(context);
    var res = this.runInContext(ctx);

    forEach(Object_keys(ctx), function (key) {
        context[key] = ctx[key];
    });

    return res;
};

forEach(Object_keys(Script.prototype), function (name) {
    exports[name] = Script[name] = function (code) {
        var s = Script(code);
        return s[name].apply(s, [].slice.call(arguments, 1));
    };
});

exports.createScript = function (code) {
    return exports.Script(code);
};

exports.createContext = Script.createContext = function (context) {
    var copy = new Context();
    if(typeof context === 'object') {
        forEach(Object_keys(context), function (key) {
            copy[key] = context[key];
        });
    }
    return copy;
};

},{"indexof":"browserify/node_modules/vm-browserify/node_modules/indexof/index"}],"browserify/node_modules/vm-browserify/node_modules/indexof/index":[function(require,module,exports){

var indexOf = [].indexOf;

module.exports = function(arr, obj){
  if (indexOf) return arr.indexOf(obj);
  for (var i = 0; i < arr.length; ++i) {
    if (arr[i] === obj) return i;
  }
  return -1;
};
},{}],"coffee-script":[function(require,module,exports){
(function (process,global){
// Generated by CoffeeScript 1.10.0
(function() {
  var Lexer, SourceMap, base, compile, ext, formatSourcePosition, fs, getSourceMap, helpers, i, len, lexer, parser, path, ref, sourceMaps, vm, withPrettyErrors,
    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; };

  fs = require('fs');

  vm = require('vm');

  path = require('path');

  Lexer = require('./lexer').Lexer;

  parser = require('./parser').parser;

  helpers = require('./helpers');

  SourceMap = require('./sourcemap');

  exports.VERSION = '1.10.0';

  exports.FILE_EXTENSIONS = ['.coffee', '.litcoffee', '.coffee.md'];

  exports.helpers = helpers;

  withPrettyErrors = function(fn) {
    return function(code, options) {
      var err, error;
      if (options == null) {
        options = {};
      }
      try {
        return fn.call(this, code, options);
      } catch (error) {
        err = error;
        if (typeof code !== 'string') {
          throw err;
        }
        throw helpers.updateSyntaxError(err, code, options.filename);
      }
    };
  };

  exports.compile = compile = withPrettyErrors(function(code, options) {
    var answer, currentColumn, currentLine, extend, fragment, fragments, header, i, js, len, map, merge, newLines, token, tokens;
    merge = helpers.merge, extend = helpers.extend;
    options = extend({}, options);
    if (options.sourceMap) {
      map = new SourceMap;
    }
    tokens = lexer.tokenize(code, options);
    options.referencedVars = (function() {
      var i, len, results;
      results = [];
      for (i = 0, len = tokens.length; i < len; i++) {
        token = tokens[i];
        if (token.variable) {
          results.push(token[1]);
        }
      }
      return results;
    })();
    fragments = parser.parse(tokens).compileToFragments(options);
    currentLine = 0;
    if (options.header) {
      currentLine += 1;
    }
    if (options.shiftLine) {
      currentLine += 1;
    }
    currentColumn = 0;
    js = "";
    for (i = 0, len = fragments.length; i < len; i++) {
      fragment = fragments[i];
      if (options.sourceMap) {
        if (fragment.locationData && !/^[;\s]*$/.test(fragment.code)) {
          map.add([fragment.locationData.first_line, fragment.locationData.first_column], [currentLine, currentColumn], {
            noReplace: true
          });
        }
        newLines = helpers.count(fragment.code, "\n");
        currentLine += newLines;
        if (newLines) {
          currentColumn = fragment.code.length - (fragment.code.lastIndexOf("\n") + 1);
        } else {
          currentColumn += fragment.code.length;
        }
      }
      js += fragment.code;
    }
    if (options.header) {
      header = "Generated by CoffeeScript " + this.VERSION;
      js = "// " + header + "\n" + js;
    }
    if (options.sourceMap) {
      answer = {
        js: js
      };
      answer.sourceMap = map;
      answer.v3SourceMap = map.generate(options, code);
      return answer;
    } else {
      return js;
    }
  });

  exports.tokens = withPrettyErrors(function(code, options) {
    return lexer.tokenize(code, options);
  });

  exports.nodes = withPrettyErrors(function(source, options) {
    if (typeof source === 'string') {
      return parser.parse(lexer.tokenize(source, options));
    } else {
      return parser.parse(source);
    }
  });

  exports.run = function(code, options) {
    var answer, dir, mainModule, ref;
    if (options == null) {
      options = {};
    }
    mainModule = require.main;
    mainModule.filename = process.argv[1] = options.filename ? fs.realpathSync(options.filename) : '.';
    mainModule.moduleCache && (mainModule.moduleCache = {});
    dir = options.filename ? path.dirname(fs.realpathSync(options.filename)) : fs.realpathSync('.');
    mainModule.paths = require('module')._nodeModulePaths(dir);
    if (!helpers.isCoffee(mainModule.filename) || require.extensions) {
      answer = compile(code, options);
      code = (ref = answer.js) != null ? ref : answer;
    }
    return mainModule._compile(code, mainModule.filename);
  };

  exports["eval"] = function(code, options) {
    var Module, _module, _require, createContext, i, isContext, js, k, len, o, r, ref, ref1, ref2, ref3, sandbox, v;
    if (options == null) {
      options = {};
    }
    if (!(code = code.trim())) {
      return;
    }
    createContext = (ref = vm.Script.createContext) != null ? ref : vm.createContext;
    isContext = (ref1 = vm.isContext) != null ? ref1 : function(ctx) {
      return options.sandbox instanceof createContext().constructor;
    };
    if (createContext) {
      if (options.sandbox != null) {
        if (isContext(options.sandbox)) {
          sandbox = options.sandbox;
        } else {
          sandbox = createContext();
          ref2 = options.sandbox;
          for (k in ref2) {
            if (!hasProp.call(ref2, k)) continue;
            v = ref2[k];
            sandbox[k] = v;
          }
        }
        sandbox.global = sandbox.root = sandbox.GLOBAL = sandbox;
      } else {
        sandbox = global;
      }
      sandbox.__filename = options.filename || 'eval';
      sandbox.__dirname = path.dirname(sandbox.__filename);
      if (!(sandbox !== global || sandbox.module || sandbox.require)) {
        Module = require('module');
        sandbox.module = _module = new Module(options.modulename || 'eval');
        sandbox.require = _require = function(path) {
          return Module._load(path, _module, true);
        };
        _module.filename = sandbox.__filename;
        ref3 = Object.getOwnPropertyNames(require);
        for (i = 0, len = ref3.length; i < len; i++) {
          r = ref3[i];
          if (r !== 'paths' && r !== 'arguments' && r !== 'caller') {
            _require[r] = require[r];
          }
        }
        _require.paths = _module.paths = Module._nodeModulePaths(process.cwd());
        _require.resolve = function(request) {
          return Module._resolveFilename(request, _module);
        };
      }
    }
    o = {};
    for (k in options) {
      if (!hasProp.call(options, k)) continue;
      v = options[k];
      o[k] = v;
    }
    o.bare = true;
    js = compile(code, o);
    if (sandbox === global) {
      return vm.runInThisContext(js);
    } else {
      return vm.runInContext(js, sandbox);
    }
  };

  exports.register = function() {
    return require('./register');
  };

  if (require.extensions) {
    ref = this.FILE_EXTENSIONS;
    for (i = 0, len = ref.length; i < len; i++) {
      ext = ref[i];
      if ((base = require.extensions)[ext] == null) {
        base[ext] = function() {
          throw new Error("Use CoffeeScript.register() or require the coffee-script/register module to require " + ext + " files.");
        };
      }
    }
  }

  exports._compileFile = function(filename, sourceMap) {
    var answer, err, error, raw, stripped;
    if (sourceMap == null) {
      sourceMap = false;
    }
    raw = fs.readFileSync(filename, 'utf8');
    stripped = raw.charCodeAt(0) === 0xFEFF ? raw.substring(1) : raw;
    try {
      answer = compile(stripped, {
        filename: filename,
        sourceMap: sourceMap,
        literate: helpers.isLiterate(filename)
      });
    } catch (error) {
      err = error;
      throw helpers.updateSyntaxError(err, stripped, filename);
    }
    return answer;
  };

  lexer = new Lexer;

  parser.lexer = {
    lex: function() {
      var tag, token;
      token = parser.tokens[this.pos++];
      if (token) {
        tag = token[0], this.yytext = token[1], this.yylloc = token[2];
        parser.errorToken = token.origin || token;
        this.yylineno = this.yylloc.first_line;
      } else {
        tag = '';
      }
      return tag;
    },
    setInput: function(tokens) {
      parser.tokens = tokens;
      return this.pos = 0;
    },
    upcomingInput: function() {
      return "";
    }
  };

  parser.yy = require('./nodes');

  parser.yy.parseError = function(message, arg) {
    var errorLoc, errorTag, errorText, errorToken, token, tokens;
    token = arg.token;
    errorToken = parser.errorToken, tokens = parser.tokens;
    errorTag = errorToken[0], errorText = errorToken[1], errorLoc = errorToken[2];
    errorText = (function() {
      switch (false) {
        case errorToken !== tokens[tokens.length - 1]:
          return 'end of input';
        case errorTag !== 'INDENT' && errorTag !== 'OUTDENT':
          return 'indentation';
        case errorTag !== 'IDENTIFIER' && errorTag !== 'NUMBER' && errorTag !== 'STRING' && errorTag !== 'STRING_START' && errorTag !== 'REGEX' && errorTag !== 'REGEX_START':
          return errorTag.replace(/_START$/, '').toLowerCase();
        default:
          return helpers.nameWhitespaceCharacter(errorText);
      }
    })();
    return helpers.throwSyntaxError("unexpected " + errorText, errorLoc);
  };

  formatSourcePosition = function(frame, getSourceMapping) {
    var as, column, fileLocation, fileName, functionName, isConstructor, isMethodCall, line, methodName, source, tp, typeName;
    fileName = void 0;
    fileLocation = '';
    if (frame.isNative()) {
      fileLocation = "native";
    } else {
      if (frame.isEval()) {
        fileName = frame.getScriptNameOrSourceURL();
        if (!fileName) {
          fileLocation = (frame.getEvalOrigin()) + ", ";
        }
      } else {
        fileName = frame.getFileName();
      }
      fileName || (fileName = "<anonymous>");
      line = frame.getLineNumber();
      column = frame.getColumnNumber();
      source = getSourceMapping(fileName, line, column);
      fileLocation = source ? fileName + ":" + source[0] + ":" + source[1] : fileName + ":" + line + ":" + column;
    }
    functionName = frame.getFunctionName();
    isConstructor = frame.isConstructor();
    isMethodCall = !(frame.isToplevel() || isConstructor);
    if (isMethodCall) {
      methodName = frame.getMethodName();
      typeName = frame.getTypeName();
      if (functionName) {
        tp = as = '';
        if (typeName && functionName.indexOf(typeName)) {
          tp = typeName + ".";
        }
        if (methodName && functionName.indexOf("." + methodName) !== functionName.length - methodName.length - 1) {
          as = " [as " + methodName + "]";
        }
        return "" + tp + functionName + as + " (" + fileLocation + ")";
      } else {
        return typeName + "." + (methodName || '<anonymous>') + " (" + fileLocation + ")";
      }
    } else if (isConstructor) {
      return "new " + (functionName || '<anonymous>') + " (" + fileLocation + ")";
    } else if (functionName) {
      return functionName + " (" + fileLocation + ")";
    } else {
      return fileLocation;
    }
  };

  sourceMaps = {};

  getSourceMap = function(filename) {
    var answer, ref1;
    if (sourceMaps[filename]) {
      return sourceMaps[filename];
    }
    if (ref1 = path != null ? path.extname(filename) : void 0, indexOf.call(exports.FILE_EXTENSIONS, ref1) < 0) {
      return;
    }
    answer = exports._compileFile(filename, true);
    return sourceMaps[filename] = answer.sourceMap;
  };

  Error.prepareStackTrace = function(err, stack) {
    var frame, frames, getSourceMapping;
    getSourceMapping = function(filename, line, column) {
      var answer, sourceMap;
      sourceMap = getSourceMap(filename);
      if (sourceMap) {
        answer = sourceMap.sourceLocation([line - 1, column - 1]);
      }
      if (answer) {
        return [answer[0] + 1, answer[1] + 1];
      } else {
        return null;
      }
    };
    frames = (function() {
      var j, len1, results;
      results = [];
      for (j = 0, len1 = stack.length; j < len1; j++) {
        frame = stack[j];
        if (frame.getFunction() === exports.run) {
          break;
        }
        results.push("  at " + (formatSourcePosition(frame, getSourceMapping)));
      }
      return results;
    })();
    return (err.toString()) + "\n" + (frames.join('\n')) + "\n";
  };

}).call(this);

}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})

},{"./helpers":"coffee-script/lib/coffee-script/helpers","./lexer":"coffee-script/lib/coffee-script/lexer","./nodes":"coffee-script/lib/coffee-script/nodes","./parser":"coffee-script/lib/coffee-script/parser","./register":"coffee-script/lib/coffee-script/register","./sourcemap":"coffee-script/lib/coffee-script/sourcemap","_process":"browserify/node_modules/process/browser","fs":"browserify/lib/_empty","module":"browserify/lib/_empty","path":"browserify/node_modules/path-browserify/index","vm":"browserify/node_modules/vm-browserify/index"}],"coffee-script/lib/coffee-script/helpers":[function(require,module,exports){
(function (process){
// Generated by CoffeeScript 1.10.0
(function() {
  var buildLocationData, extend, flatten, ref, repeat, syntaxErrorToString;

  exports.starts = function(string, literal, start) {
    return literal === string.substr(start, literal.length);
  };

  exports.ends = function(string, literal, back) {
    var len;
    len = literal.length;
    return literal === string.substr(string.length - len - (back || 0), len);
  };

  exports.repeat = repeat = function(str, n) {
    var res;
    res = '';
    while (n > 0) {
      if (n & 1) {
        res += str;
      }
      n >>>= 1;
      str += str;
    }
    return res;
  };

  exports.compact = function(array) {
    var i, item, len1, results;
    results = [];
    for (i = 0, len1 = array.length; i < len1; i++) {
      item = array[i];
      if (item) {
        results.push(item);
      }
    }
    return results;
  };

  exports.count = function(string, substr) {
    var num, pos;
    num = pos = 0;
    if (!substr.length) {
      return 1 / 0;
    }
    while (pos = 1 + string.indexOf(substr, pos)) {
      num++;
    }
    return num;
  };

  exports.merge = function(options, overrides) {
    return extend(extend({}, options), overrides);
  };

  extend = exports.extend = function(object, properties) {
    var key, val;
    for (key in properties) {
      val = properties[key];
      object[key] = val;
    }
    return object;
  };

  exports.flatten = flatten = function(array) {
    var element, flattened, i, len1;
    flattened = [];
    for (i = 0, len1 = array.length; i < len1; i++) {
      element = array[i];
      if ('[object Array]' === Object.prototype.toString.call(element)) {
        flattened = flattened.concat(flatten(element));
      } else {
        flattened.push(element);
      }
    }
    return flattened;
  };

  exports.del = function(obj, key) {
    var val;
    val = obj[key];
    delete obj[key];
    return val;
  };

  exports.some = (ref = Array.prototype.some) != null ? ref : function(fn) {
    var e, i, len1;
    for (i = 0, len1 = this.length; i < len1; i++) {
      e = this[i];
      if (fn(e)) {
        return true;
      }
    }
    return false;
  };

  exports.invertLiterate = function(code) {
    var line, lines, maybe_code;
    maybe_code = true;
    lines = (function() {
      var i, len1, ref1, results;
      ref1 = code.split('\n');
      results = [];
      for (i = 0, len1 = ref1.length; i < len1; i++) {
        line = ref1[i];
        if (maybe_code && /^([ ]{4}|[ ]{0,3}\t)/.test(line)) {
          results.push(line);
        } else if (maybe_code = /^\s*$/.test(line)) {
          results.push(line);
        } else {
          results.push('# ' + line);
        }
      }
      return results;
    })();
    return lines.join('\n');
  };

  buildLocationData = function(first, last) {
    if (!last) {
      return first;
    } else {
      return {
        first_line: first.first_line,
        first_column: first.first_column,
        last_line: last.last_line,
        last_column: last.last_column
      };
    }
  };

  exports.addLocationDataFn = function(first, last) {
    return function(obj) {
      if (((typeof obj) === 'object') && (!!obj['updateLocationDataIfMissing'])) {
        obj.updateLocationDataIfMissing(buildLocationData(first, last));
      }
      return obj;
    };
  };

  exports.locationDataToString = function(obj) {
    var locationData;
    if (("2" in obj) && ("first_line" in obj[2])) {
      locationData = obj[2];
    } else if ("first_line" in obj) {
      locationData = obj;
    }
    if (locationData) {
      return ((locationData.first_line + 1) + ":" + (locationData.first_column + 1) + "-") + ((locationData.last_line + 1) + ":" + (locationData.last_column + 1));
    } else {
      return "No location data";
    }
  };

  exports.baseFileName = function(file, stripExt, useWinPathSep) {
    var parts, pathSep;
    if (stripExt == null) {
      stripExt = false;
    }
    if (useWinPathSep == null) {
      useWinPathSep = false;
    }
    pathSep = useWinPathSep ? /\\|\// : /\//;
    parts = file.split(pathSep);
    file = parts[parts.length - 1];
    if (!(stripExt && file.indexOf('.') >= 0)) {
      return file;
    }
    parts = file.split('.');
    parts.pop();
    if (parts[parts.length - 1] === 'coffee' && parts.length > 1) {
      parts.pop();
    }
    return parts.join('.');
  };

  exports.isCoffee = function(file) {
    return /\.((lit)?coffee|coffee\.md)$/.test(file);
  };

  exports.isLiterate = function(file) {
    return /\.(litcoffee|coffee\.md)$/.test(file);
  };

  exports.throwSyntaxError = function(message, location) {
    var error;
    error = new SyntaxError(message);
    error.location = location;
    error.toString = syntaxErrorToString;
    error.stack = error.toString();
    throw error;
  };

  exports.updateSyntaxError = function(error, code, filename) {
    if (error.toString === syntaxErrorToString) {
      error.code || (error.code = code);
      error.filename || (error.filename = filename);
      error.stack = error.toString();
    }
    return error;
  };

  syntaxErrorToString = function() {
    var codeLine, colorize, colorsEnabled, end, filename, first_column, first_line, last_column, last_line, marker, ref1, ref2, ref3, ref4, start;
    if (!(this.code && this.location)) {
      return Error.prototype.toString.call(this);
    }
    ref1 = this.location, first_line = ref1.first_line, first_column = ref1.first_column, last_line = ref1.last_line, last_column = ref1.last_column;
    if (last_line == null) {
      last_line = first_line;
    }
    if (last_column == null) {
      last_column = first_column;
    }
    filename = this.filename || '[stdin]';
    codeLine = this.code.split('\n')[first_line];
    start = first_column;
    end = first_line === last_line ? last_column + 1 : codeLine.length;
    marker = codeLine.slice(0, start).replace(/[^\s]/g, ' ') + repeat('^', end - start);
    if (typeof process !== "undefined" && process !== null) {
      colorsEnabled = ((ref2 = process.stdout) != null ? ref2.isTTY : void 0) && !((ref3 = process.env) != null ? ref3.NODE_DISABLE_COLORS : void 0);
    }
    if ((ref4 = this.colorful) != null ? ref4 : colorsEnabled) {
      colorize = function(str) {
        return "\x1B[1;31m" + str + "\x1B[0m";
      };
      codeLine = codeLine.slice(0, start) + colorize(codeLine.slice(start, end)) + codeLine.slice(end);
      marker = colorize(marker);
    }
    return filename + ":" + (first_line + 1) + ":" + (first_column + 1) + ": error: " + this.message + "\n" + codeLine + "\n" + marker;
  };

  exports.nameWhitespaceCharacter = function(string) {
    switch (string) {
      case ' ':
        return 'space';
      case '\n':
        return 'newline';
      case '\r':
        return 'carriage return';
      case '\t':
        return 'tab';
      default:
        return string;
    }
  };

}).call(this);

}).call(this,require('_process'))

},{"_process":"browserify/node_modules/process/browser"}],"coffee-script/lib/coffee-script/lexer":[function(require,module,exports){
// Generated by CoffeeScript 1.10.0
(function() {
  var BOM, BOOL, CALLABLE, CODE, COFFEE_ALIASES, COFFEE_ALIAS_MAP, COFFEE_KEYWORDS, COMMENT, COMPARE, COMPOUND_ASSIGN, HERECOMMENT_ILLEGAL, HEREDOC_DOUBLE, HEREDOC_INDENT, HEREDOC_SINGLE, HEREGEX, HEREGEX_OMIT, IDENTIFIER, INDENTABLE_CLOSERS, INDEXABLE, INVALID_ESCAPE, INVERSES, JSTOKEN, JS_FORBIDDEN, JS_KEYWORDS, LEADING_BLANK_LINE, LINE_BREAK, LINE_CONTINUER, LOGIC, Lexer, MATH, MULTI_DENT, NOT_REGEX, NUMBER, OPERATOR, POSSIBLY_DIVISION, REGEX, REGEX_FLAGS, REGEX_ILLEGAL, RELATION, RESERVED, Rewriter, SHIFT, SIMPLE_STRING_OMIT, STRICT_PROSCRIBED, STRING_DOUBLE, STRING_OMIT, STRING_SINGLE, STRING_START, TRAILING_BLANK_LINE, TRAILING_SPACES, UNARY, UNARY_MATH, VALID_FLAGS, WHITESPACE, compact, count, invertLiterate, key, locationDataToString, ref, ref1, repeat, starts, throwSyntaxError,
    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; };

  ref = require('./rewriter'), Rewriter = ref.Rewriter, INVERSES = ref.INVERSES;

  ref1 = require('./helpers'), count = ref1.count, starts = ref1.starts, compact = ref1.compact, repeat = ref1.repeat, invertLiterate = ref1.invertLiterate, locationDataToString = ref1.locationDataToString, throwSyntaxError = ref1.throwSyntaxError;

  exports.Lexer = Lexer = (function() {
    function Lexer() {}

    Lexer.prototype.tokenize = function(code, opts) {
      var consumed, end, i, ref2;
      if (opts == null) {
        opts = {};
      }
      this.literate = opts.literate;
      this.indent = 0;
      this.baseIndent = 0;
      this.indebt = 0;
      this.outdebt = 0;
      this.indents = [];
      this.ends = [];
      this.tokens = [];
      this.seenFor = false;
      this.chunkLine = opts.line || 0;
      this.chunkColumn = opts.column || 0;
      code = this.clean(code);
      i = 0;
      while (this.chunk = code.slice(i)) {
        consumed = this.identifierToken() || this.commentToken() || this.whitespaceToken() || this.lineToken() || this.stringToken() || this.numberToken() || this.regexToken() || this.jsToken() || this.literalToken();
        ref2 = this.getLineAndColumnFromChunk(consumed), this.chunkLine = ref2[0], this.chunkColumn = ref2[1];
        i += consumed;
        if (opts.untilBalanced && this.ends.length === 0) {
          return {
            tokens: this.tokens,
            index: i
          };
        }
      }
      this.closeIndentation();
      if (end = this.ends.pop()) {
        this.error("missing " + end.tag, end.origin[2]);
      }
      if (opts.rewrite === false) {
        return this.tokens;
      }
      return (new Rewriter).rewrite(this.tokens);
    };

    Lexer.prototype.clean = function(code) {
      if (code.charCodeAt(0) === BOM) {
        code = code.slice(1);
      }
      code = code.replace(/\r/g, '').replace(TRAILING_SPACES, '');
      if (WHITESPACE.test(code)) {
        code = "\n" + code;
        this.chunkLine--;
      }
      if (this.literate) {
        code = invertLiterate(code);
      }
      return code;
    };

    Lexer.prototype.identifierToken = function() {
      var alias, colon, colonOffset, forcedIdentifier, id, idLength, input, match, poppedToken, prev, ref2, ref3, ref4, ref5, tag, tagToken;
      if (!(match = IDENTIFIER.exec(this.chunk))) {
        return 0;
      }
      input = match[0], id = match[1], colon = match[2];
      idLength = id.length;
      poppedToken = void 0;
      if (id === 'own' && this.tag() === 'FOR') {
        this.token('OWN', id);
        return id.length;
      }
      if (id === 'from' && this.tag() === 'YIELD') {
        this.token('FROM', id);
        return id.length;
      }
      ref2 = this.tokens, prev = ref2[ref2.length - 1];
      forcedIdentifier = colon || (prev != null) && (((ref3 = prev[0]) === '.' || ref3 === '?.' || ref3 === '::' || ref3 === '?::') || !prev.spaced && prev[0] === '@');
      tag = 'IDENTIFIER';
      if (!forcedIdentifier && (indexOf.call(JS_KEYWORDS, id) >= 0 || indexOf.call(COFFEE_KEYWORDS, id) >= 0)) {
        tag = id.toUpperCase();
        if (tag === 'WHEN' && (ref4 = this.tag(), indexOf.call(LINE_BREAK, ref4) >= 0)) {
          tag = 'LEADING_WHEN';
        } else if (tag === 'FOR') {
          this.seenFor = true;
        } else if (tag === 'UNLESS') {
          tag = 'IF';
        } else if (indexOf.call(UNARY, tag) >= 0) {
          tag = 'UNARY';
        } else if (indexOf.call(RELATION, tag) >= 0) {
          if (tag !== 'INSTANCEOF' && this.seenFor) {
            tag = 'FOR' + tag;
            this.seenFor = false;
          } else {
            tag = 'RELATION';
            if (this.value() === '!') {
              poppedToken = this.tokens.pop();
              id = '!' + id;
            }
          }
        }
      }
      if (indexOf.call(JS_FORBIDDEN, id) >= 0) {
        if (forcedIdentifier) {
          tag = 'IDENTIFIER';
          id = new String(id);
          id.reserved = true;
        } else if (indexOf.call(RESERVED, id) >= 0) {
          this.error("reserved word '" + id + "'", {
            length: id.length
          });
        }
      }
      if (!forcedIdentifier) {
        if (indexOf.call(COFFEE_ALIASES, id) >= 0) {
          alias = id;
          id = COFFEE_ALIAS_MAP[id];
        }
        tag = (function() {
          switch (id) {
            case '!':
              return 'UNARY';
            case '==':
            case '!=':
              return 'COMPARE';
            case '&&':
            case '||':
              return 'LOGIC';
            case 'true':
            case 'false':
              return 'BOOL';
            case 'break':
            case 'continue':
              return 'STATEMENT';
            default:
              return tag;
          }
        })();
      }
      tagToken = this.token(tag, id, 0, idLength);
      if (alias) {
        tagToken.origin = [tag, alias, tagToken[2]];
      }
      tagToken.variable = !forcedIdentifier;
      if (poppedToken) {
        ref5 = [poppedToken[2].first_line, poppedToken[2].first_column], tagToken[2].first_line = ref5[0], tagToken[2].first_column = ref5[1];
      }
      if (colon) {
        colonOffset = input.lastIndexOf(':');
        this.token(':', ':', colonOffset, colon.length);
      }
      return input.length;
    };

    Lexer.prototype.numberToken = function() {
      var binaryLiteral, lexedLength, match, number, octalLiteral;
      if (!(match = NUMBER.exec(this.chunk))) {
        return 0;
      }
      number = match[0];
      lexedLength = number.length;
      if (/^0[BOX]/.test(number)) {
        this.error("radix prefix in '" + number + "' must be lowercase", {
          offset: 1
        });
      } else if (/E/.test(number) && !/^0x/.test(number)) {
        this.error("exponential notation in '" + number + "' must be indicated with a lowercase 'e'", {
          offset: number.indexOf('E')
        });
      } else if (/^0\d*[89]/.test(number)) {
        this.error("decimal literal '" + number + "' must not be prefixed with '0'", {
          length: lexedLength
        });
      } else if (/^0\d+/.test(number)) {
        this.error("octal literal '" + number + "' must be prefixed with '0o'", {
          length: lexedLength
        });
      }
      if (octalLiteral = /^0o([0-7]+)/.exec(number)) {
        number = '0x' + parseInt(octalLiteral[1], 8).toString(16);
      }
      if (binaryLiteral = /^0b([01]+)/.exec(number)) {
        number = '0x' + parseInt(binaryLiteral[1], 2).toString(16);
      }
      this.token('NUMBER', number, 0, lexedLength);
      return lexedLength;
    };

    Lexer.prototype.stringToken = function() {
      var $, attempt, delimiter, doc, end, heredoc, i, indent, indentRegex, match, quote, ref2, ref3, regex, token, tokens;
      quote = (STRING_START.exec(this.chunk) || [])[0];
      if (!quote) {
        return 0;
      }
      regex = (function() {
        switch (quote) {
          case "'":
            return STRING_SINGLE;
          case '"':
            return STRING_DOUBLE;
          case "'''":
            return HEREDOC_SINGLE;
          case '"""':
            return HEREDOC_DOUBLE;
        }
      })();
      heredoc = quote.length === 3;
      ref2 = this.matchWithInterpolations(regex, quote), tokens = ref2.tokens, end = ref2.index;
      $ = tokens.length - 1;
      delimiter = quote.charAt(0);
      if (heredoc) {
        indent = null;
        doc = ((function() {
          var j, len, results;
          results = [];
          for (i = j = 0, len = tokens.length; j < len; i = ++j) {
            token = tokens[i];
            if (token[0] === 'NEOSTRING') {
              results.push(token[1]);
            }
          }
          return results;
        })()).join('#{}');
        while (match = HEREDOC_INDENT.exec(doc)) {
          attempt = match[1];
          if (indent === null || (0 < (ref3 = attempt.length) && ref3 < indent.length)) {
            indent = attempt;
          }
        }
        if (indent) {
          indentRegex = RegExp("^" + indent, "gm");
        }
        this.mergeInterpolationTokens(tokens, {
          delimiter: delimiter
        }, (function(_this) {
          return function(value, i) {
            value = _this.formatString(value);
            if (i === 0) {
              value = value.replace(LEADING_BLANK_LINE, '');
            }
            if (i === $) {
              value = value.replace(TRAILING_BLANK_LINE, '');
            }
            if (indentRegex) {
              value = value.replace(indentRegex, '');
            }
            return value;
          };
        })(this));
      } else {
        this.mergeInterpolationTokens(tokens, {
          delimiter: delimiter
        }, (function(_this) {
          return function(value, i) {
            value = _this.formatString(value);
            value = value.replace(SIMPLE_STRING_OMIT, function(match, offset) {
              if ((i === 0 && offset === 0) || (i === $ && offset + match.length === value.length)) {
                return '';
              } else {
                return ' ';
              }
            });
            return value;
          };
        })(this));
      }
      return end;
    };

    Lexer.prototype.commentToken = function() {
      var comment, here, match;
      if (!(match = this.chunk.match(COMMENT))) {
        return 0;
      }
      comment = match[0], here = match[1];
      if (here) {
        if (match = HERECOMMENT_ILLEGAL.exec(comment)) {
          this.error("block comments cannot contain " + match[0], {
            offset: match.index,
            length: match[0].length
          });
        }
        if (here.indexOf('\n') >= 0) {
          here = here.replace(RegExp("\\n" + (repeat(' ', this.indent)), "g"), '\n');
        }
        this.token('HERECOMMENT', here, 0, comment.length);
      }
      return comment.length;
    };

    Lexer.prototype.jsToken = function() {
      var match, script;
      if (!(this.chunk.charAt(0) === '`' && (match = JSTOKEN.exec(this.chunk)))) {
        return 0;
      }
      this.token('JS', (script = match[0]).slice(1, -1), 0, script.length);
      return script.length;
    };

    Lexer.prototype.regexToken = function() {
      var body, closed, end, flags, index, match, origin, prev, ref2, ref3, ref4, regex, tokens;
      switch (false) {
        case !(match = REGEX_ILLEGAL.exec(this.chunk)):
          this.error("regular expressions cannot begin with " + match[2], {
            offset: match.index + match[1].length
          });
          break;
        case !(match = this.matchWithInterpolations(HEREGEX, '///')):
          tokens = match.tokens, index = match.index;
          break;
        case !(match = REGEX.exec(this.chunk)):
          regex = match[0], body = match[1], closed = match[2];
          this.validateEscapes(body, {
            isRegex: true,
            offsetInChunk: 1
          });
          index = regex.length;
          ref2 = this.tokens, prev = ref2[ref2.length - 1];
          if (prev) {
            if (prev.spaced && (ref3 = prev[0], indexOf.call(CALLABLE, ref3) >= 0)) {
              if (!closed || POSSIBLY_DIVISION.test(regex)) {
                return 0;
              }
            } else if (ref4 = prev[0], indexOf.call(NOT_REGEX, ref4) >= 0) {
              return 0;
            }
          }
          if (!closed) {
            this.error('missing / (unclosed regex)');
          }
          break;
        default:
          return 0;
      }
      flags = REGEX_FLAGS.exec(this.chunk.slice(index))[0];
      end = index + flags.length;
      origin = this.makeToken('REGEX', null, 0, end);
      switch (false) {
        case !!VALID_FLAGS.test(flags):
          this.error("invalid regular expression flags " + flags, {
            offset: index,
            length: flags.length
          });
          break;
        case !(regex || tokens.length === 1):
          if (body == null) {
            body = this.formatHeregex(tokens[0][1]);
          }
          this.token('REGEX', "" + (this.makeDelimitedLiteral(body, {
            delimiter: '/'
          })) + flags, 0, end, origin);
          break;
        default:
          this.token('REGEX_START', '(', 0, 0, origin);
          this.token('IDENTIFIER', 'RegExp', 0, 0);
          this.token('CALL_START', '(', 0, 0);
          this.mergeInterpolationTokens(tokens, {
            delimiter: '"',
            double: true
          }, this.formatHeregex);
          if (flags) {
            this.token(',', ',', index, 0);
            this.token('STRING', '"' + flags + '"', index, flags.length);
          }
          this.token(')', ')', end, 0);
          this.token('REGEX_END', ')', end, 0);
      }
      return end;
    };

    Lexer.prototype.lineToken = function() {
      var diff, indent, match, noNewlines, size;
      if (!(match = MULTI_DENT.exec(this.chunk))) {
        return 0;
      }
      indent = match[0];
      this.seenFor = false;
      size = indent.length - 1 - indent.lastIndexOf('\n');
      noNewlines = this.unfinished();
      if (size - this.indebt === this.indent) {
        if (noNewlines) {
          this.suppressNewlines();
        } else {
          this.newlineToken(0);
        }
        return indent.length;
      }
      if (size > this.indent) {
        if (noNewlines) {
          this.indebt = size - this.indent;
          this.suppressNewlines();
          return indent.length;
        }
        if (!this.tokens.length) {
          this.baseIndent = this.indent = size;
          return indent.length;
        }
        diff = size - this.indent + this.outdebt;
        this.token('INDENT', diff, indent.length - size, size);
        this.indents.push(diff);
        this.ends.push({
          tag: 'OUTDENT'
        });
        this.outdebt = this.indebt = 0;
        this.indent = size;
      } else if (size < this.baseIndent) {
        this.error('missing indentation', {
          offset: indent.length
        });
      } else {
        this.indebt = 0;
        this.outdentToken(this.indent - size, noNewlines, indent.length);
      }
      return indent.length;
    };

    Lexer.prototype.outdentToken = function(moveOut, noNewlines, outdentLength) {
      var decreasedIndent, dent, lastIndent, ref2;
      decreasedIndent = this.indent - moveOut;
      while (moveOut > 0) {
        lastIndent = this.indents[this.indents.length - 1];
        if (!lastIndent) {
          moveOut = 0;
        } else if (lastIndent === this.outdebt) {
          moveOut -= this.outdebt;
          this.outdebt = 0;
        } else if (lastIndent < this.outdebt) {
          this.outdebt -= lastIndent;
          moveOut -= lastIndent;
        } else {
          dent = this.indents.pop() + this.outdebt;
          if (outdentLength && (ref2 = this.chunk[outdentLength], indexOf.call(INDENTABLE_CLOSERS, ref2) >= 0)) {
            decreasedIndent -= dent - moveOut;
            moveOut = dent;
          }
          this.outdebt = 0;
          this.pair('OUTDENT');
          this.token('OUTDENT', moveOut, 0, outdentLength);
          moveOut -= dent;
        }
      }
      if (dent) {
        this.outdebt -= moveOut;
      }
      while (this.value() === ';') {
        this.tokens.pop();
      }
      if (!(this.tag() === 'TERMINATOR' || noNewlines)) {
        this.token('TERMINATOR', '\n', outdentLength, 0);
      }
      this.indent = decreasedIndent;
      return this;
    };

    Lexer.prototype.whitespaceToken = function() {
      var match, nline, prev, ref2;
      if (!((match = WHITESPACE.exec(this.chunk)) || (nline = this.chunk.charAt(0) === '\n'))) {
        return 0;
      }
      ref2 = this.tokens, prev = ref2[ref2.length - 1];
      if (prev) {
        prev[match ? 'spaced' : 'newLine'] = true;
      }
      if (match) {
        return match[0].length;
      } else {
        return 0;
      }
    };

    Lexer.prototype.newlineToken = function(offset) {
      while (this.value() === ';') {
        this.tokens.pop();
      }
      if (this.tag() !== 'TERMINATOR') {
        this.token('TERMINATOR', '\n', offset, 0);
      }
      return this;
    };

    Lexer.prototype.suppressNewlines = function() {
      if (this.value() === '\\') {
        this.tokens.pop();
      }
      return this;
    };

    Lexer.prototype.literalToken = function() {
      var match, prev, ref2, ref3, ref4, ref5, ref6, tag, token, value;
      if (match = OPERATOR.exec(this.chunk)) {
        value = match[0];
        if (CODE.test(value)) {
          this.tagParameters();
        }
      } else {
        value = this.chunk.charAt(0);
      }
      tag = value;
      ref2 = this.tokens, prev = ref2[ref2.length - 1];
      if (value === '=' && prev) {
        if (!prev[1].reserved && (ref3 = prev[1], indexOf.call(JS_FORBIDDEN, ref3) >= 0)) {
          if (prev.origin) {
            prev = prev.origin;
          }
          this.error("reserved word '" + prev[1] + "' can't be assigned", prev[2]);
        }
        if ((ref4 = prev[1]) === '||' || ref4 === '&&') {
          prev[0] = 'COMPOUND_ASSIGN';
          prev[1] += '=';
          return value.length;
        }
      }
      if (value === ';') {
        this.seenFor = false;
        tag = 'TERMINATOR';
      } else if (indexOf.call(MATH, value) >= 0) {
        tag = 'MATH';
      } else if (indexOf.call(COMPARE, value) >= 0) {
        tag = 'COMPARE';
      } else if (indexOf.call(COMPOUND_ASSIGN, value) >= 0) {
        tag = 'COMPOUND_ASSIGN';
      } else if (indexOf.call(UNARY, value) >= 0) {
        tag = 'UNARY';
      } else if (indexOf.call(UNARY_MATH, value) >= 0) {
        tag = 'UNARY_MATH';
      } else if (indexOf.call(SHIFT, value) >= 0) {
        tag = 'SHIFT';
      } else if (indexOf.call(LOGIC, value) >= 0 || value === '?' && (prev != null ? prev.spaced : void 0)) {
        tag = 'LOGIC';
      } else if (prev && !prev.spaced) {
        if (value === '(' && (ref5 = prev[0], indexOf.call(CALLABLE, ref5) >= 0)) {
          if (prev[0] === '?') {
            prev[0] = 'FUNC_EXIST';
          }
          tag = 'CALL_START';
        } else if (value === '[' && (ref6 = prev[0], indexOf.call(INDEXABLE, ref6) >= 0)) {
          tag = 'INDEX_START';
          switch (prev[0]) {
            case '?':
              prev[0] = 'INDEX_SOAK';
          }
        }
      }
      token = this.makeToken(tag, value);
      switch (value) {
        case '(':
        case '{':
        case '[':
          this.ends.push({
            tag: INVERSES[value],
            origin: token
          });
          break;
        case ')':
        case '}':
        case ']':
          this.pair(value);
      }
      this.tokens.push(token);
      return value.length;
    };

    Lexer.prototype.tagParameters = function() {
      var i, stack, tok, tokens;
      if (this.tag() !== ')') {
        return this;
      }
      stack = [];
      tokens = this.tokens;
      i = tokens.length;
      tokens[--i][0] = 'PARAM_END';
      while (tok = tokens[--i]) {
        switch (tok[0]) {
          case ')':
            stack.push(tok);
            break;
          case '(':
          case 'CALL_START':
            if (stack.length) {
              stack.pop();
            } else if (tok[0] === '(') {
              tok[0] = 'PARAM_START';
              return this;
            } else {
              return this;
            }
        }
      }
      return this;
    };

    Lexer.prototype.closeIndentation = function() {
      return this.outdentToken(this.indent);
    };

    Lexer.prototype.matchWithInterpolations = function(regex, delimiter) {
      var close, column, firstToken, index, lastToken, line, nested, offsetInChunk, open, ref2, ref3, ref4, str, strPart, tokens;
      tokens = [];
      offsetInChunk = delimiter.length;
      if (this.chunk.slice(0, offsetInChunk) !== delimiter) {
        return null;
      }
      str = this.chunk.slice(offsetInChunk);
      while (true) {
        strPart = regex.exec(str)[0];
        this.validateEscapes(strPart, {
          isRegex: delimiter.charAt(0) === '/',
          offsetInChunk: offsetInChunk
        });
        tokens.push(this.makeToken('NEOSTRING', strPart, offsetInChunk));
        str = str.slice(strPart.length);
        offsetInChunk += strPart.length;
        if (str.slice(0, 2) !== '#{') {
          break;
        }
        ref2 = this.getLineAndColumnFromChunk(offsetInChunk + 1), line = ref2[0], column = ref2[1];
        ref3 = new Lexer().tokenize(str.slice(1), {
          line: line,
          column: column,
          untilBalanced: true
        }), nested = ref3.tokens, index = ref3.index;
        index += 1;
        open = nested[0], close = nested[nested.length - 1];
        open[0] = open[1] = '(';
        close[0] = close[1] = ')';
        close.origin = ['', 'end of interpolation', close[2]];
        if (((ref4 = nested[1]) != null ? ref4[0] : void 0) === 'TERMINATOR') {
          nested.splice(1, 1);
        }
        tokens.push(['TOKENS', nested]);
        str = str.slice(index);
        offsetInChunk += index;
      }
      if (str.slice(0, delimiter.length) !== delimiter) {
        this.error("missing " + delimiter, {
          length: delimiter.length
        });
      }
      firstToken = tokens[0], lastToken = tokens[tokens.length - 1];
      firstToken[2].first_column -= delimiter.length;
      lastToken[2].last_column += delimiter.length;
      if (lastToken[1].length === 0) {
        lastToken[2].last_column -= 1;
      }
      return {
        tokens: tokens,
        index: offsetInChunk + delimiter.length
      };
    };

    Lexer.prototype.mergeInterpolationTokens = function(tokens, options, fn) {
      var converted, firstEmptyStringIndex, firstIndex, i, j, lastToken, len, locationToken, lparen, plusToken, ref2, rparen, tag, token, tokensToPush, value;
      if (tokens.length > 1) {
        lparen = this.token('STRING_START', '(', 0, 0);
      }
      firstIndex = this.tokens.length;
      for (i = j = 0, len = tokens.length; j < len; i = ++j) {
        token = tokens[i];
        tag = token[0], value = token[1];
        switch (tag) {
          case 'TOKENS':
            if (value.length === 2) {
              continue;
            }
            locationToken = value[0];
            tokensToPush = value;
            break;
          case 'NEOSTRING':
            converted = fn(token[1], i);
            if (converted.length === 0) {
              if (i === 0) {
                firstEmptyStringIndex = this.tokens.length;
              } else {
                continue;
              }
            }
            if (i === 2 && (firstEmptyStringIndex != null)) {
              this.tokens.splice(firstEmptyStringIndex, 2);
            }
            token[0] = 'STRING';
            token[1] = this.makeDelimitedLiteral(converted, options);
            locationToken = token;
            tokensToPush = [token];
        }
        if (this.tokens.length > firstIndex) {
          plusToken = this.token('+', '+');
          plusToken[2] = {
            first_line: locationToken[2].first_line,
            first_column: locationToken[2].first_column,
            last_line: locationToken[2].first_line,
            last_column: locationToken[2].first_column
          };
        }
        (ref2 = this.tokens).push.apply(ref2, tokensToPush);
      }
      if (lparen) {
        lastToken = tokens[tokens.length - 1];
        lparen.origin = [
          'STRING', null, {
            first_line: lparen[2].first_line,
            first_column: lparen[2].first_column,
            last_line: lastToken[2].last_line,
            last_column: lastToken[2].last_column
          }
        ];
        rparen = this.token('STRING_END', ')');
        return rparen[2] = {
          first_line: lastToken[2].last_line,
          first_column: lastToken[2].last_column,
          last_line: lastToken[2].last_line,
          last_column: lastToken[2].last_column
        };
      }
    };

    Lexer.prototype.pair = function(tag) {
      var lastIndent, prev, ref2, ref3, wanted;
      ref2 = this.ends, prev = ref2[ref2.length - 1];
      if (tag !== (wanted = prev != null ? prev.tag : void 0)) {
        if ('OUTDENT' !== wanted) {
          this.error("unmatched " + tag);
        }
        ref3 = this.indents, lastIndent = ref3[ref3.length - 1];
        this.outdentToken(lastIndent, true);
        return this.pair(tag);
      }
      return this.ends.pop();
    };

    Lexer.prototype.getLineAndColumnFromChunk = function(offset) {
      var column, lastLine, lineCount, ref2, string;
      if (offset === 0) {
        return [this.chunkLine, this.chunkColumn];
      }
      if (offset >= this.chunk.length) {
        string = this.chunk;
      } else {
        string = this.chunk.slice(0, +(offset - 1) + 1 || 9e9);
      }
      lineCount = count(string, '\n');
      column = this.chunkColumn;
      if (lineCount > 0) {
        ref2 = string.split('\n'), lastLine = ref2[ref2.length - 1];
        column = lastLine.length;
      } else {
        column += string.length;
      }
      return [this.chunkLine + lineCount, column];
    };

    Lexer.prototype.makeToken = function(tag, value, offsetInChunk, length) {
      var lastCharacter, locationData, ref2, ref3, token;
      if (offsetInChunk == null) {
        offsetInChunk = 0;
      }
      if (length == null) {
        length = value.length;
      }
      locationData = {};
      ref2 = this.getLineAndColumnFromChunk(offsetInChunk), locationData.first_line = ref2[0], locationData.first_column = ref2[1];
      lastCharacter = Math.max(0, length - 1);
      ref3 = this.getLineAndColumnFromChunk(offsetInChunk + lastCharacter), locationData.last_line = ref3[0], locationData.last_column = ref3[1];
      token = [tag, value, locationData];
      return token;
    };

    Lexer.prototype.token = function(tag, value, offsetInChunk, length, origin) {
      var token;
      token = this.makeToken(tag, value, offsetInChunk, length);
      if (origin) {
        token.origin = origin;
      }
      this.tokens.push(token);
      return token;
    };

    Lexer.prototype.tag = function() {
      var ref2, token;
      ref2 = this.tokens, token = ref2[ref2.length - 1];
      return token != null ? token[0] : void 0;
    };

    Lexer.prototype.value = function() {
      var ref2, token;
      ref2 = this.tokens, token = ref2[ref2.length - 1];
      return token != null ? token[1] : void 0;
    };

    Lexer.prototype.unfinished = function() {
      var ref2;
      return LINE_CONTINUER.test(this.chunk) || ((ref2 = this.tag()) === '\\' || ref2 === '.' || ref2 === '?.' || ref2 === '?::' || ref2 === 'UNARY' || ref2 === 'MATH' || ref2 === 'UNARY_MATH' || ref2 === '+' || ref2 === '-' || ref2 === 'YIELD' || ref2 === '**' || ref2 === 'SHIFT' || ref2 === 'RELATION' || ref2 === 'COMPARE' || ref2 === 'LOGIC' || ref2 === 'THROW' || ref2 === 'EXTENDS');
    };

    Lexer.prototype.formatString = function(str) {
      return str.replace(STRING_OMIT, '$1');
    };

    Lexer.prototype.formatHeregex = function(str) {
      return str.replace(HEREGEX_OMIT, '$1$2');
    };

    Lexer.prototype.validateEscapes = function(str, options) {
      var before, hex, invalidEscape, match, message, octal, ref2, unicode;
      if (options == null) {
        options = {};
      }
      match = INVALID_ESCAPE.exec(str);
      if (!match) {
        return;
      }
      match[0], before = match[1], octal = match[2], hex = match[3], unicode = match[4];
      if (options.isRegex && octal && octal.charAt(0) !== '0') {
        return;
      }
      message = octal ? "octal escape sequences are not allowed" : "invalid escape sequence";
      invalidEscape = "\\" + (octal || hex || unicode);
      return this.error(message + " " + invalidEscape, {
        offset: ((ref2 = options.offsetInChunk) != null ? ref2 : 0) + match.index + before.length,
        length: invalidEscape.length
      });
    };

    Lexer.prototype.makeDelimitedLiteral = function(body, options) {
      var regex;
      if (options == null) {
        options = {};
      }
      if (body === '' && options.delimiter === '/') {
        body = '(?:)';
      }
      regex = RegExp("(\\\\\\\\)|(\\\\0(?=[1-7]))|\\\\?(" + options.delimiter + ")|\\\\?(?:(\\n)|(\\r)|(\\u2028)|(\\u2029))|(\\\\.)", "g");
      body = body.replace(regex, function(match, backslash, nul, delimiter, lf, cr, ls, ps, other) {
        switch (false) {
          case !backslash:
            if (options.double) {
              return backslash + backslash;
            } else {
              return backslash;
            }
          case !nul:
            return '\\x00';
          case !delimiter:
            return "\\" + delimiter;
          case !lf:
            return '\\n';
          case !cr:
            return '\\r';
          case !ls:
            return '\\u2028';
          case !ps:
            return '\\u2029';
          case !other:
            if (options.double) {
              return "\\" + other;
            } else {
              return other;
            }
        }
      });
      return "" + options.delimiter + body + options.delimiter;
    };

    Lexer.prototype.error = function(message, options) {
      var first_column, first_line, location, ref2, ref3, ref4;
      if (options == null) {
        options = {};
      }
      location = 'first_line' in options ? options : ((ref3 = this.getLineAndColumnFromChunk((ref2 = options.offset) != null ? ref2 : 0), first_line = ref3[0], first_column = ref3[1], ref3), {
        first_line: first_line,
        first_column: first_column,
        last_column: first_column + ((ref4 = options.length) != null ? ref4 : 1) - 1
      });
      return throwSyntaxError(message, location);
    };

    return Lexer;

  })();

  JS_KEYWORDS = ['true', 'false', 'null', 'this', 'new', 'delete', 'typeof', 'in', 'instanceof', 'return', 'throw', 'break', 'continue', 'debugger', 'yield', 'if', 'else', 'switch', 'for', 'while', 'do', 'try', 'catch', 'finally', 'class', 'extends', 'super'];

  COFFEE_KEYWORDS = ['undefined', 'then', 'unless', 'until', 'loop', 'of', 'by', 'when'];

  COFFEE_ALIAS_MAP = {
    and: '&&',
    or: '||',
    is: '==',
    isnt: '!=',
    not: '!',
    yes: 'true',
    no: 'false',
    on: 'true',
    off: 'false'
  };

  COFFEE_ALIASES = (function() {
    var results;
    results = [];
    for (key in COFFEE_ALIAS_MAP) {
      results.push(key);
    }
    return results;
  })();

  COFFEE_KEYWORDS = COFFEE_KEYWORDS.concat(COFFEE_ALIASES);

  RESERVED = ['case', 'default', 'function', 'var', 'void', 'with', 'const', 'let', 'enum', 'export', 'import', 'native', 'implements', 'interface', 'package', 'private', 'protected', 'public', 'static'];

  STRICT_PROSCRIBED = ['arguments', 'eval', 'yield*'];

  JS_FORBIDDEN = JS_KEYWORDS.concat(RESERVED).concat(STRICT_PROSCRIBED);

  exports.RESERVED = RESERVED.concat(JS_KEYWORDS).concat(COFFEE_KEYWORDS).concat(STRICT_PROSCRIBED);

  exports.STRICT_PROSCRIBED = STRICT_PROSCRIBED;

  BOM = 65279;

  IDENTIFIER = /^(?!\d)((?:(?!\s)[$\w\x7f-\uffff])+)([^\n\S]*:(?!:))?/;

  NUMBER = /^0b[01]+|^0o[0-7]+|^0x[\da-f]+|^\d*\.?\d+(?:e[+-]?\d+)?/i;

  OPERATOR = /^(?:[-=]>|[-+*\/%<>&|^!?=]=|>>>=?|([-+:])\1|([&|<>*\/%])\2=?|\?(\.|::)|\.{2,3})/;

  WHITESPACE = /^[^\n\S]+/;

  COMMENT = /^###([^#][\s\S]*?)(?:###[^\n\S]*|###$)|^(?:\s*#(?!##[^#]).*)+/;

  CODE = /^[-=]>/;

  MULTI_DENT = /^(?:\n[^\n\S]*)+/;

  JSTOKEN = /^`[^\\`]*(?:\\.[^\\`]*)*`/;

  STRING_START = /^(?:'''|"""|'|")/;

  STRING_SINGLE = /^(?:[^\\']|\\[\s\S])*/;

  STRING_DOUBLE = /^(?:[^\\"#]|\\[\s\S]|\#(?!\{))*/;

  HEREDOC_SINGLE = /^(?:[^\\']|\\[\s\S]|'(?!''))*/;

  HEREDOC_DOUBLE = /^(?:[^\\"#]|\\[\s\S]|"(?!"")|\#(?!\{))*/;

  STRING_OMIT = /((?:\\\\)+)|\\[^\S\n]*\n\s*/g;

  SIMPLE_STRING_OMIT = /\s*\n\s*/g;

  HEREDOC_INDENT = /\n+([^\n\S]*)(?=\S)/g;

  REGEX = /^\/(?!\/)((?:[^[\/\n\\]|\\[^\n]|\[(?:\\[^\n]|[^\]\n\\])*\])*)(\/)?/;

  REGEX_FLAGS = /^\w*/;

  VALID_FLAGS = /^(?!.*(.).*\1)[imgy]*$/;

  HEREGEX = /^(?:[^\\\/#]|\\[\s\S]|\/(?!\/\/)|\#(?!\{))*/;

  HEREGEX_OMIT = /((?:\\\\)+)|\\(\s)|\s+(?:#.*)?/g;

  REGEX_ILLEGAL = /^(\/|\/{3}\s*)(\*)/;

  POSSIBLY_DIVISION = /^\/=?\s/;

  HERECOMMENT_ILLEGAL = /\*\//;

  LINE_CONTINUER = /^\s*(?:,|\??\.(?![.\d])|::)/;

  INVALID_ESCAPE = /((?:^|[^\\])(?:\\\\)*)\\(?:(0[0-7]|[1-7])|(x(?![\da-fA-F]{2}).{0,2})|(u(?![\da-fA-F]{4}).{0,4}))/;

  LEADING_BLANK_LINE = /^[^\n\S]*\n/;

  TRAILING_BLANK_LINE = /\n[^\n\S]*$/;

  TRAILING_SPACES = /\s+$/;

  COMPOUND_ASSIGN = ['-=', '+=', '/=', '*=', '%=', '||=', '&&=', '?=', '<<=', '>>=', '>>>=', '&=', '^=', '|=', '**=', '//=', '%%='];

  UNARY = ['NEW', 'TYPEOF', 'DELETE', 'DO'];

  UNARY_MATH = ['!', '~'];

  LOGIC = ['&&', '||', '&', '|', '^'];

  SHIFT = ['<<', '>>', '>>>'];

  COMPARE = ['==', '!=', '<', '>', '<=', '>='];

  MATH = ['*', '/', '%', '//', '%%'];

  RELATION = ['IN', 'OF', 'INSTANCEOF'];

  BOOL = ['TRUE', 'FALSE'];

  CALLABLE = ['IDENTIFIER', ')', ']', '?', '@', 'THIS', 'SUPER'];

  INDEXABLE = CALLABLE.concat(['NUMBER', 'STRING', 'STRING_END', 'REGEX', 'REGEX_END', 'BOOL', 'NULL', 'UNDEFINED', '}', '::']);

  NOT_REGEX = INDEXABLE.concat(['++', '--']);

  LINE_BREAK = ['INDENT', 'OUTDENT', 'TERMINATOR'];

  INDENTABLE_CLOSERS = [')', '}', ']'];

}).call(this);

},{"./helpers":"coffee-script/lib/coffee-script/helpers","./rewriter":"coffee-script/lib/coffee-script/rewriter"}],"coffee-script/lib/coffee-script/nodes":[function(require,module,exports){
// Generated by CoffeeScript 1.10.0
(function() {
  var Access, Arr, Assign, Base, Block, Call, Class, Code, CodeFragment, Comment, Existence, Expansion, Extends, For, HEXNUM, IDENTIFIER, IS_REGEX, IS_STRING, If, In, Index, LEVEL_ACCESS, LEVEL_COND, LEVEL_LIST, LEVEL_OP, LEVEL_PAREN, LEVEL_TOP, Literal, NEGATE, NO, NUMBER, Obj, Op, Param, Parens, RESERVED, Range, Return, SIMPLENUM, STRICT_PROSCRIBED, Scope, Slice, Splat, Switch, TAB, THIS, Throw, Try, UTILITIES, Value, While, YES, addLocationDataFn, compact, del, ends, extend, flatten, fragmentsToText, isComplexOrAssignable, isLiteralArguments, isLiteralThis, locationDataToString, merge, multident, parseNum, ref1, ref2, some, starts, throwSyntaxError, unfoldSoak, utility,
    extend1 = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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; },
    slice = [].slice;

  Error.stackTraceLimit = Infinity;

  Scope = require('./scope').Scope;

  ref1 = require('./lexer'), RESERVED = ref1.RESERVED, STRICT_PROSCRIBED = ref1.STRICT_PROSCRIBED;

  ref2 = require('./helpers'), compact = ref2.compact, flatten = ref2.flatten, extend = ref2.extend, merge = ref2.merge, del = ref2.del, starts = ref2.starts, ends = ref2.ends, some = ref2.some, addLocationDataFn = ref2.addLocationDataFn, locationDataToString = ref2.locationDataToString, throwSyntaxError = ref2.throwSyntaxError;

  exports.extend = extend;

  exports.addLocationDataFn = addLocationDataFn;

  YES = function() {
    return true;
  };

  NO = function() {
    return false;
  };

  THIS = function() {
    return this;
  };

  NEGATE = function() {
    this.negated = !this.negated;
    return this;
  };

  exports.CodeFragment = CodeFragment = (function() {
    function CodeFragment(parent, code) {
      var ref3;
      this.code = "" + code;
      this.locationData = parent != null ? parent.locationData : void 0;
      this.type = (parent != null ? (ref3 = parent.constructor) != null ? ref3.name : void 0 : void 0) || 'unknown';
    }

    CodeFragment.prototype.toString = function() {
      return "" + this.code + (this.locationData ? ": " + locationDataToString(this.locationData) : '');
    };

    return CodeFragment;

  })();

  fragmentsToText = function(fragments) {
    var fragment;
    return ((function() {
      var j, len1, results;
      results = [];
      for (j = 0, len1 = fragments.length; j < len1; j++) {
        fragment = fragments[j];
        results.push(fragment.code);
      }
      return results;
    })()).join('');
  };

  exports.Base = Base = (function() {
    function Base() {}

    Base.prototype.compile = function(o, lvl) {
      return fragmentsToText(this.compileToFragments(o, lvl));
    };

    Base.prototype.compileToFragments = function(o, lvl) {
      var node;
      o = extend({}, o);
      if (lvl) {
        o.level = lvl;
      }
      node = this.unfoldSoak(o) || this;
      node.tab = o.indent;
      if (o.level === LEVEL_TOP || !node.isStatement(o)) {
        return node.compileNode(o);
      } else {
        return node.compileClosure(o);
      }
    };

    Base.prototype.compileClosure = function(o) {
      var args, argumentsNode, func, jumpNode, meth, parts, ref3;
      if (jumpNode = this.jumps()) {
        jumpNode.error('cannot use a pure statement in an expression');
      }
      o.sharedScope = true;
      func = new Code([], Block.wrap([this]));
      args = [];
      if ((argumentsNode = this.contains(isLiteralArguments)) || this.contains(isLiteralThis)) {
        args = [new Literal('this')];
        if (argumentsNode) {
          meth = 'apply';
          args.push(new Literal('arguments'));
        } else {
          meth = 'call';
        }
        func = new Value(func, [new Access(new Literal(meth))]);
      }
      parts = (new Call(func, args)).compileNode(o);
      if (func.isGenerator || ((ref3 = func.base) != null ? ref3.isGenerator : void 0)) {
        parts.unshift(this.makeCode("(yield* "));
        parts.push(this.makeCode(")"));
      }
      return parts;
    };

    Base.prototype.cache = function(o, level, isComplex) {
      var complex, ref, sub;
      complex = isComplex != null ? isComplex(this) : this.isComplex();
      if (complex) {
        ref = new Literal(o.scope.freeVariable('ref'));
        sub = new Assign(ref, this);
        if (level) {
          return [sub.compileToFragments(o, level), [this.makeCode(ref.value)]];
        } else {
          return [sub, ref];
        }
      } else {
        ref = level ? this.compileToFragments(o, level) : this;
        return [ref, ref];
      }
    };

    Base.prototype.cacheToCodeFragments = function(cacheValues) {
      return [fragmentsToText(cacheValues[0]), fragmentsToText(cacheValues[1])];
    };

    Base.prototype.makeReturn = function(res) {
      var me;
      me = this.unwrapAll();
      if (res) {
        return new Call(new Literal(res + ".push"), [me]);
      } else {
        return new Return(me);
      }
    };

    Base.prototype.contains = function(pred) {
      var node;
      node = void 0;
      this.traverseChildren(false, function(n) {
        if (pred(n)) {
          node = n;
          return false;
        }
      });
      return node;
    };

    Base.prototype.lastNonComment = function(list) {
      var i;
      i = list.length;
      while (i--) {
        if (!(list[i] instanceof Comment)) {
          return list[i];
        }
      }
      return null;
    };

    Base.prototype.toString = function(idt, name) {
      var tree;
      if (idt == null) {
        idt = '';
      }
      if (name == null) {
        name = this.constructor.name;
      }
      tree = '\n' + idt + name;
      if (this.soak) {
        tree += '?';
      }
      this.eachChild(function(node) {
        return tree += node.toString(idt + TAB);
      });
      return tree;
    };

    Base.prototype.eachChild = function(func) {
      var attr, child, j, k, len1, len2, ref3, ref4;
      if (!this.children) {
        return this;
      }
      ref3 = this.children;
      for (j = 0, len1 = ref3.length; j < len1; j++) {
        attr = ref3[j];
        if (this[attr]) {
          ref4 = flatten([this[attr]]);
          for (k = 0, len2 = ref4.length; k < len2; k++) {
            child = ref4[k];
            if (func(child) === false) {
              return this;
            }
          }
        }
      }
      return this;
    };

    Base.prototype.traverseChildren = function(crossScope, func) {
      return this.eachChild(function(child) {
        var recur;
        recur = func(child);
        if (recur !== false) {
          return child.traverseChildren(crossScope, func);
        }
      });
    };

    Base.prototype.invert = function() {
      return new Op('!', this);
    };

    Base.prototype.unwrapAll = function() {
      var node;
      node = this;
      while (node !== (node = node.unwrap())) {
        continue;
      }
      return node;
    };

    Base.prototype.children = [];

    Base.prototype.isStatement = NO;

    Base.prototype.jumps = NO;

    Base.prototype.isComplex = YES;

    Base.prototype.isChainable = NO;

    Base.prototype.isAssignable = NO;

    Base.prototype.unwrap = THIS;

    Base.prototype.unfoldSoak = NO;

    Base.prototype.assigns = NO;

    Base.prototype.updateLocationDataIfMissing = function(locationData) {
      if (this.locationData) {
        return this;
      }
      this.locationData = locationData;
      return this.eachChild(function(child) {
        return child.updateLocationDataIfMissing(locationData);
      });
    };

    Base.prototype.error = function(message) {
      return throwSyntaxError(message, this.locationData);
    };

    Base.prototype.makeCode = function(code) {
      return new CodeFragment(this, code);
    };

    Base.prototype.wrapInBraces = function(fragments) {
      return [].concat(this.makeCode('('), fragments, this.makeCode(')'));
    };

    Base.prototype.joinFragmentArrays = function(fragmentsList, joinStr) {
      var answer, fragments, i, j, len1;
      answer = [];
      for (i = j = 0, len1 = fragmentsList.length; j < len1; i = ++j) {
        fragments = fragmentsList[i];
        if (i) {
          answer.push(this.makeCode(joinStr));
        }
        answer = answer.concat(fragments);
      }
      return answer;
    };

    return Base;

  })();

  exports.Block = Block = (function(superClass1) {
    extend1(Block, superClass1);

    function Block(nodes) {
      this.expressions = compact(flatten(nodes || []));
    }

    Block.prototype.children = ['expressions'];

    Block.prototype.push = function(node) {
      this.expressions.push(node);
      return this;
    };

    Block.prototype.pop = function() {
      return this.expressions.pop();
    };

    Block.prototype.unshift = function(node) {
      this.expressions.unshift(node);
      return this;
    };

    Block.prototype.unwrap = function() {
      if (this.expressions.length === 1) {
        return this.expressions[0];
      } else {
        return this;
      }
    };

    Block.prototype.isEmpty = function() {
      return !this.expressions.length;
    };

    Block.prototype.isStatement = function(o) {
      var exp, j, len1, ref3;
      ref3 = this.expressions;
      for (j = 0, len1 = ref3.length; j < len1; j++) {
        exp = ref3[j];
        if (exp.isStatement(o)) {
          return true;
        }
      }
      return false;
    };

    Block.prototype.jumps = function(o) {
      var exp, j, jumpNode, len1, ref3;
      ref3 = this.expressions;
      for (j = 0, len1 = ref3.length; j < len1; j++) {
        exp = ref3[j];
        if (jumpNode = exp.jumps(o)) {
          return jumpNode;
        }
      }
    };

    Block.prototype.makeReturn = function(res) {
      var expr, len;
      len = this.expressions.length;
      while (len--) {
        expr = this.expressions[len];
        if (!(expr instanceof Comment)) {
          this.expressions[len] = expr.makeReturn(res);
          if (expr instanceof Return && !expr.expression) {
            this.expressions.splice(len, 1);
          }
          break;
        }
      }
      return this;
    };

    Block.prototype.compileToFragments = function(o, level) {
      if (o == null) {
        o = {};
      }
      if (o.scope) {
        return Block.__super__.compileToFragments.call(this, o, level);
      } else {
        return this.compileRoot(o);
      }
    };

    Block.prototype.compileNode = function(o) {
      var answer, compiledNodes, fragments, index, j, len1, node, ref3, top;
      this.tab = o.indent;
      top = o.level === LEVEL_TOP;
      compiledNodes = [];
      ref3 = this.expressions;
      for (index = j = 0, len1 = ref3.length; j < len1; index = ++j) {
        node = ref3[index];
        node = node.unwrapAll();
        node = node.unfoldSoak(o) || node;
        if (node instanceof Block) {
          compiledNodes.push(node.compileNode(o));
        } else if (top) {
          node.front = true;
          fragments = node.compileToFragments(o);
          if (!node.isStatement(o)) {
            fragments.unshift(this.makeCode("" + this.tab));
            fragments.push(this.makeCode(";"));
          }
          compiledNodes.push(fragments);
        } else {
          compiledNodes.push(node.compileToFragments(o, LEVEL_LIST));
        }
      }
      if (top) {
        if (this.spaced) {
          return [].concat(this.joinFragmentArrays(compiledNodes, '\n\n'), this.makeCode("\n"));
        } else {
          return this.joinFragmentArrays(compiledNodes, '\n');
        }
      }
      if (compiledNodes.length) {
        answer = this.joinFragmentArrays(compiledNodes, ', ');
      } else {
        answer = [this.makeCode("void 0")];
      }
      if (compiledNodes.length > 1 && o.level >= LEVEL_LIST) {
        return this.wrapInBraces(answer);
      } else {
        return answer;
      }
    };

    Block.prototype.compileRoot = function(o) {
      var exp, fragments, i, j, len1, name, prelude, preludeExps, ref3, ref4, rest;
      o.indent = o.bare ? '' : TAB;
      o.level = LEVEL_TOP;
      this.spaced = true;
      o.scope = new Scope(null, this, null, (ref3 = o.referencedVars) != null ? ref3 : []);
      ref4 = o.locals || [];
      for (j = 0, len1 = ref4.length; j < len1; j++) {
        name = ref4[j];
        o.scope.parameter(name);
      }
      prelude = [];
      if (!o.bare) {
        preludeExps = (function() {
          var k, len2, ref5, results;
          ref5 = this.expressions;
          results = [];
          for (i = k = 0, len2 = ref5.length; k < len2; i = ++k) {
            exp = ref5[i];
            if (!(exp.unwrap() instanceof Comment)) {
              break;
            }
            results.push(exp);
          }
          return results;
        }).call(this);
        rest = this.expressions.slice(preludeExps.length);
        this.expressions = preludeExps;
        if (preludeExps.length) {
          prelude = this.compileNode(merge(o, {
            indent: ''
          }));
          prelude.push(this.makeCode("\n"));
        }
        this.expressions = rest;
      }
      fragments = this.compileWithDeclarations(o);
      if (o.bare) {
        return fragments;
      }
      return [].concat(prelude, this.makeCode("(function() {\n"), fragments, this.makeCode("\n}).call(this);\n"));
    };

    Block.prototype.compileWithDeclarations = function(o) {
      var assigns, declars, exp, fragments, i, j, len1, post, ref3, ref4, ref5, rest, scope, spaced;
      fragments = [];
      post = [];
      ref3 = this.expressions;
      for (i = j = 0, len1 = ref3.length; j < len1; i = ++j) {
        exp = ref3[i];
        exp = exp.unwrap();
        if (!(exp instanceof Comment || exp instanceof Literal)) {
          break;
        }
      }
      o = merge(o, {
        level: LEVEL_TOP
      });
      if (i) {
        rest = this.expressions.splice(i, 9e9);
        ref4 = [this.spaced, false], spaced = ref4[0], this.spaced = ref4[1];
        ref5 = [this.compileNode(o), spaced], fragments = ref5[0], this.spaced = ref5[1];
        this.expressions = rest;
      }
      post = this.compileNode(o);
      scope = o.scope;
      if (scope.expressions === this) {
        declars = o.scope.hasDeclarations();
        assigns = scope.hasAssignments;
        if (declars || assigns) {
          if (i) {
            fragments.push(this.makeCode('\n'));
          }
          fragments.push(this.makeCode(this.tab + "var "));
          if (declars) {
            fragments.push(this.makeCode(scope.declaredVariables().join(', ')));
          }
          if (assigns) {
            if (declars) {
              fragments.push(this.makeCode(",\n" + (this.tab + TAB)));
            }
            fragments.push(this.makeCode(scope.assignedVariables().join(",\n" + (this.tab + TAB))));
          }
          fragments.push(this.makeCode(";\n" + (this.spaced ? '\n' : '')));
        } else if (fragments.length && post.length) {
          fragments.push(this.makeCode("\n"));
        }
      }
      return fragments.concat(post);
    };

    Block.wrap = function(nodes) {
      if (nodes.length === 1 && nodes[0] instanceof Block) {
        return nodes[0];
      }
      return new Block(nodes);
    };

    return Block;

  })(Base);

  exports.Literal = Literal = (function(superClass1) {
    extend1(Literal, superClass1);

    function Literal(value1) {
      this.value = value1;
    }

    Literal.prototype.makeReturn = function() {
      if (this.isStatement()) {
        return this;
      } else {
        return Literal.__super__.makeReturn.apply(this, arguments);
      }
    };

    Literal.prototype.isAssignable = function() {
      return IDENTIFIER.test(this.value);
    };

    Literal.prototype.isStatement = function() {
      var ref3;
      return (ref3 = this.value) === 'break' || ref3 === 'continue' || ref3 === 'debugger';
    };

    Literal.prototype.isComplex = NO;

    Literal.prototype.assigns = function(name) {
      return name === this.value;
    };

    Literal.prototype.jumps = function(o) {
      if (this.value === 'break' && !((o != null ? o.loop : void 0) || (o != null ? o.block : void 0))) {
        return this;
      }
      if (this.value === 'continue' && !(o != null ? o.loop : void 0)) {
        return this;
      }
    };

    Literal.prototype.compileNode = function(o) {
      var answer, code, ref3;
      code = this.value === 'this' ? ((ref3 = o.scope.method) != null ? ref3.bound : void 0) ? o.scope.method.context : this.value : this.value.reserved ? "\"" + this.value + "\"" : this.value;
      answer = this.isStatement() ? "" + this.tab + code + ";" : code;
      return [this.makeCode(answer)];
    };

    Literal.prototype.toString = function() {
      return ' "' + this.value + '"';
    };

    return Literal;

  })(Base);

  exports.Undefined = (function(superClass1) {
    extend1(Undefined, superClass1);

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

    Undefined.prototype.isAssignable = NO;

    Undefined.prototype.isComplex = NO;

    Undefined.prototype.compileNode = function(o) {
      return [this.makeCode(o.level >= LEVEL_ACCESS ? '(void 0)' : 'void 0')];
    };

    return Undefined;

  })(Base);

  exports.Null = (function(superClass1) {
    extend1(Null, superClass1);

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

    Null.prototype.isAssignable = NO;

    Null.prototype.isComplex = NO;

    Null.prototype.compileNode = function() {
      return [this.makeCode("null")];
    };

    return Null;

  })(Base);

  exports.Bool = (function(superClass1) {
    extend1(Bool, superClass1);

    Bool.prototype.isAssignable = NO;

    Bool.prototype.isComplex = NO;

    Bool.prototype.compileNode = function() {
      return [this.makeCode(this.val)];
    };

    function Bool(val1) {
      this.val = val1;
    }

    return Bool;

  })(Base);

  exports.Return = Return = (function(superClass1) {
    extend1(Return, superClass1);

    function Return(expression) {
      this.expression = expression;
    }

    Return.prototype.children = ['expression'];

    Return.prototype.isStatement = YES;

    Return.prototype.makeReturn = THIS;

    Return.prototype.jumps = THIS;

    Return.prototype.compileToFragments = function(o, level) {
      var expr, ref3;
      expr = (ref3 = this.expression) != null ? ref3.makeReturn() : void 0;
      if (expr && !(expr instanceof Return)) {
        return expr.compileToFragments(o, level);
      } else {
        return Return.__super__.compileToFragments.call(this, o, level);
      }
    };

    Return.prototype.compileNode = function(o) {
      var answer, exprIsYieldReturn, ref3;
      answer = [];
      exprIsYieldReturn = (ref3 = this.expression) != null ? typeof ref3.isYieldReturn === "function" ? ref3.isYieldReturn() : void 0 : void 0;
      if (!exprIsYieldReturn) {
        answer.push(this.makeCode(this.tab + ("return" + (this.expression ? " " : ""))));
      }
      if (this.expression) {
        answer = answer.concat(this.expression.compileToFragments(o, LEVEL_PAREN));
      }
      if (!exprIsYieldReturn) {
        answer.push(this.makeCode(";"));
      }
      return answer;
    };

    return Return;

  })(Base);

  exports.Value = Value = (function(superClass1) {
    extend1(Value, superClass1);

    function Value(base, props, tag) {
      if (!props && base instanceof Value) {
        return base;
      }
      this.base = base;
      this.properties = props || [];
      if (tag) {
        this[tag] = true;
      }
      return this;
    }

    Value.prototype.children = ['base', 'properties'];

    Value.prototype.add = function(props) {
      this.properties = this.properties.concat(props);
      return this;
    };

    Value.prototype.hasProperties = function() {
      return !!this.properties.length;
    };

    Value.prototype.bareLiteral = function(type) {
      return !this.properties.length && this.base instanceof type;
    };

    Value.prototype.isArray = function() {
      return this.bareLiteral(Arr);
    };

    Value.prototype.isRange = function() {
      return this.bareLiteral(Range);
    };

    Value.prototype.isComplex = function() {
      return this.hasProperties() || this.base.isComplex();
    };

    Value.prototype.isAssignable = function() {
      return this.hasProperties() || this.base.isAssignable();
    };

    Value.prototype.isSimpleNumber = function() {
      return this.bareLiteral(Literal) && SIMPLENUM.test(this.base.value);
    };

    Value.prototype.isString = function() {
      return this.bareLiteral(Literal) && IS_STRING.test(this.base.value);
    };

    Value.prototype.isRegex = function() {
      return this.bareLiteral(Literal) && IS_REGEX.test(this.base.value);
    };

    Value.prototype.isAtomic = function() {
      var j, len1, node, ref3;
      ref3 = this.properties.concat(this.base);
      for (j = 0, len1 = ref3.length; j < len1; j++) {
        node = ref3[j];
        if (node.soak || node instanceof Call) {
          return false;
        }
      }
      return true;
    };

    Value.prototype.isNotCallable = function() {
      return this.isSimpleNumber() || this.isString() || this.isRegex() || this.isArray() || this.isRange() || this.isSplice() || this.isObject();
    };

    Value.prototype.isStatement = function(o) {
      return !this.properties.length && this.base.isStatement(o);
    };

    Value.prototype.assigns = function(name) {
      return !this.properties.length && this.base.assigns(name);
    };

    Value.prototype.jumps = function(o) {
      return !this.properties.length && this.base.jumps(o);
    };

    Value.prototype.isObject = function(onlyGenerated) {
      if (this.properties.length) {
        return false;
      }
      return (this.base instanceof Obj) && (!onlyGenerated || this.base.generated);
    };

    Value.prototype.isSplice = function() {
      var lastProp, ref3;
      ref3 = this.properties, lastProp = ref3[ref3.length - 1];
      return lastProp instanceof Slice;
    };

    Value.prototype.looksStatic = function(className) {
      var ref3;
      return this.base.value === className && this.properties.length === 1 && ((ref3 = this.properties[0].name) != null ? ref3.value : void 0) !== 'prototype';
    };

    Value.prototype.unwrap = function() {
      if (this.properties.length) {
        return this;
      } else {
        return this.base;
      }
    };

    Value.prototype.cacheReference = function(o) {
      var base, bref, name, nref, ref3;
      ref3 = this.properties, name = ref3[ref3.length - 1];
      if (this.properties.length < 2 && !this.base.isComplex() && !(name != null ? name.isComplex() : void 0)) {
        return [this, this];
      }
      base = new Value(this.base, this.properties.slice(0, -1));
      if (base.isComplex()) {
        bref = new Literal(o.scope.freeVariable('base'));
        base = new Value(new Parens(new Assign(bref, base)));
      }
      if (!name) {
        return [base, bref];
      }
      if (name.isComplex()) {
        nref = new Literal(o.scope.freeVariable('name'));
        name = new Index(new Assign(nref, name.index));
        nref = new Index(nref);
      }
      return [base.add(name), new Value(bref || base.base, [nref || name])];
    };

    Value.prototype.compileNode = function(o) {
      var fragments, j, len1, prop, props;
      this.base.front = this.front;
      props = this.properties;
      fragments = this.base.compileToFragments(o, (props.length ? LEVEL_ACCESS : null));
      if ((this.base instanceof Parens || props.length) && SIMPLENUM.test(fragmentsToText(fragments))) {
        fragments.push(this.makeCode('.'));
      }
      for (j = 0, len1 = props.length; j < len1; j++) {
        prop = props[j];
        fragments.push.apply(fragments, prop.compileToFragments(o));
      }
      return fragments;
    };

    Value.prototype.unfoldSoak = function(o) {
      return this.unfoldedSoak != null ? this.unfoldedSoak : this.unfoldedSoak = (function(_this) {
        return function() {
          var fst, i, ifn, j, len1, prop, ref, ref3, ref4, snd;
          if (ifn = _this.base.unfoldSoak(o)) {
            (ref3 = ifn.body.properties).push.apply(ref3, _this.properties);
            return ifn;
          }
          ref4 = _this.properties;
          for (i = j = 0, len1 = ref4.length; j < len1; i = ++j) {
            prop = ref4[i];
            if (!prop.soak) {
              continue;
            }
            prop.soak = false;
            fst = new Value(_this.base, _this.properties.slice(0, i));
            snd = new Value(_this.base, _this.properties.slice(i));
            if (fst.isComplex()) {
              ref = new Literal(o.scope.freeVariable('ref'));
              fst = new Parens(new Assign(ref, fst));
              snd.base = ref;
            }
            return new If(new Existence(fst), snd, {
              soak: true
            });
          }
          return false;
        };
      })(this)();
    };

    return Value;

  })(Base);

  exports.Comment = Comment = (function(superClass1) {
    extend1(Comment, superClass1);

    function Comment(comment1) {
      this.comment = comment1;
    }

    Comment.prototype.isStatement = YES;

    Comment.prototype.makeReturn = THIS;

    Comment.prototype.compileNode = function(o, level) {
      var code, comment;
      comment = this.comment.replace(/^(\s*)#(?=\s)/gm, "$1 *");
      code = "/*" + (multident(comment, this.tab)) + (indexOf.call(comment, '\n') >= 0 ? "\n" + this.tab : '') + " */";
      if ((level || o.level) === LEVEL_TOP) {
        code = o.indent + code;
      }
      return [this.makeCode("\n"), this.makeCode(code)];
    };

    return Comment;

  })(Base);

  exports.Call = Call = (function(superClass1) {
    extend1(Call, superClass1);

    function Call(variable, args1, soak) {
      this.args = args1 != null ? args1 : [];
      this.soak = soak;
      this.isNew = false;
      this.isSuper = variable === 'super';
      this.variable = this.isSuper ? null : variable;
      if (variable instanceof Value && variable.isNotCallable()) {
        variable.error("literal is not a function");
      }
    }

    Call.prototype.children = ['variable', 'args'];

    Call.prototype.newInstance = function() {
      var base, ref3;
      base = ((ref3 = this.variable) != null ? ref3.base : void 0) || this.variable;
      if (base instanceof Call && !base.isNew) {
        base.newInstance();
      } else {
        this.isNew = true;
      }
      return this;
    };

    Call.prototype.superReference = function(o) {
      var accesses, base, bref, klass, method, name, nref, variable;
      method = o.scope.namedMethod();
      if (method != null ? method.klass : void 0) {
        klass = method.klass, name = method.name, variable = method.variable;
        if (klass.isComplex()) {
          bref = new Literal(o.scope.parent.freeVariable('base'));
          base = new Value(new Parens(new Assign(bref, klass)));
          variable.base = base;
          variable.properties.splice(0, klass.properties.length);
        }
        if (name.isComplex() || (name instanceof Index && name.index.isAssignable())) {
          nref = new Literal(o.scope.parent.freeVariable('name'));
          name = new Index(new Assign(nref, name.index));
          variable.properties.pop();
          variable.properties.push(name);
        }
        accesses = [new Access(new Literal('__super__'))];
        if (method["static"]) {
          accesses.push(new Access(new Literal('constructor')));
        }
        accesses.push(nref != null ? new Index(nref) : name);
        return (new Value(bref != null ? bref : klass, accesses)).compile(o);
      } else if (method != null ? method.ctor : void 0) {
        return method.name + ".__super__.constructor";
      } else {
        return this.error('cannot call super outside of an instance method.');
      }
    };

    Call.prototype.superThis = function(o) {
      var method;
      method = o.scope.method;
      return (method && !method.klass && method.context) || "this";
    };

    Call.prototype.unfoldSoak = function(o) {
      var call, ifn, j, left, len1, list, ref3, ref4, rite;
      if (this.soak) {
        if (this.variable) {
          if (ifn = unfoldSoak(o, this, 'variable')) {
            return ifn;
          }
          ref3 = new Value(this.variable).cacheReference(o), left = ref3[0], rite = ref3[1];
        } else {
          left = new Literal(this.superReference(o));
          rite = new Value(left);
        }
        rite = new Call(rite, this.args);
        rite.isNew = this.isNew;
        left = new Literal("typeof " + (left.compile(o)) + " === \"function\"");
        return new If(left, new Value(rite), {
          soak: true
        });
      }
      call = this;
      list = [];
      while (true) {
        if (call.variable instanceof Call) {
          list.push(call);
          call = call.variable;
          continue;
        }
        if (!(call.variable instanceof Value)) {
          break;
        }
        list.push(call);
        if (!((call = call.variable.base) instanceof Call)) {
          break;
        }
      }
      ref4 = list.reverse();
      for (j = 0, len1 = ref4.length; j < len1; j++) {
        call = ref4[j];
        if (ifn) {
          if (call.variable instanceof Call) {
            call.variable = ifn;
          } else {
            call.variable.base = ifn;
          }
        }
        ifn = unfoldSoak(o, call, 'variable');
      }
      return ifn;
    };

    Call.prototype.compileNode = function(o) {
      var arg, argIndex, compiledArgs, compiledArray, fragments, j, len1, preface, ref3, ref4;
      if ((ref3 = this.variable) != null) {
        ref3.front = this.front;
      }
      compiledArray = Splat.compileSplattedArray(o, this.args, true);
      if (compiledArray.length) {
        return this.compileSplat(o, compiledArray);
      }
      compiledArgs = [];
      ref4 = this.args;
      for (argIndex = j = 0, len1 = ref4.length; j < len1; argIndex = ++j) {
        arg = ref4[argIndex];
        if (argIndex) {
          compiledArgs.push(this.makeCode(", "));
        }
        compiledArgs.push.apply(compiledArgs, arg.compileToFragments(o, LEVEL_LIST));
      }
      fragments = [];
      if (this.isSuper) {
        preface = this.superReference(o) + (".call(" + (this.superThis(o)));
        if (compiledArgs.length) {
          preface += ", ";
        }
        fragments.push(this.makeCode(preface));
      } else {
        if (this.isNew) {
          fragments.push(this.makeCode('new '));
        }
        fragments.push.apply(fragments, this.variable.compileToFragments(o, LEVEL_ACCESS));
        fragments.push(this.makeCode("("));
      }
      fragments.push.apply(fragments, compiledArgs);
      fragments.push(this.makeCode(")"));
      return fragments;
    };

    Call.prototype.compileSplat = function(o, splatArgs) {
      var answer, base, fun, idt, name, ref;
      if (this.isSuper) {
        return [].concat(this.makeCode((this.superReference(o)) + ".apply(" + (this.superThis(o)) + ", "), splatArgs, this.makeCode(")"));
      }
      if (this.isNew) {
        idt = this.tab + TAB;
        return [].concat(this.makeCode("(function(func, args, ctor) {\n" + idt + "ctor.prototype = func.prototype;\n" + idt + "var child = new ctor, result = func.apply(child, args);\n" + idt + "return Object(result) === result ? result : child;\n" + this.tab + "})("), this.variable.compileToFragments(o, LEVEL_LIST), this.makeCode(", "), splatArgs, this.makeCode(", function(){})"));
      }
      answer = [];
      base = new Value(this.variable);
      if ((name = base.properties.pop()) && base.isComplex()) {
        ref = o.scope.freeVariable('ref');
        answer = answer.concat(this.makeCode("(" + ref + " = "), base.compileToFragments(o, LEVEL_LIST), this.makeCode(")"), name.compileToFragments(o));
      } else {
        fun = base.compileToFragments(o, LEVEL_ACCESS);
        if (SIMPLENUM.test(fragmentsToText(fun))) {
          fun = this.wrapInBraces(fun);
        }
        if (name) {
          ref = fragmentsToText(fun);
          fun.push.apply(fun, name.compileToFragments(o));
        } else {
          ref = 'null';
        }
        answer = answer.concat(fun);
      }
      return answer = answer.concat(this.makeCode(".apply(" + ref + ", "), splatArgs, this.makeCode(")"));
    };

    return Call;

  })(Base);

  exports.Extends = Extends = (function(superClass1) {
    extend1(Extends, superClass1);

    function Extends(child1, parent1) {
      this.child = child1;
      this.parent = parent1;
    }

    Extends.prototype.children = ['child', 'parent'];

    Extends.prototype.compileToFragments = function(o) {
      return new Call(new Value(new Literal(utility('extend', o))), [this.child, this.parent]).compileToFragments(o);
    };

    return Extends;

  })(Base);

  exports.Access = Access = (function(superClass1) {
    extend1(Access, superClass1);

    function Access(name1, tag) {
      this.name = name1;
      this.name.asKey = true;
      this.soak = tag === 'soak';
    }

    Access.prototype.children = ['name'];

    Access.prototype.compileToFragments = function(o) {
      var name;
      name = this.name.compileToFragments(o);
      if (IDENTIFIER.test(fragmentsToText(name))) {
        name.unshift(this.makeCode("."));
      } else {
        name.unshift(this.makeCode("["));
        name.push(this.makeCode("]"));
      }
      return name;
    };

    Access.prototype.isComplex = NO;

    return Access;

  })(Base);

  exports.Index = Index = (function(superClass1) {
    extend1(Index, superClass1);

    function Index(index1) {
      this.index = index1;
    }

    Index.prototype.children = ['index'];

    Index.prototype.compileToFragments = function(o) {
      return [].concat(this.makeCode("["), this.index.compileToFragments(o, LEVEL_PAREN), this.makeCode("]"));
    };

    Index.prototype.isComplex = function() {
      return this.index.isComplex();
    };

    return Index;

  })(Base);

  exports.Range = Range = (function(superClass1) {
    extend1(Range, superClass1);

    Range.prototype.children = ['from', 'to'];

    function Range(from1, to1, tag) {
      this.from = from1;
      this.to = to1;
      this.exclusive = tag === 'exclusive';
      this.equals = this.exclusive ? '' : '=';
    }

    Range.prototype.compileVariables = function(o) {
      var isComplex, ref3, ref4, ref5, ref6, step;
      o = merge(o, {
        top: true
      });
      isComplex = del(o, 'isComplex');
      ref3 = this.cacheToCodeFragments(this.from.cache(o, LEVEL_LIST, isComplex)), this.fromC = ref3[0], this.fromVar = ref3[1];
      ref4 = this.cacheToCodeFragments(this.to.cache(o, LEVEL_LIST, isComplex)), this.toC = ref4[0], this.toVar = ref4[1];
      if (step = del(o, 'step')) {
        ref5 = this.cacheToCodeFragments(step.cache(o, LEVEL_LIST, isComplex)), this.step = ref5[0], this.stepVar = ref5[1];
      }
      ref6 = [this.fromVar.match(NUMBER), this.toVar.match(NUMBER)], this.fromNum = ref6[0], this.toNum = ref6[1];
      if (this.stepVar) {
        return this.stepNum = this.stepVar.match(NUMBER);
      }
    };

    Range.prototype.compileNode = function(o) {
      var cond, condPart, from, gt, idx, idxName, known, lt, namedIndex, ref3, ref4, stepPart, to, varPart;
      if (!this.fromVar) {
        this.compileVariables(o);
      }
      if (!o.index) {
        return this.compileArray(o);
      }
      known = this.fromNum && this.toNum;
      idx = del(o, 'index');
      idxName = del(o, 'name');
      namedIndex = idxName && idxName !== idx;
      varPart = idx + " = " + this.fromC;
      if (this.toC !== this.toVar) {
        varPart += ", " + this.toC;
      }
      if (this.step !== this.stepVar) {
        varPart += ", " + this.step;
      }
      ref3 = [idx + " <" + this.equals, idx + " >" + this.equals], lt = ref3[0], gt = ref3[1];
      condPart = this.stepNum ? parseNum(this.stepNum[0]) > 0 ? lt + " " + this.toVar : gt + " " + this.toVar : known ? ((ref4 = [parseNum(this.fromNum[0]), parseNum(this.toNum[0])], from = ref4[0], to = ref4[1], ref4), from <= to ? lt + " " + to : gt + " " + to) : (cond = this.stepVar ? this.stepVar + " > 0" : this.fromVar + " <= " + this.toVar, cond + " ? " + lt + " " + this.toVar + " : " + gt + " " + this.toVar);
      stepPart = this.stepVar ? idx + " += " + this.stepVar : known ? namedIndex ? from <= to ? "++" + idx : "--" + idx : from <= to ? idx + "++" : idx + "--" : namedIndex ? cond + " ? ++" + idx + " : --" + idx : cond + " ? " + idx + "++ : " + idx + "--";
      if (namedIndex) {
        varPart = idxName + " = " + varPart;
      }
      if (namedIndex) {
        stepPart = idxName + " = " + stepPart;
      }
      return [this.makeCode(varPart + "; " + condPart + "; " + stepPart)];
    };

    Range.prototype.compileArray = function(o) {
      var args, body, cond, hasArgs, i, idt, j, post, pre, range, ref3, ref4, result, results, vars;
      if (this.fromNum && this.toNum && Math.abs(this.fromNum - this.toNum) <= 20) {
        range = (function() {
          results = [];
          for (var j = ref3 = +this.fromNum, ref4 = +this.toNum; ref3 <= ref4 ? j <= ref4 : j >= ref4; ref3 <= ref4 ? j++ : j--){ results.push(j); }
          return results;
        }).apply(this);
        if (this.exclusive) {
          range.pop();
        }
        return [this.makeCode("[" + (range.join(', ')) + "]")];
      }
      idt = this.tab + TAB;
      i = o.scope.freeVariable('i', {
        single: true
      });
      result = o.scope.freeVariable('results');
      pre = "\n" + idt + result + " = [];";
      if (this.fromNum && this.toNum) {
        o.index = i;
        body = fragmentsToText(this.compileNode(o));
      } else {
        vars = (i + " = " + this.fromC) + (this.toC !== this.toVar ? ", " + this.toC : '');
        cond = this.fromVar + " <= " + this.toVar;
        body = "var " + vars + "; " + cond + " ? " + i + " <" + this.equals + " " + this.toVar + " : " + i + " >" + this.equals + " " + this.toVar + "; " + cond + " ? " + i + "++ : " + i + "--";
      }
      post = "{ " + result + ".push(" + i + "); }\n" + idt + "return " + result + ";\n" + o.indent;
      hasArgs = function(node) {
        return node != null ? node.contains(isLiteralArguments) : void 0;
      };
      if (hasArgs(this.from) || hasArgs(this.to)) {
        args = ', arguments';
      }
      return [this.makeCode("(function() {" + pre + "\n" + idt + "for (" + body + ")" + post + "}).apply(this" + (args != null ? args : '') + ")")];
    };

    return Range;

  })(Base);

  exports.Slice = Slice = (function(superClass1) {
    extend1(Slice, superClass1);

    Slice.prototype.children = ['range'];

    function Slice(range1) {
      this.range = range1;
      Slice.__super__.constructor.call(this);
    }

    Slice.prototype.compileNode = function(o) {
      var compiled, compiledText, from, fromCompiled, ref3, to, toStr;
      ref3 = this.range, to = ref3.to, from = ref3.from;
      fromCompiled = from && from.compileToFragments(o, LEVEL_PAREN) || [this.makeCode('0')];
      if (to) {
        compiled = to.compileToFragments(o, LEVEL_PAREN);
        compiledText = fragmentsToText(compiled);
        if (!(!this.range.exclusive && +compiledText === -1)) {
          toStr = ', ' + (this.range.exclusive ? compiledText : SIMPLENUM.test(compiledText) ? "" + (+compiledText + 1) : (compiled = to.compileToFragments(o, LEVEL_ACCESS), "+" + (fragmentsToText(compiled)) + " + 1 || 9e9"));
        }
      }
      return [this.makeCode(".slice(" + (fragmentsToText(fromCompiled)) + (toStr || '') + ")")];
    };

    return Slice;

  })(Base);

  exports.Obj = Obj = (function(superClass1) {
    extend1(Obj, superClass1);

    function Obj(props, generated) {
      this.generated = generated != null ? generated : false;
      this.objects = this.properties = props || [];
    }

    Obj.prototype.children = ['properties'];

    Obj.prototype.compileNode = function(o) {
      var answer, dynamicIndex, hasDynamic, i, idt, indent, j, join, k, key, l, lastNoncom, len1, len2, len3, node, oref, prop, props, ref3, value;
      props = this.properties;
      if (this.generated) {
        for (j = 0, len1 = props.length; j < len1; j++) {
          node = props[j];
          if (node instanceof Value) {
            node.error('cannot have an implicit value in an implicit object');
          }
        }
      }
      for (dynamicIndex = k = 0, len2 = props.length; k < len2; dynamicIndex = ++k) {
        prop = props[dynamicIndex];
        if ((prop.variable || prop).base instanceof Parens) {
          break;
        }
      }
      hasDynamic = dynamicIndex < props.length;
      idt = o.indent += TAB;
      lastNoncom = this.lastNonComment(this.properties);
      answer = [];
      if (hasDynamic) {
        oref = o.scope.freeVariable('obj');
        answer.push(this.makeCode("(\n" + idt + oref + " = "));
      }
      answer.push(this.makeCode("{" + (props.length === 0 || dynamicIndex === 0 ? '}' : '\n')));
      for (i = l = 0, len3 = props.length; l < len3; i = ++l) {
        prop = props[i];
        if (i === dynamicIndex) {
          if (i !== 0) {
            answer.push(this.makeCode("\n" + idt + "}"));
          }
          answer.push(this.makeCode(',\n'));
        }
        join = i === props.length - 1 || i === dynamicIndex - 1 ? '' : prop === lastNoncom || prop instanceof Comment ? '\n' : ',\n';
        indent = prop instanceof Comment ? '' : idt;
        if (hasDynamic && i < dynamicIndex) {
          indent += TAB;
        }
        if (prop instanceof Assign) {
          if (prop.context !== 'object') {
            prop.operatorToken.error("unexpected " + prop.operatorToken.value);
          }
          if (prop.variable instanceof Value && prop.variable.hasProperties()) {
            prop.variable.error('invalid object key');
          }
        }
        if (prop instanceof Value && prop["this"]) {
          prop = new Assign(prop.properties[0].name, prop, 'object');
        }
        if (!(prop instanceof Comment)) {
          if (i < dynamicIndex) {
            if (!(prop instanceof Assign)) {
              prop = new Assign(prop, prop, 'object');
            }
            (prop.variable.base || prop.variable).asKey = true;
          } else {
            if (prop instanceof Assign) {
              key = prop.variable;
              value = prop.value;
            } else {
              ref3 = prop.base.cache(o), key = ref3[0], value = ref3[1];
            }
            prop = new Assign(new Value(new Literal(oref), [new Access(key)]), value);
          }
        }
        if (indent) {
          answer.push(this.makeCode(indent));
        }
        answer.push.apply(answer, prop.compileToFragments(o, LEVEL_TOP));
        if (join) {
          answer.push(this.makeCode(join));
        }
      }
      if (hasDynamic) {
        answer.push(this.makeCode(",\n" + idt + oref + "\n" + this.tab + ")"));
      } else {
        if (props.length !== 0) {
          answer.push(this.makeCode("\n" + this.tab + "}"));
        }
      }
      if (this.front && !hasDynamic) {
        return this.wrapInBraces(answer);
      } else {
        return answer;
      }
    };

    Obj.prototype.assigns = function(name) {
      var j, len1, prop, ref3;
      ref3 = this.properties;
      for (j = 0, len1 = ref3.length; j < len1; j++) {
        prop = ref3[j];
        if (prop.assigns(name)) {
          return true;
        }
      }
      return false;
    };

    return Obj;

  })(Base);

  exports.Arr = Arr = (function(superClass1) {
    extend1(Arr, superClass1);

    function Arr(objs) {
      this.objects = objs || [];
    }

    Arr.prototype.children = ['objects'];

    Arr.prototype.compileNode = function(o) {
      var answer, compiledObjs, fragments, index, j, len1, obj;
      if (!this.objects.length) {
        return [this.makeCode('[]')];
      }
      o.indent += TAB;
      answer = Splat.compileSplattedArray(o, this.objects);
      if (answer.length) {
        return answer;
      }
      answer = [];
      compiledObjs = (function() {
        var j, len1, ref3, results;
        ref3 = this.objects;
        results = [];
        for (j = 0, len1 = ref3.length; j < len1; j++) {
          obj = ref3[j];
          results.push(obj.compileToFragments(o, LEVEL_LIST));
        }
        return results;
      }).call(this);
      for (index = j = 0, len1 = compiledObjs.length; j < len1; index = ++j) {
        fragments = compiledObjs[index];
        if (index) {
          answer.push(this.makeCode(", "));
        }
        answer.push.apply(answer, fragments);
      }
      if (fragmentsToText(answer).indexOf('\n') >= 0) {
        answer.unshift(this.makeCode("[\n" + o.indent));
        answer.push(this.makeCode("\n" + this.tab + "]"));
      } else {
        answer.unshift(this.makeCode("["));
        answer.push(this.makeCode("]"));
      }
      return answer;
    };

    Arr.prototype.assigns = function(name) {
      var j, len1, obj, ref3;
      ref3 = this.objects;
      for (j = 0, len1 = ref3.length; j < len1; j++) {
        obj = ref3[j];
        if (obj.assigns(name)) {
          return true;
        }
      }
      return false;
    };

    return Arr;

  })(Base);

  exports.Class = Class = (function(superClass1) {
    extend1(Class, superClass1);

    function Class(variable1, parent1, body1) {
      this.variable = variable1;
      this.parent = parent1;
      this.body = body1 != null ? body1 : new Block;
      this.boundFuncs = [];
      this.body.classBody = true;
    }

    Class.prototype.children = ['variable', 'parent', 'body'];

    Class.prototype.determineName = function() {
      var decl, ref3, tail;
      if (!this.variable) {
        return null;
      }
      ref3 = this.variable.properties, tail = ref3[ref3.length - 1];
      decl = tail ? tail instanceof Access && tail.name.value : this.variable.base.value;
      if (indexOf.call(STRICT_PROSCRIBED, decl) >= 0) {
        this.variable.error("class variable name may not be " + decl);
      }
      return decl && (decl = IDENTIFIER.test(decl) && decl);
    };

    Class.prototype.setContext = function(name) {
      return this.body.traverseChildren(false, function(node) {
        if (node.classBody) {
          return false;
        }
        if (node instanceof Literal && node.value === 'this') {
          return node.value = name;
        } else if (node instanceof Code) {
          if (node.bound) {
            return node.context = name;
          }
        }
      });
    };

    Class.prototype.addBoundFunctions = function(o) {
      var bvar, j, len1, lhs, ref3;
      ref3 = this.boundFuncs;
      for (j = 0, len1 = ref3.length; j < len1; j++) {
        bvar = ref3[j];
        lhs = (new Value(new Literal("this"), [new Access(bvar)])).compile(o);
        this.ctor.body.unshift(new Literal(lhs + " = " + (utility('bind', o)) + "(" + lhs + ", this)"));
      }
    };

    Class.prototype.addProperties = function(node, name, o) {
      var acc, assign, base, exprs, func, props;
      props = node.base.properties.slice(0);
      exprs = (function() {
        var results;
        results = [];
        while (assign = props.shift()) {
          if (assign instanceof Assign) {
            base = assign.variable.base;
            delete assign.context;
            func = assign.value;
            if (base.value === 'constructor') {
              if (this.ctor) {
                assign.error('cannot define more than one constructor in a class');
              }
              if (func.bound) {
                assign.error('cannot define a constructor as a bound function');
              }
              if (func instanceof Code) {
                assign = this.ctor = func;
              } else {
                this.externalCtor = o.classScope.freeVariable('class');
                assign = new Assign(new Literal(this.externalCtor), func);
              }
            } else {
              if (assign.variable["this"]) {
                func["static"] = true;
              } else {
                acc = base.isComplex() ? new Index(base) : new Access(base);
                assign.variable = new Value(new Literal(name), [new Access(new Literal('prototype')), acc]);
                if (func instanceof Code && func.bound) {
                  this.boundFuncs.push(base);
                  func.bound = false;
                }
              }
            }
          }
          results.push(assign);
        }
        return results;
      }).call(this);
      return compact(exprs);
    };

    Class.prototype.walkBody = function(name, o) {
      return this.traverseChildren(false, (function(_this) {
        return function(child) {
          var cont, exps, i, j, len1, node, ref3;
          cont = true;
          if (child instanceof Class) {
            return false;
          }
          if (child instanceof Block) {
            ref3 = exps = child.expressions;
            for (i = j = 0, len1 = ref3.length; j < len1; i = ++j) {
              node = ref3[i];
              if (node instanceof Assign && node.variable.looksStatic(name)) {
                node.value["static"] = true;
              } else if (node instanceof Value && node.isObject(true)) {
                cont = false;
                exps[i] = _this.addProperties(node, name, o);
              }
            }
            child.expressions = exps = flatten(exps);
          }
          return cont && !(child instanceof Class);
        };
      })(this));
    };

    Class.prototype.hoistDirectivePrologue = function() {
      var expressions, index, node;
      index = 0;
      expressions = this.body.expressions;
      while ((node = expressions[index]) && node instanceof Comment || node instanceof Value && node.isString()) {
        ++index;
      }
      return this.directives = expressions.splice(0, index);
    };

    Class.prototype.ensureConstructor = function(name) {
      if (!this.ctor) {
        this.ctor = new Code;
        if (this.externalCtor) {
          this.ctor.body.push(new Literal(this.externalCtor + ".apply(this, arguments)"));
        } else if (this.parent) {
          this.ctor.body.push(new Literal(name + ".__super__.constructor.apply(this, arguments)"));
        }
        this.ctor.body.makeReturn();
        this.body.expressions.unshift(this.ctor);
      }
      this.ctor.ctor = this.ctor.name = name;
      this.ctor.klass = null;
      return this.ctor.noReturn = true;
    };

    Class.prototype.compileNode = function(o) {
      var args, argumentsNode, func, jumpNode, klass, lname, name, ref3, superClass;
      if (jumpNode = this.body.jumps()) {
        jumpNode.error('Class bodies cannot contain pure statements');
      }
      if (argumentsNode = this.body.contains(isLiteralArguments)) {
        argumentsNode.error("Class bodies shouldn't reference arguments");
      }
      name = this.determineName() || '_Class';
      if (name.reserved) {
        name = "_" + name;
      }
      lname = new Literal(name);
      func = new Code([], Block.wrap([this.body]));
      args = [];
      o.classScope = func.makeScope(o.scope);
      this.hoistDirectivePrologue();
      this.setContext(name);
      this.walkBody(name, o);
      this.ensureConstructor(name);
      this.addBoundFunctions(o);
      this.body.spaced = true;
      this.body.expressions.push(lname);
      if (this.parent) {
        superClass = new Literal(o.classScope.freeVariable('superClass', {
          reserve: false
        }));
        this.body.expressions.unshift(new Extends(lname, superClass));
        func.params.push(new Param(superClass));
        args.push(this.parent);
      }
      (ref3 = this.body.expressions).unshift.apply(ref3, this.directives);
      klass = new Parens(new Call(func, args));
      if (this.variable) {
        klass = new Assign(this.variable, klass);
      }
      return klass.compileToFragments(o);
    };

    return Class;

  })(Base);

  exports.Assign = Assign = (function(superClass1) {
    extend1(Assign, superClass1);

    function Assign(variable1, value1, context, options) {
      var forbidden, name, ref3;
      this.variable = variable1;
      this.value = value1;
      this.context = context;
      if (options == null) {
        options = {};
      }
      this.param = options.param, this.subpattern = options.subpattern, this.operatorToken = options.operatorToken;
      forbidden = (ref3 = (name = this.variable.unwrapAll().value), indexOf.call(STRICT_PROSCRIBED, ref3) >= 0);
      if (forbidden && this.context !== 'object') {
        this.variable.error("variable name may not be \"" + name + "\"");
      }
    }

    Assign.prototype.children = ['variable', 'value'];

    Assign.prototype.isStatement = function(o) {
      return (o != null ? o.level : void 0) === LEVEL_TOP && (this.context != null) && indexOf.call(this.context, "?") >= 0;
    };

    Assign.prototype.assigns = function(name) {
      return this[this.context === 'object' ? 'value' : 'variable'].assigns(name);
    };

    Assign.prototype.unfoldSoak = function(o) {
      return unfoldSoak(o, this, 'variable');
    };

    Assign.prototype.compileNode = function(o) {
      var answer, compiledName, isValue, j, name, properties, prototype, ref3, ref4, ref5, ref6, ref7, val, varBase;
      if (isValue = this.variable instanceof Value) {
        if (this.variable.isArray() || this.variable.isObject()) {
          return this.compilePatternMatch(o);
        }
        if (this.variable.isSplice()) {
          return this.compileSplice(o);
        }
        if ((ref3 = this.context) === '||=' || ref3 === '&&=' || ref3 === '?=') {
          return this.compileConditional(o);
        }
        if ((ref4 = this.context) === '**=' || ref4 === '//=' || ref4 === '%%=') {
          return this.compileSpecialMath(o);
        }
      }
      if (this.value instanceof Code) {
        if (this.value["static"]) {
          this.value.klass = this.variable.base;
          this.value.name = this.variable.properties[0];
          this.value.variable = this.variable;
        } else if (((ref5 = this.variable.properties) != null ? ref5.length : void 0) >= 2) {
          ref6 = this.variable.properties, properties = 3 <= ref6.length ? slice.call(ref6, 0, j = ref6.length - 2) : (j = 0, []), prototype = ref6[j++], name = ref6[j++];
          if (((ref7 = prototype.name) != null ? ref7.value : void 0) === 'prototype') {
            this.value.klass = new Value(this.variable.base, properties);
            this.value.name = name;
            this.value.variable = this.variable;
          }
        }
      }
      if (!this.context) {
        varBase = this.variable.unwrapAll();
        if (!varBase.isAssignable()) {
          this.variable.error("\"" + (this.variable.compile(o)) + "\" cannot be assigned");
        }
        if (!(typeof varBase.hasProperties === "function" ? varBase.hasProperties() : void 0)) {
          if (this.param) {
            o.scope.add(varBase.value, 'var');
          } else {
            o.scope.find(varBase.value);
          }
        }
      }
      val = this.value.compileToFragments(o, LEVEL_LIST);
      if (isValue && this.variable.base instanceof Obj) {
        this.variable.front = true;
      }
      compiledName = this.variable.compileToFragments(o, LEVEL_LIST);
      if (this.context === 'object') {
        return compiledName.concat(this.makeCode(": "), val);
      }
      answer = compiledName.concat(this.makeCode(" " + (this.context || '=') + " "), val);
      if (o.level <= LEVEL_LIST) {
        return answer;
      } else {
        return this.wrapInBraces(answer);
      }
    };

    Assign.prototype.compilePatternMatch = function(o) {
      var acc, assigns, code, defaultValue, expandedIdx, fragments, i, idx, isObject, ivar, j, len1, name, obj, objects, olen, ref, ref3, ref4, ref5, ref6, ref7, rest, top, val, value, vvar, vvarText;
      top = o.level === LEVEL_TOP;
      value = this.value;
      objects = this.variable.base.objects;
      if (!(olen = objects.length)) {
        code = value.compileToFragments(o);
        if (o.level >= LEVEL_OP) {
          return this.wrapInBraces(code);
        } else {
          return code;
        }
      }
      obj = objects[0];
      if (olen === 1 && obj instanceof Expansion) {
        obj.error('Destructuring assignment has no target');
      }
      isObject = this.variable.isObject();
      if (top && olen === 1 && !(obj instanceof Splat)) {
        defaultValue = null;
        if (obj instanceof Assign && obj.context === 'object') {
          ref3 = obj, (ref4 = ref3.variable, idx = ref4.base), obj = ref3.value;
          if (obj instanceof Assign) {
            defaultValue = obj.value;
            obj = obj.variable;
          }
        } else {
          if (obj instanceof Assign) {
            defaultValue = obj.value;
            obj = obj.variable;
          }
          idx = isObject ? obj["this"] ? obj.properties[0].name : obj : new Literal(0);
        }
        acc = IDENTIFIER.test(idx.unwrap().value);
        value = new Value(value);
        value.properties.push(new (acc ? Access : Index)(idx));
        if (ref5 = obj.unwrap().value, indexOf.call(RESERVED, ref5) >= 0) {
          obj.error("assignment to a reserved word: " + (obj.compile(o)));
        }
        if (defaultValue) {
          value = new Op('?', value, defaultValue);
        }
        return new Assign(obj, value, null, {
          param: this.param
        }).compileToFragments(o, LEVEL_TOP);
      }
      vvar = value.compileToFragments(o, LEVEL_LIST);
      vvarText = fragmentsToText(vvar);
      assigns = [];
      expandedIdx = false;
      if (!IDENTIFIER.test(vvarText) || this.variable.assigns(vvarText)) {
        assigns.push([this.makeCode((ref = o.scope.freeVariable('ref')) + " = ")].concat(slice.call(vvar)));
        vvar = [this.makeCode(ref)];
        vvarText = ref;
      }
      for (i = j = 0, len1 = objects.length; j < len1; i = ++j) {
        obj = objects[i];
        idx = i;
        if (!expandedIdx && obj instanceof Splat) {
          name = obj.name.unwrap().value;
          obj = obj.unwrap();
          val = olen + " <= " + vvarText + ".length ? " + (utility('slice', o)) + ".call(" + vvarText + ", " + i;
          if (rest = olen - i - 1) {
            ivar = o.scope.freeVariable('i', {
              single: true
            });
            val += ", " + ivar + " = " + vvarText + ".length - " + rest + ") : (" + ivar + " = " + i + ", [])";
          } else {
            val += ") : []";
          }
          val = new Literal(val);
          expandedIdx = ivar + "++";
        } else if (!expandedIdx && obj instanceof Expansion) {
          if (rest = olen - i - 1) {
            if (rest === 1) {
              expandedIdx = vvarText + ".length - 1";
            } else {
              ivar = o.scope.freeVariable('i', {
                single: true
              });
              val = new Literal(ivar + " = " + vvarText + ".length - " + rest);
              expandedIdx = ivar + "++";
              assigns.push(val.compileToFragments(o, LEVEL_LIST));
            }
          }
          continue;
        } else {
          if (obj instanceof Splat || obj instanceof Expansion) {
            obj.error("multiple splats/expansions are disallowed in an assignment");
          }
          defaultValue = null;
          if (obj instanceof Assign && obj.context === 'object') {
            ref6 = obj, (ref7 = ref6.variable, idx = ref7.base), obj = ref6.value;
            if (obj instanceof Assign) {
              defaultValue = obj.value;
              obj = obj.variable;
            }
          } else {
            if (obj instanceof Assign) {
              defaultValue = obj.value;
              obj = obj.variable;
            }
            idx = isObject ? obj["this"] ? obj.properties[0].name : obj : new Literal(expandedIdx || idx);
          }
          name = obj.unwrap().value;
          acc = IDENTIFIER.test(idx.unwrap().value);
          val = new Value(new Literal(vvarText), [new (acc ? Access : Index)(idx)]);
          if (defaultValue) {
            val = new Op('?', val, defaultValue);
          }
        }
        if ((name != null) && indexOf.call(RESERVED, name) >= 0) {
          obj.error("assignment to a reserved word: " + (obj.compile(o)));
        }
        assigns.push(new Assign(obj, val, null, {
          param: this.param,
          subpattern: true
        }).compileToFragments(o, LEVEL_LIST));
      }
      if (!(top || this.subpattern)) {
        assigns.push(vvar);
      }
      fragments = this.joinFragmentArrays(assigns, ', ');
      if (o.level < LEVEL_LIST) {
        return fragments;
      } else {
        return this.wrapInBraces(fragments);
      }
    };

    Assign.prototype.compileConditional = function(o) {
      var fragments, left, ref3, right;
      ref3 = this.variable.cacheReference(o), left = ref3[0], right = ref3[1];
      if (!left.properties.length && left.base instanceof Literal && left.base.value !== "this" && !o.scope.check(left.base.value)) {
        this.variable.error("the variable \"" + left.base.value + "\" can't be assigned with " + this.context + " because it has not been declared before");
      }
      if (indexOf.call(this.context, "?") >= 0) {
        o.isExistentialEquals = true;
        return new If(new Existence(left), right, {
          type: 'if'
        }).addElse(new Assign(right, this.value, '=')).compileToFragments(o);
      } else {
        fragments = new Op(this.context.slice(0, -1), left, new Assign(right, this.value, '=')).compileToFragments(o);
        if (o.level <= LEVEL_LIST) {
          return fragments;
        } else {
          return this.wrapInBraces(fragments);
        }
      }
    };

    Assign.prototype.compileSpecialMath = function(o) {
      var left, ref3, right;
      ref3 = this.variable.cacheReference(o), left = ref3[0], right = ref3[1];
      return new Assign(left, new Op(this.context.slice(0, -1), right, this.value)).compileToFragments(o);
    };

    Assign.prototype.compileSplice = function(o) {
      var answer, exclusive, from, fromDecl, fromRef, name, ref3, ref4, ref5, to, valDef, valRef;
      ref3 = this.variable.properties.pop().range, from = ref3.from, to = ref3.to, exclusive = ref3.exclusive;
      name = this.variable.compile(o);
      if (from) {
        ref4 = this.cacheToCodeFragments(from.cache(o, LEVEL_OP)), fromDecl = ref4[0], fromRef = ref4[1];
      } else {
        fromDecl = fromRef = '0';
      }
      if (to) {
        if (from instanceof Value && from.isSimpleNumber() && to instanceof Value && to.isSimpleNumber()) {
          to = to.compile(o) - fromRef;
          if (!exclusive) {
            to += 1;
          }
        } else {
          to = to.compile(o, LEVEL_ACCESS) + ' - ' + fromRef;
          if (!exclusive) {
            to += ' + 1';
          }
        }
      } else {
        to = "9e9";
      }
      ref5 = this.value.cache(o, LEVEL_LIST), valDef = ref5[0], valRef = ref5[1];
      answer = [].concat(this.makeCode("[].splice.apply(" + name + ", [" + fromDecl + ", " + to + "].concat("), valDef, this.makeCode(")), "), valRef);
      if (o.level > LEVEL_TOP) {
        return this.wrapInBraces(answer);
      } else {
        return answer;
      }
    };

    return Assign;

  })(Base);

  exports.Code = Code = (function(superClass1) {
    extend1(Code, superClass1);

    function Code(params, body, tag) {
      this.params = params || [];
      this.body = body || new Block;
      this.bound = tag === 'boundfunc';
      this.isGenerator = !!this.body.contains(function(node) {
        var ref3;
        return node instanceof Op && ((ref3 = node.operator) === 'yield' || ref3 === 'yield*');
      });
    }

    Code.prototype.children = ['params', 'body'];

    Code.prototype.isStatement = function() {
      return !!this.ctor;
    };

    Code.prototype.jumps = NO;

    Code.prototype.makeScope = function(parentScope) {
      return new Scope(parentScope, this.body, this);
    };

    Code.prototype.compileNode = function(o) {
      var answer, boundfunc, code, exprs, i, j, k, l, len1, len2, len3, len4, len5, len6, lit, m, p, param, params, q, r, ref, ref3, ref4, ref5, ref6, ref7, ref8, splats, uniqs, val, wasEmpty, wrapper;
      if (this.bound && ((ref3 = o.scope.method) != null ? ref3.bound : void 0)) {
        this.context = o.scope.method.context;
      }
      if (this.bound && !this.context) {
        this.context = '_this';
        wrapper = new Code([new Param(new Literal(this.context))], new Block([this]));
        boundfunc = new Call(wrapper, [new Literal('this')]);
        boundfunc.updateLocationDataIfMissing(this.locationData);
        return boundfunc.compileNode(o);
      }
      o.scope = del(o, 'classScope') || this.makeScope(o.scope);
      o.scope.shared = del(o, 'sharedScope');
      o.indent += TAB;
      delete o.bare;
      delete o.isExistentialEquals;
      params = [];
      exprs = [];
      ref4 = this.params;
      for (j = 0, len1 = ref4.length; j < len1; j++) {
        param = ref4[j];
        if (!(param instanceof Expansion)) {
          o.scope.parameter(param.asReference(o));
        }
      }
      ref5 = this.params;
      for (k = 0, len2 = ref5.length; k < len2; k++) {
        param = ref5[k];
        if (!(param.splat || param instanceof Expansion)) {
          continue;
        }
        ref6 = this.params;
        for (l = 0, len3 = ref6.length; l < len3; l++) {
          p = ref6[l];
          if (!(p instanceof Expansion) && p.name.value) {
            o.scope.add(p.name.value, 'var', true);
          }
        }
        splats = new Assign(new Value(new Arr((function() {
          var len4, m, ref7, results;
          ref7 = this.params;
          results = [];
          for (m = 0, len4 = ref7.length; m < len4; m++) {
            p = ref7[m];
            results.push(p.asReference(o));
          }
          return results;
        }).call(this))), new Value(new Literal('arguments')));
        break;
      }
      ref7 = this.params;
      for (m = 0, len4 = ref7.length; m < len4; m++) {
        param = ref7[m];
        if (param.isComplex()) {
          val = ref = param.asReference(o);
          if (param.value) {
            val = new Op('?', ref, param.value);
          }
          exprs.push(new Assign(new Value(param.name), val, '=', {
            param: true
          }));
        } else {
          ref = param;
          if (param.value) {
            lit = new Literal(ref.name.value + ' == null');
            val = new Assign(new Value(param.name), param.value, '=');
            exprs.push(new If(lit, val));
          }
        }
        if (!splats) {
          params.push(ref);
        }
      }
      wasEmpty = this.body.isEmpty();
      if (splats) {
        exprs.unshift(splats);
      }
      if (exprs.length) {
        (ref8 = this.body.expressions).unshift.apply(ref8, exprs);
      }
      for (i = q = 0, len5 = params.length; q < len5; i = ++q) {
        p = params[i];
        params[i] = p.compileToFragments(o);
        o.scope.parameter(fragmentsToText(params[i]));
      }
      uniqs = [];
      this.eachParamName(function(name, node) {
        if (indexOf.call(uniqs, name) >= 0) {
          node.error("multiple parameters named " + name);
        }
        return uniqs.push(name);
      });
      if (!(wasEmpty || this.noReturn)) {
        this.body.makeReturn();
      }
      code = 'function';
      if (this.isGenerator) {
        code += '*';
      }
      if (this.ctor) {
        code += ' ' + this.name;
      }
      code += '(';
      answer = [this.makeCode(code)];
      for (i = r = 0, len6 = params.length; r < len6; i = ++r) {
        p = params[i];
        if (i) {
          answer.push(this.makeCode(", "));
        }
        answer.push.apply(answer, p);
      }
      answer.push(this.makeCode(') {'));
      if (!this.body.isEmpty()) {
        answer = answer.concat(this.makeCode("\n"), this.body.compileWithDeclarations(o), this.makeCode("\n" + this.tab));
      }
      answer.push(this.makeCode('}'));
      if (this.ctor) {
        return [this.makeCode(this.tab)].concat(slice.call(answer));
      }
      if (this.front || (o.level >= LEVEL_ACCESS)) {
        return this.wrapInBraces(answer);
      } else {
        return answer;
      }
    };

    Code.prototype.eachParamName = function(iterator) {
      var j, len1, param, ref3, results;
      ref3 = this.params;
      results = [];
      for (j = 0, len1 = ref3.length; j < len1; j++) {
        param = ref3[j];
        results.push(param.eachName(iterator));
      }
      return results;
    };

    Code.prototype.traverseChildren = function(crossScope, func) {
      if (crossScope) {
        return Code.__super__.traverseChildren.call(this, crossScope, func);
      }
    };

    return Code;

  })(Base);

  exports.Param = Param = (function(superClass1) {
    extend1(Param, superClass1);

    function Param(name1, value1, splat) {
      var name, ref3, token;
      this.name = name1;
      this.value = value1;
      this.splat = splat;
      if (ref3 = (name = this.name.unwrapAll().value), indexOf.call(STRICT_PROSCRIBED, ref3) >= 0) {
        this.name.error("parameter name \"" + name + "\" is not allowed");
      }
      if (this.name instanceof Obj && this.name.generated) {
        token = this.name.objects[0].operatorToken;
        token.error("unexpected " + token.value);
      }
    }

    Param.prototype.children = ['name', 'value'];

    Param.prototype.compileToFragments = function(o) {
      return this.name.compileToFragments(o, LEVEL_LIST);
    };

    Param.prototype.asReference = function(o) {
      var name, node;
      if (this.reference) {
        return this.reference;
      }
      node = this.name;
      if (node["this"]) {
        name = node.properties[0].name.value;
        if (name.reserved) {
          name = "_" + name;
        }
        node = new Literal(o.scope.freeVariable(name));
      } else if (node.isComplex()) {
        node = new Literal(o.scope.freeVariable('arg'));
      }
      node = new Value(node);
      if (this.splat) {
        node = new Splat(node);
      }
      node.updateLocationDataIfMissing(this.locationData);
      return this.reference = node;
    };

    Param.prototype.isComplex = function() {
      return this.name.isComplex();
    };

    Param.prototype.eachName = function(iterator, name) {
      var atParam, j, len1, node, obj, ref3;
      if (name == null) {
        name = this.name;
      }
      atParam = function(obj) {
        return iterator("@" + obj.properties[0].name.value, obj);
      };
      if (name instanceof Literal) {
        return iterator(name.value, name);
      }
      if (name instanceof Value) {
        return atParam(name);
      }
      ref3 = name.objects;
      for (j = 0, len1 = ref3.length; j < len1; j++) {
        obj = ref3[j];
        if (obj instanceof Assign && (obj.context == null)) {
          obj = obj.variable;
        }
        if (obj instanceof Assign) {
          this.eachName(iterator, obj.value.unwrap());
        } else if (obj instanceof Splat) {
          node = obj.name.unwrap();
          iterator(node.value, node);
        } else if (obj instanceof Value) {
          if (obj.isArray() || obj.isObject()) {
            this.eachName(iterator, obj.base);
          } else if (obj["this"]) {
            atParam(obj);
          } else {
            iterator(obj.base.value, obj.base);
          }
        } else if (!(obj instanceof Expansion)) {
          obj.error("illegal parameter " + (obj.compile()));
        }
      }
    };

    return Param;

  })(Base);

  exports.Splat = Splat = (function(superClass1) {
    extend1(Splat, superClass1);

    Splat.prototype.children = ['name'];

    Splat.prototype.isAssignable = YES;

    function Splat(name) {
      this.name = name.compile ? name : new Literal(name);
    }

    Splat.prototype.assigns = function(name) {
      return this.name.assigns(name);
    };

    Splat.prototype.compileToFragments = function(o) {
      return this.name.compileToFragments(o);
    };

    Splat.prototype.unwrap = function() {
      return this.name;
    };

    Splat.compileSplattedArray = function(o, list, apply) {
      var args, base, compiledNode, concatPart, fragments, i, index, j, last, len1, node;
      index = -1;
      while ((node = list[++index]) && !(node instanceof Splat)) {
        continue;
      }
      if (index >= list.length) {
        return [];
      }
      if (list.length === 1) {
        node = list[0];
        fragments = node.compileToFragments(o, LEVEL_LIST);
        if (apply) {
          return fragments;
        }
        return [].concat(node.makeCode((utility('slice', o)) + ".call("), fragments, node.makeCode(")"));
      }
      args = list.slice(index);
      for (i = j = 0, len1 = args.length; j < len1; i = ++j) {
        node = args[i];
        compiledNode = node.compileToFragments(o, LEVEL_LIST);
        args[i] = node instanceof Splat ? [].concat(node.makeCode((utility('slice', o)) + ".call("), compiledNode, node.makeCode(")")) : [].concat(node.makeCode("["), compiledNode, node.makeCode("]"));
      }
      if (index === 0) {
        node = list[0];
        concatPart = node.joinFragmentArrays(args.slice(1), ', ');
        return args[0].concat(node.makeCode(".concat("), concatPart, node.makeCode(")"));
      }
      base = (function() {
        var k, len2, ref3, results;
        ref3 = list.slice(0, index);
        results = [];
        for (k = 0, len2 = ref3.length; k < len2; k++) {
          node = ref3[k];
          results.push(node.compileToFragments(o, LEVEL_LIST));
        }
        return results;
      })();
      base = list[0].joinFragmentArrays(base, ', ');
      concatPart = list[index].joinFragmentArrays(args, ', ');
      last = list[list.length - 1];
      return [].concat(list[0].makeCode("["), base, list[index].makeCode("].concat("), concatPart, last.makeCode(")"));
    };

    return Splat;

  })(Base);

  exports.Expansion = Expansion = (function(superClass1) {
    extend1(Expansion, superClass1);

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

    Expansion.prototype.isComplex = NO;

    Expansion.prototype.compileNode = function(o) {
      return this.error('Expansion must be used inside a destructuring assignment or parameter list');
    };

    Expansion.prototype.asReference = function(o) {
      return this;
    };

    Expansion.prototype.eachName = function(iterator) {};

    return Expansion;

  })(Base);

  exports.While = While = (function(superClass1) {
    extend1(While, superClass1);

    function While(condition, options) {
      this.condition = (options != null ? options.invert : void 0) ? condition.invert() : condition;
      this.guard = options != null ? options.guard : void 0;
    }

    While.prototype.children = ['condition', 'guard', 'body'];

    While.prototype.isStatement = YES;

    While.prototype.makeReturn = function(res) {
      if (res) {
        return While.__super__.makeReturn.apply(this, arguments);
      } else {
        this.returns = !this.jumps({
          loop: true
        });
        return this;
      }
    };

    While.prototype.addBody = function(body1) {
      this.body = body1;
      return this;
    };

    While.prototype.jumps = function() {
      var expressions, j, jumpNode, len1, node;
      expressions = this.body.expressions;
      if (!expressions.length) {
        return false;
      }
      for (j = 0, len1 = expressions.length; j < len1; j++) {
        node = expressions[j];
        if (jumpNode = node.jumps({
          loop: true
        })) {
          return jumpNode;
        }
      }
      return false;
    };

    While.prototype.compileNode = function(o) {
      var answer, body, rvar, set;
      o.indent += TAB;
      set = '';
      body = this.body;
      if (body.isEmpty()) {
        body = this.makeCode('');
      } else {
        if (this.returns) {
          body.makeReturn(rvar = o.scope.freeVariable('results'));
          set = "" + this.tab + rvar + " = [];\n";
        }
        if (this.guard) {
          if (body.expressions.length > 1) {
            body.expressions.unshift(new If((new Parens(this.guard)).invert(), new Literal("continue")));
          } else {
            if (this.guard) {
              body = Block.wrap([new If(this.guard, body)]);
            }
          }
        }
        body = [].concat(this.makeCode("\n"), body.compileToFragments(o, LEVEL_TOP), this.makeCode("\n" + this.tab));
      }
      answer = [].concat(this.makeCode(set + this.tab + "while ("), this.condition.compileToFragments(o, LEVEL_PAREN), this.makeCode(") {"), body, this.makeCode("}"));
      if (this.returns) {
        answer.push(this.makeCode("\n" + this.tab + "return " + rvar + ";"));
      }
      return answer;
    };

    return While;

  })(Base);

  exports.Op = Op = (function(superClass1) {
    var CONVERSIONS, INVERSIONS;

    extend1(Op, superClass1);

    function Op(op, first, second, flip) {
      if (op === 'in') {
        return new In(first, second);
      }
      if (op === 'do') {
        return this.generateDo(first);
      }
      if (op === 'new') {
        if (first instanceof Call && !first["do"] && !first.isNew) {
          return first.newInstance();
        }
        if (first instanceof Code && first.bound || first["do"]) {
          first = new Parens(first);
        }
      }
      this.operator = CONVERSIONS[op] || op;
      this.first = first;
      this.second = second;
      this.flip = !!flip;
      return this;
    }

    CONVERSIONS = {
      '==': '===',
      '!=': '!==',
      'of': 'in',
      'yieldfrom': 'yield*'
    };

    INVERSIONS = {
      '!==': '===',
      '===': '!=='
    };

    Op.prototype.children = ['first', 'second'];

    Op.prototype.isSimpleNumber = NO;

    Op.prototype.isYield = function() {
      var ref3;
      return (ref3 = this.operator) === 'yield' || ref3 === 'yield*';
    };

    Op.prototype.isYieldReturn = function() {
      return this.isYield() && this.first instanceof Return;
    };

    Op.prototype.isUnary = function() {
      return !this.second;
    };

    Op.prototype.isComplex = function() {
      var ref3;
      return !(this.isUnary() && ((ref3 = this.operator) === '+' || ref3 === '-') && this.first instanceof Value && this.first.isSimpleNumber());
    };

    Op.prototype.isChainable = function() {
      var ref3;
      return (ref3 = this.operator) === '<' || ref3 === '>' || ref3 === '>=' || ref3 === '<=' || ref3 === '===' || ref3 === '!==';
    };

    Op.prototype.invert = function() {
      var allInvertable, curr, fst, op, ref3;
      if (this.isChainable() && this.first.isChainable()) {
        allInvertable = true;
        curr = this;
        while (curr && curr.operator) {
          allInvertable && (allInvertable = curr.operator in INVERSIONS);
          curr = curr.first;
        }
        if (!allInvertable) {
          return new Parens(this).invert();
        }
        curr = this;
        while (curr && curr.operator) {
          curr.invert = !curr.invert;
          curr.operator = INVERSIONS[curr.operator];
          curr = curr.first;
        }
        return this;
      } else if (op = INVERSIONS[this.operator]) {
        this.operator = op;
        if (this.first.unwrap() instanceof Op) {
          this.first.invert();
        }
        return this;
      } else if (this.second) {
        return new Parens(this).invert();
      } else if (this.operator === '!' && (fst = this.first.unwrap()) instanceof Op && ((ref3 = fst.operator) === '!' || ref3 === 'in' || ref3 === 'instanceof')) {
        return fst;
      } else {
        return new Op('!', this);
      }
    };

    Op.prototype.unfoldSoak = function(o) {
      var ref3;
      return ((ref3 = this.operator) === '++' || ref3 === '--' || ref3 === 'delete') && unfoldSoak(o, this, 'first');
    };

    Op.prototype.generateDo = function(exp) {
      var call, func, j, len1, param, passedParams, ref, ref3;
      passedParams = [];
      func = exp instanceof Assign && (ref = exp.value.unwrap()) instanceof Code ? ref : exp;
      ref3 = func.params || [];
      for (j = 0, len1 = ref3.length; j < len1; j++) {
        param = ref3[j];
        if (param.value) {
          passedParams.push(param.value);
          delete param.value;
        } else {
          passedParams.push(param);
        }
      }
      call = new Call(exp, passedParams);
      call["do"] = true;
      return call;
    };

    Op.prototype.compileNode = function(o) {
      var answer, isChain, lhs, ref3, ref4, rhs;
      isChain = this.isChainable() && this.first.isChainable();
      if (!isChain) {
        this.first.front = this.front;
      }
      if (this.operator === 'delete' && o.scope.check(this.first.unwrapAll().value)) {
        this.error('delete operand may not be argument or var');
      }
      if (((ref3 = this.operator) === '--' || ref3 === '++') && (ref4 = this.first.unwrapAll().value, indexOf.call(STRICT_PROSCRIBED, ref4) >= 0)) {
        this.error("cannot increment/decrement \"" + (this.first.unwrapAll().value) + "\"");
      }
      if (this.isYield()) {
        return this.compileYield(o);
      }
      if (this.isUnary()) {
        return this.compileUnary(o);
      }
      if (isChain) {
        return this.compileChain(o);
      }
      switch (this.operator) {
        case '?':
          return this.compileExistence(o);
        case '**':
          return this.compilePower(o);
        case '//':
          return this.compileFloorDivision(o);
        case '%%':
          return this.compileModulo(o);
        default:
          lhs = this.first.compileToFragments(o, LEVEL_OP);
          rhs = this.second.compileToFragments(o, LEVEL_OP);
          answer = [].concat(lhs, this.makeCode(" " + this.operator + " "), rhs);
          if (o.level <= LEVEL_OP) {
            return answer;
          } else {
            return this.wrapInBraces(answer);
          }
      }
    };

    Op.prototype.compileChain = function(o) {
      var fragments, fst, ref3, shared;
      ref3 = this.first.second.cache(o), this.first.second = ref3[0], shared = ref3[1];
      fst = this.first.compileToFragments(o, LEVEL_OP);
      fragments = fst.concat(this.makeCode(" " + (this.invert ? '&&' : '||') + " "), shared.compileToFragments(o), this.makeCode(" " + this.operator + " "), this.second.compileToFragments(o, LEVEL_OP));
      return this.wrapInBraces(fragments);
    };

    Op.prototype.compileExistence = function(o) {
      var fst, ref;
      if (this.first.isComplex()) {
        ref = new Literal(o.scope.freeVariable('ref'));
        fst = new Parens(new Assign(ref, this.first));
      } else {
        fst = this.first;
        ref = fst;
      }
      return new If(new Existence(fst), ref, {
        type: 'if'
      }).addElse(this.second).compileToFragments(o);
    };

    Op.prototype.compileUnary = function(o) {
      var op, parts, plusMinus;
      parts = [];
      op = this.operator;
      parts.push([this.makeCode(op)]);
      if (op === '!' && this.first instanceof Existence) {
        this.first.negated = !this.first.negated;
        return this.first.compileToFragments(o);
      }
      if (o.level >= LEVEL_ACCESS) {
        return (new Parens(this)).compileToFragments(o);
      }
      plusMinus = op === '+' || op === '-';
      if ((op === 'new' || op === 'typeof' || op === 'delete') || plusMinus && this.first instanceof Op && this.first.operator === op) {
        parts.push([this.makeCode(' ')]);
      }
      if ((plusMinus && this.first instanceof Op) || (op === 'new' && this.first.isStatement(o))) {
        this.first = new Parens(this.first);
      }
      parts.push(this.first.compileToFragments(o, LEVEL_OP));
      if (this.flip) {
        parts.reverse();
      }
      return this.joinFragmentArrays(parts, '');
    };

    Op.prototype.compileYield = function(o) {
      var op, parts;
      parts = [];
      op = this.operator;
      if (o.scope.parent == null) {
        this.error('yield statements must occur within a function generator.');
      }
      if (indexOf.call(Object.keys(this.first), 'expression') >= 0 && !(this.first instanceof Throw)) {
        if (this.isYieldReturn()) {
          parts.push(this.first.compileToFragments(o, LEVEL_TOP));
        } else if (this.first.expression != null) {
          parts.push(this.first.expression.compileToFragments(o, LEVEL_OP));
        }
      } else {
        parts.push([this.makeCode("(" + op + " ")]);
        parts.push(this.first.compileToFragments(o, LEVEL_OP));
        parts.push([this.makeCode(")")]);
      }
      return this.joinFragmentArrays(parts, '');
    };

    Op.prototype.compilePower = function(o) {
      var pow;
      pow = new Value(new Literal('Math'), [new Access(new Literal('pow'))]);
      return new Call(pow, [this.first, this.second]).compileToFragments(o);
    };

    Op.prototype.compileFloorDivision = function(o) {
      var div, floor;
      floor = new Value(new Literal('Math'), [new Access(new Literal('floor'))]);
      div = new Op('/', this.first, this.second);
      return new Call(floor, [div]).compileToFragments(o);
    };

    Op.prototype.compileModulo = function(o) {
      var mod;
      mod = new Value(new Literal(utility('modulo', o)));
      return new Call(mod, [this.first, this.second]).compileToFragments(o);
    };

    Op.prototype.toString = function(idt) {
      return Op.__super__.toString.call(this, idt, this.constructor.name + ' ' + this.operator);
    };

    return Op;

  })(Base);

  exports.In = In = (function(superClass1) {
    extend1(In, superClass1);

    function In(object, array) {
      this.object = object;
      this.array = array;
    }

    In.prototype.children = ['object', 'array'];

    In.prototype.invert = NEGATE;

    In.prototype.compileNode = function(o) {
      var hasSplat, j, len1, obj, ref3;
      if (this.array instanceof Value && this.array.isArray() && this.array.base.objects.length) {
        ref3 = this.array.base.objects;
        for (j = 0, len1 = ref3.length; j < len1; j++) {
          obj = ref3[j];
          if (!(obj instanceof Splat)) {
            continue;
          }
          hasSplat = true;
          break;
        }
        if (!hasSplat) {
          return this.compileOrTest(o);
        }
      }
      return this.compileLoopTest(o);
    };

    In.prototype.compileOrTest = function(o) {
      var cmp, cnj, i, item, j, len1, ref, ref3, ref4, ref5, sub, tests;
      ref3 = this.object.cache(o, LEVEL_OP), sub = ref3[0], ref = ref3[1];
      ref4 = this.negated ? [' !== ', ' && '] : [' === ', ' || '], cmp = ref4[0], cnj = ref4[1];
      tests = [];
      ref5 = this.array.base.objects;
      for (i = j = 0, len1 = ref5.length; j < len1; i = ++j) {
        item = ref5[i];
        if (i) {
          tests.push(this.makeCode(cnj));
        }
        tests = tests.concat((i ? ref : sub), this.makeCode(cmp), item.compileToFragments(o, LEVEL_ACCESS));
      }
      if (o.level < LEVEL_OP) {
        return tests;
      } else {
        return this.wrapInBraces(tests);
      }
    };

    In.prototype.compileLoopTest = function(o) {
      var fragments, ref, ref3, sub;
      ref3 = this.object.cache(o, LEVEL_LIST), sub = ref3[0], ref = ref3[1];
      fragments = [].concat(this.makeCode(utility('indexOf', o) + ".call("), this.array.compileToFragments(o, LEVEL_LIST), this.makeCode(", "), ref, this.makeCode(") " + (this.negated ? '< 0' : '>= 0')));
      if (fragmentsToText(sub) === fragmentsToText(ref)) {
        return fragments;
      }
      fragments = sub.concat(this.makeCode(', '), fragments);
      if (o.level < LEVEL_LIST) {
        return fragments;
      } else {
        return this.wrapInBraces(fragments);
      }
    };

    In.prototype.toString = function(idt) {
      return In.__super__.toString.call(this, idt, this.constructor.name + (this.negated ? '!' : ''));
    };

    return In;

  })(Base);

  exports.Try = Try = (function(superClass1) {
    extend1(Try, superClass1);

    function Try(attempt, errorVariable, recovery, ensure) {
      this.attempt = attempt;
      this.errorVariable = errorVariable;
      this.recovery = recovery;
      this.ensure = ensure;
    }

    Try.prototype.children = ['attempt', 'recovery', 'ensure'];

    Try.prototype.isStatement = YES;

    Try.prototype.jumps = function(o) {
      var ref3;
      return this.attempt.jumps(o) || ((ref3 = this.recovery) != null ? ref3.jumps(o) : void 0);
    };

    Try.prototype.makeReturn = function(res) {
      if (this.attempt) {
        this.attempt = this.attempt.makeReturn(res);
      }
      if (this.recovery) {
        this.recovery = this.recovery.makeReturn(res);
      }
      return this;
    };

    Try.prototype.compileNode = function(o) {
      var catchPart, ensurePart, generatedErrorVariableName, placeholder, tryPart;
      o.indent += TAB;
      tryPart = this.attempt.compileToFragments(o, LEVEL_TOP);
      catchPart = this.recovery ? (generatedErrorVariableName = o.scope.freeVariable('error'), placeholder = new Literal(generatedErrorVariableName), this.errorVariable ? this.recovery.unshift(new Assign(this.errorVariable, placeholder)) : void 0, [].concat(this.makeCode(" catch ("), placeholder.compileToFragments(o), this.makeCode(") {\n"), this.recovery.compileToFragments(o, LEVEL_TOP), this.makeCode("\n" + this.tab + "}"))) : !(this.ensure || this.recovery) ? [this.makeCode(" catch (" + generatedErrorVariableName + ") {}")] : [];
      ensurePart = this.ensure ? [].concat(this.makeCode(" finally {\n"), this.ensure.compileToFragments(o, LEVEL_TOP), this.makeCode("\n" + this.tab + "}")) : [];
      return [].concat(this.makeCode(this.tab + "try {\n"), tryPart, this.makeCode("\n" + this.tab + "}"), catchPart, ensurePart);
    };

    return Try;

  })(Base);

  exports.Throw = Throw = (function(superClass1) {
    extend1(Throw, superClass1);

    function Throw(expression) {
      this.expression = expression;
    }

    Throw.prototype.children = ['expression'];

    Throw.prototype.isStatement = YES;

    Throw.prototype.jumps = NO;

    Throw.prototype.makeReturn = THIS;

    Throw.prototype.compileNode = function(o) {
      return [].concat(this.makeCode(this.tab + "throw "), this.expression.compileToFragments(o), this.makeCode(";"));
    };

    return Throw;

  })(Base);

  exports.Existence = Existence = (function(superClass1) {
    extend1(Existence, superClass1);

    function Existence(expression) {
      this.expression = expression;
    }

    Existence.prototype.children = ['expression'];

    Existence.prototype.invert = NEGATE;

    Existence.prototype.compileNode = function(o) {
      var cmp, cnj, code, ref3;
      this.expression.front = this.front;
      code = this.expression.compile(o, LEVEL_OP);
      if (IDENTIFIER.test(code) && !o.scope.check(code)) {
        ref3 = this.negated ? ['===', '||'] : ['!==', '&&'], cmp = ref3[0], cnj = ref3[1];
        code = "typeof " + code + " " + cmp + " \"undefined\" " + cnj + " " + code + " " + cmp + " null";
      } else {
        code = code + " " + (this.negated ? '==' : '!=') + " null";
      }
      return [this.makeCode(o.level <= LEVEL_COND ? code : "(" + code + ")")];
    };

    return Existence;

  })(Base);

  exports.Parens = Parens = (function(superClass1) {
    extend1(Parens, superClass1);

    function Parens(body1) {
      this.body = body1;
    }

    Parens.prototype.children = ['body'];

    Parens.prototype.unwrap = function() {
      return this.body;
    };

    Parens.prototype.isComplex = function() {
      return this.body.isComplex();
    };

    Parens.prototype.compileNode = function(o) {
      var bare, expr, fragments;
      expr = this.body.unwrap();
      if (expr instanceof Value && expr.isAtomic()) {
        expr.front = this.front;
        return expr.compileToFragments(o);
      }
      fragments = expr.compileToFragments(o, LEVEL_PAREN);
      bare = o.level < LEVEL_OP && (expr instanceof Op || expr instanceof Call || (expr instanceof For && expr.returns));
      if (bare) {
        return fragments;
      } else {
        return this.wrapInBraces(fragments);
      }
    };

    return Parens;

  })(Base);

  exports.For = For = (function(superClass1) {
    extend1(For, superClass1);

    function For(body, source) {
      var ref3;
      this.source = source.source, this.guard = source.guard, this.step = source.step, this.name = source.name, this.index = source.index;
      this.body = Block.wrap([body]);
      this.own = !!source.own;
      this.object = !!source.object;
      if (this.object) {
        ref3 = [this.index, this.name], this.name = ref3[0], this.index = ref3[1];
      }
      if (this.index instanceof Value) {
        this.index.error('index cannot be a pattern matching expression');
      }
      this.range = this.source instanceof Value && this.source.base instanceof Range && !this.source.properties.length;
      this.pattern = this.name instanceof Value;
      if (this.range && this.index) {
        this.index.error('indexes do not apply to range loops');
      }
      if (this.range && this.pattern) {
        this.name.error('cannot pattern match over range loops');
      }
      if (this.own && !this.object) {
        this.name.error('cannot use own with for-in');
      }
      this.returns = false;
    }

    For.prototype.children = ['body', 'source', 'guard', 'step'];

    For.prototype.compileNode = function(o) {
      var body, bodyFragments, compare, compareDown, declare, declareDown, defPart, defPartFragments, down, forPartFragments, guardPart, idt1, increment, index, ivar, kvar, kvarAssign, last, lvar, name, namePart, ref, ref3, ref4, resultPart, returnResult, rvar, scope, source, step, stepNum, stepVar, svar, varPart;
      body = Block.wrap([this.body]);
      ref3 = body.expressions, last = ref3[ref3.length - 1];
      if ((last != null ? last.jumps() : void 0) instanceof Return) {
        this.returns = false;
      }
      source = this.range ? this.source.base : this.source;
      scope = o.scope;
      if (!this.pattern) {
        name = this.name && (this.name.compile(o, LEVEL_LIST));
      }
      index = this.index && (this.index.compile(o, LEVEL_LIST));
      if (name && !this.pattern) {
        scope.find(name);
      }
      if (index) {
        scope.find(index);
      }
      if (this.returns) {
        rvar = scope.freeVariable('results');
      }
      ivar = (this.object && index) || scope.freeVariable('i', {
        single: true
      });
      kvar = (this.range && name) || index || ivar;
      kvarAssign = kvar !== ivar ? kvar + " = " : "";
      if (this.step && !this.range) {
        ref4 = this.cacheToCodeFragments(this.step.cache(o, LEVEL_LIST, isComplexOrAssignable)), step = ref4[0], stepVar = ref4[1];
        stepNum = stepVar.match(NUMBER);
      }
      if (this.pattern) {
        name = ivar;
      }
      varPart = '';
      guardPart = '';
      defPart = '';
      idt1 = this.tab + TAB;
      if (this.range) {
        forPartFragments = source.compileToFragments(merge(o, {
          index: ivar,
          name: name,
          step: this.step,
          isComplex: isComplexOrAssignable
        }));
      } else {
        svar = this.source.compile(o, LEVEL_LIST);
        if ((name || this.own) && !IDENTIFIER.test(svar)) {
          defPart += "" + this.tab + (ref = scope.freeVariable('ref')) + " = " + svar + ";\n";
          svar = ref;
        }
        if (name && !this.pattern) {
          namePart = name + " = " + svar + "[" + kvar + "]";
        }
        if (!this.object) {
          if (step !== stepVar) {
            defPart += "" + this.tab + step + ";\n";
          }
          if (!(this.step && stepNum && (down = parseNum(stepNum[0]) < 0))) {
            lvar = scope.freeVariable('len');
          }
          declare = "" + kvarAssign + ivar + " = 0, " + lvar + " = " + svar + ".length";
          declareDown = "" + kvarAssign + ivar + " = " + svar + ".length - 1";
          compare = ivar + " < " + lvar;
          compareDown = ivar + " >= 0";
          if (this.step) {
            if (stepNum) {
              if (down) {
                compare = compareDown;
                declare = declareDown;
              }
            } else {
              compare = stepVar + " > 0 ? " + compare + " : " + compareDown;
              declare = "(" + stepVar + " > 0 ? (" + declare + ") : " + declareDown + ")";
            }
            increment = ivar + " += " + stepVar;
          } else {
            increment = "" + (kvar !== ivar ? "++" + ivar : ivar + "++");
          }
          forPartFragments = [this.makeCode(declare + "; " + compare + "; " + kvarAssign + increment)];
        }
      }
      if (this.returns) {
        resultPart = "" + this.tab + rvar + " = [];\n";
        returnResult = "\n" + this.tab + "return " + rvar + ";";
        body.makeReturn(rvar);
      }
      if (this.guard) {
        if (body.expressions.length > 1) {
          body.expressions.unshift(new If((new Parens(this.guard)).invert(), new Literal("continue")));
        } else {
          if (this.guard) {
            body = Block.wrap([new If(this.guard, body)]);
          }
        }
      }
      if (this.pattern) {
        body.expressions.unshift(new Assign(this.name, new Literal(svar + "[" + kvar + "]")));
      }
      defPartFragments = [].concat(this.makeCode(defPart), this.pluckDirectCall(o, body));
      if (namePart) {
        varPart = "\n" + idt1 + namePart + ";";
      }
      if (this.object) {
        forPartFragments = [this.makeCode(kvar + " in " + svar)];
        if (this.own) {
          guardPart = "\n" + idt1 + "if (!" + (utility('hasProp', o)) + ".call(" + svar + ", " + kvar + ")) continue;";
        }
      }
      bodyFragments = body.compileToFragments(merge(o, {
        indent: idt1
      }), LEVEL_TOP);
      if (bodyFragments && (bodyFragments.length > 0)) {
        bodyFragments = [].concat(this.makeCode("\n"), bodyFragments, this.makeCode("\n"));
      }
      return [].concat(defPartFragments, this.makeCode("" + (resultPart || '') + this.tab + "for ("), forPartFragments, this.makeCode(") {" + guardPart + varPart), bodyFragments, this.makeCode(this.tab + "}" + (returnResult || '')));
    };

    For.prototype.pluckDirectCall = function(o, body) {
      var base, defs, expr, fn, idx, j, len1, ref, ref3, ref4, ref5, ref6, ref7, ref8, ref9, val;
      defs = [];
      ref3 = body.expressions;
      for (idx = j = 0, len1 = ref3.length; j < len1; idx = ++j) {
        expr = ref3[idx];
        expr = expr.unwrapAll();
        if (!(expr instanceof Call)) {
          continue;
        }
        val = (ref4 = expr.variable) != null ? ref4.unwrapAll() : void 0;
        if (!((val instanceof Code) || (val instanceof Value && ((ref5 = val.base) != null ? ref5.unwrapAll() : void 0) instanceof Code && val.properties.length === 1 && ((ref6 = (ref7 = val.properties[0].name) != null ? ref7.value : void 0) === 'call' || ref6 === 'apply')))) {
          continue;
        }
        fn = ((ref8 = val.base) != null ? ref8.unwrapAll() : void 0) || val;
        ref = new Literal(o.scope.freeVariable('fn'));
        base = new Value(ref);
        if (val.base) {
          ref9 = [base, val], val.base = ref9[0], base = ref9[1];
        }
        body.expressions[idx] = new Call(base, expr.args);
        defs = defs.concat(this.makeCode(this.tab), new Assign(ref, fn).compileToFragments(o, LEVEL_TOP), this.makeCode(';\n'));
      }
      return defs;
    };

    return For;

  })(While);

  exports.Switch = Switch = (function(superClass1) {
    extend1(Switch, superClass1);

    function Switch(subject, cases, otherwise) {
      this.subject = subject;
      this.cases = cases;
      this.otherwise = otherwise;
    }

    Switch.prototype.children = ['subject', 'cases', 'otherwise'];

    Switch.prototype.isStatement = YES;

    Switch.prototype.jumps = function(o) {
      var block, conds, j, jumpNode, len1, ref3, ref4, ref5;
      if (o == null) {
        o = {
          block: true
        };
      }
      ref3 = this.cases;
      for (j = 0, len1 = ref3.length; j < len1; j++) {
        ref4 = ref3[j], conds = ref4[0], block = ref4[1];
        if (jumpNode = block.jumps(o)) {
          return jumpNode;
        }
      }
      return (ref5 = this.otherwise) != null ? ref5.jumps(o) : void 0;
    };

    Switch.prototype.makeReturn = function(res) {
      var j, len1, pair, ref3, ref4;
      ref3 = this.cases;
      for (j = 0, len1 = ref3.length; j < len1; j++) {
        pair = ref3[j];
        pair[1].makeReturn(res);
      }
      if (res) {
        this.otherwise || (this.otherwise = new Block([new Literal('void 0')]));
      }
      if ((ref4 = this.otherwise) != null) {
        ref4.makeReturn(res);
      }
      return this;
    };

    Switch.prototype.compileNode = function(o) {
      var block, body, cond, conditions, expr, fragments, i, idt1, idt2, j, k, len1, len2, ref3, ref4, ref5;
      idt1 = o.indent + TAB;
      idt2 = o.indent = idt1 + TAB;
      fragments = [].concat(this.makeCode(this.tab + "switch ("), (this.subject ? this.subject.compileToFragments(o, LEVEL_PAREN) : this.makeCode("false")), this.makeCode(") {\n"));
      ref3 = this.cases;
      for (i = j = 0, len1 = ref3.length; j < len1; i = ++j) {
        ref4 = ref3[i], conditions = ref4[0], block = ref4[1];
        ref5 = flatten([conditions]);
        for (k = 0, len2 = ref5.length; k < len2; k++) {
          cond = ref5[k];
          if (!this.subject) {
            cond = cond.invert();
          }
          fragments = fragments.concat(this.makeCode(idt1 + "case "), cond.compileToFragments(o, LEVEL_PAREN), this.makeCode(":\n"));
        }
        if ((body = block.compileToFragments(o, LEVEL_TOP)).length > 0) {
          fragments = fragments.concat(body, this.makeCode('\n'));
        }
        if (i === this.cases.length - 1 && !this.otherwise) {
          break;
        }
        expr = this.lastNonComment(block.expressions);
        if (expr instanceof Return || (expr instanceof Literal && expr.jumps() && expr.value !== 'debugger')) {
          continue;
        }
        fragments.push(cond.makeCode(idt2 + 'break;\n'));
      }
      if (this.otherwise && this.otherwise.expressions.length) {
        fragments.push.apply(fragments, [this.makeCode(idt1 + "default:\n")].concat(slice.call(this.otherwise.compileToFragments(o, LEVEL_TOP)), [this.makeCode("\n")]));
      }
      fragments.push(this.makeCode(this.tab + '}'));
      return fragments;
    };

    return Switch;

  })(Base);

  exports.If = If = (function(superClass1) {
    extend1(If, superClass1);

    function If(condition, body1, options) {
      this.body = body1;
      if (options == null) {
        options = {};
      }
      this.condition = options.type === 'unless' ? condition.invert() : condition;
      this.elseBody = null;
      this.isChain = false;
      this.soak = options.soak;
    }

    If.prototype.children = ['condition', 'body', 'elseBody'];

    If.prototype.bodyNode = function() {
      var ref3;
      return (ref3 = this.body) != null ? ref3.unwrap() : void 0;
    };

    If.prototype.elseBodyNode = function() {
      var ref3;
      return (ref3 = this.elseBody) != null ? ref3.unwrap() : void 0;
    };

    If.prototype.addElse = function(elseBody) {
      if (this.isChain) {
        this.elseBodyNode().addElse(elseBody);
      } else {
        this.isChain = elseBody instanceof If;
        this.elseBody = this.ensureBlock(elseBody);
        this.elseBody.updateLocationDataIfMissing(elseBody.locationData);
      }
      return this;
    };

    If.prototype.isStatement = function(o) {
      var ref3;
      return (o != null ? o.level : void 0) === LEVEL_TOP || this.bodyNode().isStatement(o) || ((ref3 = this.elseBodyNode()) != null ? ref3.isStatement(o) : void 0);
    };

    If.prototype.jumps = function(o) {
      var ref3;
      return this.body.jumps(o) || ((ref3 = this.elseBody) != null ? ref3.jumps(o) : void 0);
    };

    If.prototype.compileNode = function(o) {
      if (this.isStatement(o)) {
        return this.compileStatement(o);
      } else {
        return this.compileExpression(o);
      }
    };

    If.prototype.makeReturn = function(res) {
      if (res) {
        this.elseBody || (this.elseBody = new Block([new Literal('void 0')]));
      }
      this.body && (this.body = new Block([this.body.makeReturn(res)]));
      this.elseBody && (this.elseBody = new Block([this.elseBody.makeReturn(res)]));
      return this;
    };

    If.prototype.ensureBlock = function(node) {
      if (node instanceof Block) {
        return node;
      } else {
        return new Block([node]);
      }
    };

    If.prototype.compileStatement = function(o) {
      var answer, body, child, cond, exeq, ifPart, indent;
      child = del(o, 'chainChild');
      exeq = del(o, 'isExistentialEquals');
      if (exeq) {
        return new If(this.condition.invert(), this.elseBodyNode(), {
          type: 'if'
        }).compileToFragments(o);
      }
      indent = o.indent + TAB;
      cond = this.condition.compileToFragments(o, LEVEL_PAREN);
      body = this.ensureBlock(this.body).compileToFragments(merge(o, {
        indent: indent
      }));
      ifPart = [].concat(this.makeCode("if ("), cond, this.makeCode(") {\n"), body, this.makeCode("\n" + this.tab + "}"));
      if (!child) {
        ifPart.unshift(this.makeCode(this.tab));
      }
      if (!this.elseBody) {
        return ifPart;
      }
      answer = ifPart.concat(this.makeCode(' else '));
      if (this.isChain) {
        o.chainChild = true;
        answer = answer.concat(this.elseBody.unwrap().compileToFragments(o, LEVEL_TOP));
      } else {
        answer = answer.concat(this.makeCode("{\n"), this.elseBody.compileToFragments(merge(o, {
          indent: indent
        }), LEVEL_TOP), this.makeCode("\n" + this.tab + "}"));
      }
      return answer;
    };

    If.prototype.compileExpression = function(o) {
      var alt, body, cond, fragments;
      cond = this.condition.compileToFragments(o, LEVEL_COND);
      body = this.bodyNode().compileToFragments(o, LEVEL_LIST);
      alt = this.elseBodyNode() ? this.elseBodyNode().compileToFragments(o, LEVEL_LIST) : [this.makeCode('void 0')];
      fragments = cond.concat(this.makeCode(" ? "), body, this.makeCode(" : "), alt);
      if (o.level >= LEVEL_COND) {
        return this.wrapInBraces(fragments);
      } else {
        return fragments;
      }
    };

    If.prototype.unfoldSoak = function() {
      return this.soak && this;
    };

    return If;

  })(Base);

  UTILITIES = {
    extend: function(o) {
      return "function(child, parent) { for (var key in parent) { if (" + (utility('hasProp', o)) + ".call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }";
    },
    bind: function() {
      return 'function(fn, me){ return function(){ return fn.apply(me, arguments); }; }';
    },
    indexOf: function() {
      return "[].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }";
    },
    modulo: function() {
      return "function(a, b) { return (+a % (b = +b) + b) % b; }";
    },
    hasProp: function() {
      return '{}.hasOwnProperty';
    },
    slice: function() {
      return '[].slice';
    }
  };

  LEVEL_TOP = 1;

  LEVEL_PAREN = 2;

  LEVEL_LIST = 3;

  LEVEL_COND = 4;

  LEVEL_OP = 5;

  LEVEL_ACCESS = 6;

  TAB = '  ';

  IDENTIFIER = /^(?!\d)[$\w\x7f-\uffff]+$/;

  SIMPLENUM = /^[+-]?\d+$/;

  HEXNUM = /^[+-]?0x[\da-f]+/i;

  NUMBER = /^[+-]?(?:0x[\da-f]+|\d*\.?\d+(?:e[+-]?\d+)?)$/i;

  IS_STRING = /^['"]/;

  IS_REGEX = /^\//;

  utility = function(name, o) {
    var ref, root;
    root = o.scope.root;
    if (name in root.utilities) {
      return root.utilities[name];
    } else {
      ref = root.freeVariable(name);
      root.assign(ref, UTILITIES[name](o));
      return root.utilities[name] = ref;
    }
  };

  multident = function(code, tab) {
    code = code.replace(/\n/g, '$&' + tab);
    return code.replace(/\s+$/, '');
  };

  parseNum = function(x) {
    if (x == null) {
      return 0;
    } else if (x.match(HEXNUM)) {
      return parseInt(x, 16);
    } else {
      return parseFloat(x);
    }
  };

  isLiteralArguments = function(node) {
    return node instanceof Literal && node.value === 'arguments' && !node.asKey;
  };

  isLiteralThis = function(node) {
    return (node instanceof Literal && node.value === 'this' && !node.asKey) || (node instanceof Code && node.bound) || (node instanceof Call && node.isSuper);
  };

  isComplexOrAssignable = function(node) {
    return node.isComplex() || (typeof node.isAssignable === "function" ? node.isAssignable() : void 0);
  };

  unfoldSoak = function(o, parent, name) {
    var ifn;
    if (!(ifn = parent[name].unfoldSoak(o))) {
      return;
    }
    parent[name] = ifn.body;
    ifn.body = new Value(parent);
    return ifn;
  };

}).call(this);

},{"./helpers":"coffee-script/lib/coffee-script/helpers","./lexer":"coffee-script/lib/coffee-script/lexer","./scope":"coffee-script/lib/coffee-script/scope"}],"coffee-script/lib/coffee-script/parser":[function(require,module,exports){
(function (process){
/* parser generated by jison 0.4.15 */
/*
  Returns a Parser object of the following structure:

  Parser: {
    yy: {}
  }

  Parser.prototype: {
    yy: {},
    trace: function(),
    symbols_: {associative list: name ==> number},
    terminals_: {associative list: number ==> name},
    productions_: [...],
    performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$),
    table: [...],
    defaultActions: {...},
    parseError: function(str, hash),
    parse: function(input),

    lexer: {
        EOF: 1,
        parseError: function(str, hash),
        setInput: function(input),
        input: function(),
        unput: function(str),
        more: function(),
        less: function(n),
        pastInput: function(),
        upcomingInput: function(),
        showPosition: function(),
        test_match: function(regex_match_array, rule_index),
        next: function(),
        lex: function(),
        begin: function(condition),
        popState: function(),
        _currentRules: function(),
        topState: function(),
        pushState: function(condition),

        options: {
            ranges: boolean           (optional: true ==> token location info will include a .range[] member)
            flex: boolean             (optional: true ==> flex-like lexing behaviour where the rules are tested exhaustively to find the longest match)
            backtrack_lexer: boolean  (optional: true ==> lexer regexes are tested in order and for each matching regex the action code is invoked; the lexer terminates the scan when a token is returned by the action code)
        },

        performAction: function(yy, yy_, $avoiding_name_collisions, YY_START),
        rules: [...],
        conditions: {associative list: name ==> set},
    }
  }


  token location info (@$, _$, etc.): {
    first_line: n,
    last_line: n,
    first_column: n,
    last_column: n,
    range: [start_number, end_number]       (where the numbers are indexes into the input string, regular zero-based)
  }


  the parseError function receives a 'hash' object with these members for lexer and parser errors: {
    text:        (matched text)
    token:       (the produced terminal token, if any)
    line:        (yylineno)
  }
  while parser (grammar) errors will also provide these members, i.e. parser errors deliver a superset of attributes: {
    loc:         (yylloc)
    expected:    (string describing the set of expected tokens)
    recoverable: (boolean: TRUE when the parser has a error recovery rule available for this particular error)
  }
*/
var parser = (function(){
var o=function(k,v,o,l){for(o=o||{},l=k.length;l--;o[k[l]]=v);return o},$V0=[1,20],$V1=[1,75],$V2=[1,71],$V3=[1,76],$V4=[1,77],$V5=[1,73],$V6=[1,74],$V7=[1,50],$V8=[1,52],$V9=[1,53],$Va=[1,54],$Vb=[1,55],$Vc=[1,45],$Vd=[1,46],$Ve=[1,27],$Vf=[1,60],$Vg=[1,61],$Vh=[1,70],$Vi=[1,43],$Vj=[1,26],$Vk=[1,58],$Vl=[1,59],$Vm=[1,57],$Vn=[1,38],$Vo=[1,44],$Vp=[1,56],$Vq=[1,65],$Vr=[1,66],$Vs=[1,67],$Vt=[1,68],$Vu=[1,42],$Vv=[1,64],$Vw=[1,29],$Vx=[1,30],$Vy=[1,31],$Vz=[1,32],$VA=[1,33],$VB=[1,34],$VC=[1,35],$VD=[1,78],$VE=[1,6,26,34,109],$VF=[1,88],$VG=[1,81],$VH=[1,80],$VI=[1,79],$VJ=[1,82],$VK=[1,83],$VL=[1,84],$VM=[1,85],$VN=[1,86],$VO=[1,87],$VP=[1,91],$VQ=[1,6,25,26,34,56,61,64,80,85,93,98,100,109,111,112,113,117,118,133,136,137,142,143,144,145,146,147,148],$VR=[1,97],$VS=[1,98],$VT=[1,99],$VU=[1,100],$VV=[1,102],$VW=[1,103],$VX=[1,96],$VY=[2,115],$VZ=[1,6,25,26,34,56,61,64,73,74,75,76,78,80,81,85,91,92,93,98,100,109,111,112,113,117,118,133,136,137,142,143,144,145,146,147,148],$V_=[2,82],$V$=[1,108],$V01=[2,61],$V11=[1,112],$V21=[1,117],$V31=[1,118],$V41=[1,120],$V51=[1,6,25,26,34,46,56,61,64,73,74,75,76,78,80,81,85,91,92,93,98,100,109,111,112,113,117,118,133,136,137,142,143,144,145,146,147,148],$V61=[2,79],$V71=[1,6,26,34,56,61,64,80,85,93,98,100,109,111,112,113,117,118,133,136,137,142,143,144,145,146,147,148],$V81=[1,155],$V91=[1,157],$Va1=[1,152],$Vb1=[1,6,25,26,34,46,56,61,64,73,74,75,76,78,80,81,85,87,91,92,93,98,100,109,111,112,113,117,118,133,136,137,140,141,142,143,144,145,146,147,148,149],$Vc1=[2,98],$Vd1=[1,6,25,26,34,49,56,61,64,73,74,75,76,78,80,81,85,91,92,93,98,100,109,111,112,113,117,118,133,136,137,142,143,144,145,146,147,148],$Ve1=[1,6,25,26,34,46,49,56,61,64,73,74,75,76,78,80,81,85,87,91,92,93,98,100,109,111,112,113,117,118,124,125,133,136,137,140,141,142,143,144,145,146,147,148,149],$Vf1=[1,207],$Vg1=[1,206],$Vh1=[1,6,25,26,34,38,56,61,64,73,74,75,76,78,80,81,85,91,92,93,98,100,109,111,112,113,117,118,133,136,137,142,143,144,145,146,147,148],$Vi1=[2,59],$Vj1=[1,217],$Vk1=[6,25,26,56,61],$Vl1=[6,25,26,46,56,61,64],$Vm1=[1,6,25,26,34,56,61,64,80,85,93,98,100,109,111,112,113,117,118,133,136,137,143,145,146,147,148],$Vn1=[1,6,25,26,34,56,61,64,80,85,93,98,100,109,111,112,113,117,118,133],$Vo1=[73,74,75,76,78,81,91,92],$Vp1=[1,236],$Vq1=[2,136],$Vr1=[1,6,25,26,34,46,56,61,64,73,74,75,76,78,80,81,85,91,92,93,98,100,109,111,112,113,117,118,124,125,133,136,137,142,143,144,145,146,147,148],$Vs1=[1,245],$Vt1=[6,25,26,61,93,98],$Vu1=[1,6,25,26,34,56,61,64,80,85,93,98,100,109,118,133],$Vv1=[1,6,25,26,34,56,61,64,80,85,93,98,100,109,112,118,133],$Vw1=[124,125],$Vx1=[61,124,125],$Vy1=[1,256],$Vz1=[6,25,26,61,85],$VA1=[6,25,26,49,61,85],$VB1=[6,25,26,46,49,61,85],$VC1=[1,6,25,26,34,56,61,64,80,85,93,98,100,109,111,112,113,117,118,133,136,137,145,146,147,148],$VD1=[11,28,30,32,33,36,37,40,41,42,43,44,52,53,54,58,59,80,83,86,90,95,96,97,103,107,108,111,113,115,117,126,132,134,135,136,137,138,140,141],$VE1=[2,125],$VF1=[6,25,26],$VG1=[2,60],$VH1=[1,270],$VI1=[1,271],$VJ1=[1,6,25,26,34,56,61,64,80,85,93,98,100,105,106,109,111,112,113,117,118,128,130,133,136,137,142,143,144,145,146,147,148],$VK1=[26,128,130],$VL1=[1,6,26,34,56,61,64,80,85,93,98,100,109,112,118,133],$VM1=[2,74],$VN1=[1,293],$VO1=[1,294],$VP1=[1,6,25,26,34,56,61,64,80,85,93,98,100,109,111,112,113,117,118,128,133,136,137,142,143,144,145,146,147,148],$VQ1=[1,6,25,26,34,56,61,64,80,85,93,98,100,109,111,113,117,118,133],$VR1=[1,305],$VS1=[1,306],$VT1=[6,25,26,61],$VU1=[1,6,25,26,34,56,61,64,80,85,93,98,100,105,109,111,112,113,117,118,133,136,137,142,143,144,145,146,147,148],$VV1=[25,61];
var parser = {trace: function trace() { },
yy: {},
symbols_: {"error":2,"Root":3,"Body":4,"Line":5,"TERMINATOR":6,"Expression":7,"Statement":8,"Return":9,"Comment":10,"STATEMENT":11,"Value":12,"Invocation":13,"Code":14,"Operation":15,"Assign":16,"If":17,"Try":18,"While":19,"For":20,"Switch":21,"Class":22,"Throw":23,"Block":24,"INDENT":25,"OUTDENT":26,"Identifier":27,"IDENTIFIER":28,"AlphaNumeric":29,"NUMBER":30,"String":31,"STRING":32,"STRING_START":33,"STRING_END":34,"Regex":35,"REGEX":36,"REGEX_START":37,"REGEX_END":38,"Literal":39,"JS":40,"DEBUGGER":41,"UNDEFINED":42,"NULL":43,"BOOL":44,"Assignable":45,"=":46,"AssignObj":47,"ObjAssignable":48,":":49,"SimpleObjAssignable":50,"ThisProperty":51,"RETURN":52,"HERECOMMENT":53,"PARAM_START":54,"ParamList":55,"PARAM_END":56,"FuncGlyph":57,"->":58,"=>":59,"OptComma":60,",":61,"Param":62,"ParamVar":63,"...":64,"Array":65,"Object":66,"Splat":67,"SimpleAssignable":68,"Accessor":69,"Parenthetical":70,"Range":71,"This":72,".":73,"?.":74,"::":75,"?::":76,"Index":77,"INDEX_START":78,"IndexValue":79,"INDEX_END":80,"INDEX_SOAK":81,"Slice":82,"{":83,"AssignList":84,"}":85,"CLASS":86,"EXTENDS":87,"OptFuncExist":88,"Arguments":89,"SUPER":90,"FUNC_EXIST":91,"CALL_START":92,"CALL_END":93,"ArgList":94,"THIS":95,"@":96,"[":97,"]":98,"RangeDots":99,"..":100,"Arg":101,"SimpleArgs":102,"TRY":103,"Catch":104,"FINALLY":105,"CATCH":106,"THROW":107,"(":108,")":109,"WhileSource":110,"WHILE":111,"WHEN":112,"UNTIL":113,"Loop":114,"LOOP":115,"ForBody":116,"FOR":117,"BY":118,"ForStart":119,"ForSource":120,"ForVariables":121,"OWN":122,"ForValue":123,"FORIN":124,"FOROF":125,"SWITCH":126,"Whens":127,"ELSE":128,"When":129,"LEADING_WHEN":130,"IfBlock":131,"IF":132,"POST_IF":133,"UNARY":134,"UNARY_MATH":135,"-":136,"+":137,"YIELD":138,"FROM":139,"--":140,"++":141,"?":142,"MATH":143,"**":144,"SHIFT":145,"COMPARE":146,"LOGIC":147,"RELATION":148,"COMPOUND_ASSIGN":149,"$accept":0,"$end":1},
terminals_: {2:"error",6:"TERMINATOR",11:"STATEMENT",25:"INDENT",26:"OUTDENT",28:"IDENTIFIER",30:"NUMBER",32:"STRING",33:"STRING_START",34:"STRING_END",36:"REGEX",37:"REGEX_START",38:"REGEX_END",40:"JS",41:"DEBUGGER",42:"UNDEFINED",43:"NULL",44:"BOOL",46:"=",49:":",52:"RETURN",53:"HERECOMMENT",54:"PARAM_START",56:"PARAM_END",58:"->",59:"=>",61:",",64:"...",73:".",74:"?.",75:"::",76:"?::",78:"INDEX_START",80:"INDEX_END",81:"INDEX_SOAK",83:"{",85:"}",86:"CLASS",87:"EXTENDS",90:"SUPER",91:"FUNC_EXIST",92:"CALL_START",93:"CALL_END",95:"THIS",96:"@",97:"[",98:"]",100:"..",103:"TRY",105:"FINALLY",106:"CATCH",107:"THROW",108:"(",109:")",111:"WHILE",112:"WHEN",113:"UNTIL",115:"LOOP",117:"FOR",118:"BY",122:"OWN",124:"FORIN",125:"FOROF",126:"SWITCH",128:"ELSE",130:"LEADING_WHEN",132:"IF",133:"POST_IF",134:"UNARY",135:"UNARY_MATH",136:"-",137:"+",138:"YIELD",139:"FROM",140:"--",141:"++",142:"?",143:"MATH",144:"**",145:"SHIFT",146:"COMPARE",147:"LOGIC",148:"RELATION",149:"COMPOUND_ASSIGN"},
productions_: [0,[3,0],[3,1],[4,1],[4,3],[4,2],[5,1],[5,1],[8,1],[8,1],[8,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[24,2],[24,3],[27,1],[29,1],[29,1],[31,1],[31,3],[35,1],[35,3],[39,1],[39,1],[39,1],[39,1],[39,1],[39,1],[39,1],[16,3],[16,4],[16,5],[47,1],[47,3],[47,5],[47,3],[47,5],[47,1],[50,1],[50,1],[48,1],[48,1],[9,2],[9,1],[10,1],[14,5],[14,2],[57,1],[57,1],[60,0],[60,1],[55,0],[55,1],[55,3],[55,4],[55,6],[62,1],[62,2],[62,3],[62,1],[63,1],[63,1],[63,1],[63,1],[67,2],[68,1],[68,2],[68,2],[68,1],[45,1],[45,1],[45,1],[12,1],[12,1],[12,1],[12,1],[12,1],[69,2],[69,2],[69,2],[69,2],[69,1],[69,1],[77,3],[77,2],[79,1],[79,1],[66,4],[84,0],[84,1],[84,3],[84,4],[84,6],[22,1],[22,2],[22,3],[22,4],[22,2],[22,3],[22,4],[22,5],[13,3],[13,3],[13,1],[13,2],[88,0],[88,1],[89,2],[89,4],[72,1],[72,1],[51,2],[65,2],[65,4],[99,1],[99,1],[71,5],[82,3],[82,2],[82,2],[82,1],[94,1],[94,3],[94,4],[94,4],[94,6],[101,1],[101,1],[101,1],[102,1],[102,3],[18,2],[18,3],[18,4],[18,5],[104,3],[104,3],[104,2],[23,2],[70,3],[70,5],[110,2],[110,4],[110,2],[110,4],[19,2],[19,2],[19,2],[19,1],[114,2],[114,2],[20,2],[20,2],[20,2],[116,2],[116,4],[116,2],[119,2],[119,3],[123,1],[123,1],[123,1],[123,1],[121,1],[121,3],[120,2],[120,2],[120,4],[120,4],[120,4],[120,6],[120,6],[21,5],[21,7],[21,4],[21,6],[127,1],[127,2],[129,3],[129,4],[131,3],[131,5],[17,1],[17,3],[17,3],[17,3],[15,2],[15,2],[15,2],[15,2],[15,2],[15,2],[15,3],[15,2],[15,2],[15,2],[15,2],[15,2],[15,3],[15,3],[15,3],[15,3],[15,3],[15,3],[15,3],[15,3],[15,3],[15,5],[15,4],[15,3]],
performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate /* action[1] */, $$ /* vstack */, _$ /* lstack */) {
/* this == yyval */

var $0 = $$.length - 1;
switch (yystate) {
case 1:
return this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Block);
break;
case 2:
return this.$ = $$[$0];
break;
case 3:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(yy.Block.wrap([$$[$0]]));
break;
case 4:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])($$[$0-2].push($$[$0]));
break;
case 5:
this.$ = $$[$0-1];
break;
case 6: case 7: case 8: case 9: case 11: case 12: case 13: case 14: case 15: case 16: case 17: case 18: case 19: case 20: case 21: case 22: case 27: case 32: case 34: case 47: case 48: case 49: case 50: case 51: case 59: case 60: case 70: case 71: case 72: case 73: case 78: case 79: case 82: case 86: case 92: case 136: case 137: case 139: case 169: case 170: case 186: case 192:
this.$ = $$[$0];
break;
case 10: case 25: case 26: case 28: case 30: case 33: case 35:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Literal($$[$0]));
break;
case 23:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Block);
break;
case 24: case 31: case 93:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])($$[$0-1]);
break;
case 29: case 149:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.Parens($$[$0-1]));
break;
case 36:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Undefined);
break;
case 37:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Null);
break;
case 38:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Bool($$[$0]));
break;
case 39:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.Assign($$[$0-2], $$[$0]));
break;
case 40:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])(new yy.Assign($$[$0-3], $$[$0]));
break;
case 41:
this.$ = yy.addLocationDataFn(_$[$0-4], _$[$0])(new yy.Assign($$[$0-4], $$[$0-1]));
break;
case 42: case 75: case 80: case 81: case 83: case 84: case 85: case 171: case 172:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Value($$[$0]));
break;
case 43:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.Assign(yy.addLocationDataFn(_$[$0-2])(new yy.Value($$[$0-2])), $$[$0], 'object', {
          operatorToken: yy.addLocationDataFn(_$[$0-1])(new yy.Literal($$[$0-1]))
        }));
break;
case 44:
this.$ = yy.addLocationDataFn(_$[$0-4], _$[$0])(new yy.Assign(yy.addLocationDataFn(_$[$0-4])(new yy.Value($$[$0-4])), $$[$0-1], 'object', {
          operatorToken: yy.addLocationDataFn(_$[$0-3])(new yy.Literal($$[$0-3]))
        }));
break;
case 45:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.Assign(yy.addLocationDataFn(_$[$0-2])(new yy.Value($$[$0-2])), $$[$0], null, {
          operatorToken: yy.addLocationDataFn(_$[$0-1])(new yy.Literal($$[$0-1]))
        }));
break;
case 46:
this.$ = yy.addLocationDataFn(_$[$0-4], _$[$0])(new yy.Assign(yy.addLocationDataFn(_$[$0-4])(new yy.Value($$[$0-4])), $$[$0-1], null, {
          operatorToken: yy.addLocationDataFn(_$[$0-3])(new yy.Literal($$[$0-3]))
        }));
break;
case 52:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Return($$[$0]));
break;
case 53:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Return);
break;
case 54:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Comment($$[$0]));
break;
case 55:
this.$ = yy.addLocationDataFn(_$[$0-4], _$[$0])(new yy.Code($$[$0-3], $$[$0], $$[$0-1]));
break;
case 56:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Code([], $$[$0], $$[$0-1]));
break;
case 57:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])('func');
break;
case 58:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])('boundfunc');
break;
case 61: case 98:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])([]);
break;
case 62: case 99: case 131: case 173:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])([$$[$0]]);
break;
case 63: case 100: case 132:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])($$[$0-2].concat($$[$0]));
break;
case 64: case 101: case 133:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])($$[$0-3].concat($$[$0]));
break;
case 65: case 102: case 135:
this.$ = yy.addLocationDataFn(_$[$0-5], _$[$0])($$[$0-5].concat($$[$0-2]));
break;
case 66:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Param($$[$0]));
break;
case 67:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Param($$[$0-1], null, true));
break;
case 68:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.Param($$[$0-2], $$[$0]));
break;
case 69: case 138:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Expansion);
break;
case 74:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Splat($$[$0-1]));
break;
case 76:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])($$[$0-1].add($$[$0]));
break;
case 77:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Value($$[$0-1], [].concat($$[$0])));
break;
case 87:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Access($$[$0]));
break;
case 88:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Access($$[$0], 'soak'));
break;
case 89:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])([yy.addLocationDataFn(_$[$0-1])(new yy.Access(new yy.Literal('prototype'))), yy.addLocationDataFn(_$[$0])(new yy.Access($$[$0]))]);
break;
case 90:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])([yy.addLocationDataFn(_$[$0-1])(new yy.Access(new yy.Literal('prototype'), 'soak')), yy.addLocationDataFn(_$[$0])(new yy.Access($$[$0]))]);
break;
case 91:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Access(new yy.Literal('prototype')));
break;
case 94:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(yy.extend($$[$0], {
          soak: true
        }));
break;
case 95:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Index($$[$0]));
break;
case 96:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Slice($$[$0]));
break;
case 97:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])(new yy.Obj($$[$0-2], $$[$0-3].generated));
break;
case 103:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Class);
break;
case 104:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Class(null, null, $$[$0]));
break;
case 105:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.Class(null, $$[$0]));
break;
case 106:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])(new yy.Class(null, $$[$0-1], $$[$0]));
break;
case 107:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Class($$[$0]));
break;
case 108:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.Class($$[$0-1], null, $$[$0]));
break;
case 109:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])(new yy.Class($$[$0-2], $$[$0]));
break;
case 110:
this.$ = yy.addLocationDataFn(_$[$0-4], _$[$0])(new yy.Class($$[$0-3], $$[$0-1], $$[$0]));
break;
case 111: case 112:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.Call($$[$0-2], $$[$0], $$[$0-1]));
break;
case 113:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Call('super', [new yy.Splat(new yy.Literal('arguments'))]));
break;
case 114:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Call('super', $$[$0]));
break;
case 115:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(false);
break;
case 116:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(true);
break;
case 117:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])([]);
break;
case 118: case 134:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])($$[$0-2]);
break;
case 119: case 120:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Value(new yy.Literal('this')));
break;
case 121:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Value(yy.addLocationDataFn(_$[$0-1])(new yy.Literal('this')), [yy.addLocationDataFn(_$[$0])(new yy.Access($$[$0]))], 'this'));
break;
case 122:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Arr([]));
break;
case 123:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])(new yy.Arr($$[$0-2]));
break;
case 124:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])('inclusive');
break;
case 125:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])('exclusive');
break;
case 126:
this.$ = yy.addLocationDataFn(_$[$0-4], _$[$0])(new yy.Range($$[$0-3], $$[$0-1], $$[$0-2]));
break;
case 127:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.Range($$[$0-2], $$[$0], $$[$0-1]));
break;
case 128:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Range($$[$0-1], null, $$[$0]));
break;
case 129:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Range(null, $$[$0], $$[$0-1]));
break;
case 130:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Range(null, null, $$[$0]));
break;
case 140:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])([].concat($$[$0-2], $$[$0]));
break;
case 141:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Try($$[$0]));
break;
case 142:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.Try($$[$0-1], $$[$0][0], $$[$0][1]));
break;
case 143:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])(new yy.Try($$[$0-2], null, null, $$[$0]));
break;
case 144:
this.$ = yy.addLocationDataFn(_$[$0-4], _$[$0])(new yy.Try($$[$0-3], $$[$0-2][0], $$[$0-2][1], $$[$0]));
break;
case 145:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])([$$[$0-1], $$[$0]]);
break;
case 146:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])([yy.addLocationDataFn(_$[$0-1])(new yy.Value($$[$0-1])), $$[$0]]);
break;
case 147:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])([null, $$[$0]]);
break;
case 148:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Throw($$[$0]));
break;
case 150:
this.$ = yy.addLocationDataFn(_$[$0-4], _$[$0])(new yy.Parens($$[$0-2]));
break;
case 151:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.While($$[$0]));
break;
case 152:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])(new yy.While($$[$0-2], {
          guard: $$[$0]
        }));
break;
case 153:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.While($$[$0], {
          invert: true
        }));
break;
case 154:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])(new yy.While($$[$0-2], {
          invert: true,
          guard: $$[$0]
        }));
break;
case 155:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])($$[$0-1].addBody($$[$0]));
break;
case 156: case 157:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])($$[$0].addBody(yy.addLocationDataFn(_$[$0-1])(yy.Block.wrap([$$[$0-1]]))));
break;
case 158:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])($$[$0]);
break;
case 159:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.While(yy.addLocationDataFn(_$[$0-1])(new yy.Literal('true'))).addBody($$[$0]));
break;
case 160:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.While(yy.addLocationDataFn(_$[$0-1])(new yy.Literal('true'))).addBody(yy.addLocationDataFn(_$[$0])(yy.Block.wrap([$$[$0]]))));
break;
case 161: case 162:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.For($$[$0-1], $$[$0]));
break;
case 163:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.For($$[$0], $$[$0-1]));
break;
case 164:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])({
          source: yy.addLocationDataFn(_$[$0])(new yy.Value($$[$0]))
        });
break;
case 165:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])({
          source: yy.addLocationDataFn(_$[$0-2])(new yy.Value($$[$0-2])),
          step: $$[$0]
        });
break;
case 166:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])((function () {
        $$[$0].own = $$[$0-1].own;
        $$[$0].name = $$[$0-1][0];
        $$[$0].index = $$[$0-1][1];
        return $$[$0];
      }()));
break;
case 167:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])($$[$0]);
break;
case 168:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])((function () {
        $$[$0].own = true;
        return $$[$0];
      }()));
break;
case 174:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])([$$[$0-2], $$[$0]]);
break;
case 175:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])({
          source: $$[$0]
        });
break;
case 176:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])({
          source: $$[$0],
          object: true
        });
break;
case 177:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])({
          source: $$[$0-2],
          guard: $$[$0]
        });
break;
case 178:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])({
          source: $$[$0-2],
          guard: $$[$0],
          object: true
        });
break;
case 179:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])({
          source: $$[$0-2],
          step: $$[$0]
        });
break;
case 180:
this.$ = yy.addLocationDataFn(_$[$0-5], _$[$0])({
          source: $$[$0-4],
          guard: $$[$0-2],
          step: $$[$0]
        });
break;
case 181:
this.$ = yy.addLocationDataFn(_$[$0-5], _$[$0])({
          source: $$[$0-4],
          step: $$[$0-2],
          guard: $$[$0]
        });
break;
case 182:
this.$ = yy.addLocationDataFn(_$[$0-4], _$[$0])(new yy.Switch($$[$0-3], $$[$0-1]));
break;
case 183:
this.$ = yy.addLocationDataFn(_$[$0-6], _$[$0])(new yy.Switch($$[$0-5], $$[$0-3], $$[$0-1]));
break;
case 184:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])(new yy.Switch(null, $$[$0-1]));
break;
case 185:
this.$ = yy.addLocationDataFn(_$[$0-5], _$[$0])(new yy.Switch(null, $$[$0-3], $$[$0-1]));
break;
case 187:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])($$[$0-1].concat($$[$0]));
break;
case 188:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])([[$$[$0-1], $$[$0]]]);
break;
case 189:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])([[$$[$0-2], $$[$0-1]]]);
break;
case 190:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.If($$[$0-1], $$[$0], {
          type: $$[$0-2]
        }));
break;
case 191:
this.$ = yy.addLocationDataFn(_$[$0-4], _$[$0])($$[$0-4].addElse(yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.If($$[$0-1], $$[$0], {
          type: $$[$0-2]
        }))));
break;
case 193:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])($$[$0-2].addElse($$[$0]));
break;
case 194: case 195:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.If($$[$0], yy.addLocationDataFn(_$[$0-2])(yy.Block.wrap([$$[$0-2]])), {
          type: $$[$0-1],
          statement: true
        }));
break;
case 196: case 197: case 200: case 201:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Op($$[$0-1], $$[$0]));
break;
case 198:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Op('-', $$[$0]));
break;
case 199:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Op('+', $$[$0]));
break;
case 202:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.Op($$[$0-2].concat($$[$0-1]), $$[$0]));
break;
case 203:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Op('--', $$[$0]));
break;
case 204:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Op('++', $$[$0]));
break;
case 205:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Op('--', $$[$0-1], null, true));
break;
case 206:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Op('++', $$[$0-1], null, true));
break;
case 207:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Existence($$[$0-1]));
break;
case 208:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.Op('+', $$[$0-2], $$[$0]));
break;
case 209:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.Op('-', $$[$0-2], $$[$0]));
break;
case 210: case 211: case 212: case 213: case 214:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.Op($$[$0-1], $$[$0-2], $$[$0]));
break;
case 215:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])((function () {
        if ($$[$0-1].charAt(0) === '!') {
          return new yy.Op($$[$0-1].slice(1), $$[$0-2], $$[$0]).invert();
        } else {
          return new yy.Op($$[$0-1], $$[$0-2], $$[$0]);
        }
      }()));
break;
case 216:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.Assign($$[$0-2], $$[$0], $$[$0-1]));
break;
case 217:
this.$ = yy.addLocationDataFn(_$[$0-4], _$[$0])(new yy.Assign($$[$0-4], $$[$0-1], $$[$0-3]));
break;
case 218:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])(new yy.Assign($$[$0-3], $$[$0], $$[$0-2]));
break;
case 219:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.Extends($$[$0-2], $$[$0]));
break;
}
},
table: [{1:[2,1],3:1,4:2,5:3,7:4,8:5,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{1:[3]},{1:[2,2],6:$VD},o($VE,[2,3]),o($VE,[2,6],{119:69,110:89,116:90,111:$Vq,113:$Vr,117:$Vt,133:$VF,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),o($VE,[2,7],{119:69,110:92,116:93,111:$Vq,113:$Vr,117:$Vt,133:$VP}),o($VQ,[2,11],{88:94,69:95,77:101,73:$VR,74:$VS,75:$VT,76:$VU,78:$VV,81:$VW,91:$VX,92:$VY}),o($VQ,[2,12],{77:101,88:104,69:105,73:$VR,74:$VS,75:$VT,76:$VU,78:$VV,81:$VW,91:$VX,92:$VY}),o($VQ,[2,13]),o($VQ,[2,14]),o($VQ,[2,15]),o($VQ,[2,16]),o($VQ,[2,17]),o($VQ,[2,18]),o($VQ,[2,19]),o($VQ,[2,20]),o($VQ,[2,21]),o($VQ,[2,22]),o($VQ,[2,8]),o($VQ,[2,9]),o($VQ,[2,10]),o($VZ,$V_,{46:[1,106]}),o($VZ,[2,83]),o($VZ,[2,84]),o($VZ,[2,85]),o($VZ,[2,86]),o([1,6,25,26,34,38,56,61,64,73,74,75,76,78,80,81,85,91,93,98,100,109,111,112,113,117,118,133,136,137,142,143,144,145,146,147,148],[2,113],{89:107,92:$V$}),o([6,25,56,61],$V01,{55:109,62:110,63:111,27:113,51:114,65:115,66:116,28:$V1,64:$V11,83:$Vh,96:$V21,97:$V31}),{24:119,25:$V41},{7:121,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{7:123,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{7:124,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{7:125,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{7:127,8:126,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,139:[1,128],140:$VB,141:$VC},{12:130,13:131,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:132,51:63,65:47,66:48,68:129,70:23,71:24,72:25,83:$Vh,90:$Vj,95:$Vk,96:$Vl,97:$Vm,108:$Vp},{12:130,13:131,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:132,51:63,65:47,66:48,68:133,70:23,71:24,72:25,83:$Vh,90:$Vj,95:$Vk,96:$Vl,97:$Vm,108:$Vp},o($V51,$V61,{87:[1,137],140:[1,134],141:[1,135],149:[1,136]}),o($VQ,[2,192],{128:[1,138]}),{24:139,25:$V41},{24:140,25:$V41},o($VQ,[2,158]),{24:141,25:$V41},{7:142,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,25:[1,143],27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},o($V71,[2,103],{39:22,70:23,71:24,72:25,65:47,66:48,29:49,35:51,27:62,51:63,31:72,12:130,13:131,45:132,24:144,68:146,25:$V41,28:$V1,30:$V2,32:$V3,33:$V4,36:$V5,37:$V6,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,83:$Vh,87:[1,145],90:$Vj,95:$Vk,96:$Vl,97:$Vm,108:$Vp}),{7:147,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},o([1,6,25,26,34,56,61,64,80,85,93,98,100,109,111,112,113,117,118,133,142,143,144,145,146,147,148],[2,53],{12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,9:18,10:19,45:21,39:22,70:23,71:24,72:25,57:28,68:36,131:37,110:39,114:40,116:41,65:47,66:48,29:49,35:51,27:62,51:63,119:69,31:72,8:122,7:148,11:$V0,28:$V1,30:$V2,32:$V3,33:$V4,36:$V5,37:$V6,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,52:$Vc,53:$Vd,54:$Ve,58:$Vf,59:$Vg,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,115:$Vs,126:$Vu,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC}),o($VQ,[2,54]),o($V51,[2,80]),o($V51,[2,81]),o($VZ,[2,32]),o($VZ,[2,33]),o($VZ,[2,34]),o($VZ,[2,35]),o($VZ,[2,36]),o($VZ,[2,37]),o($VZ,[2,38]),{4:149,5:3,7:4,8:5,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,25:[1,150],27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{7:151,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,25:$V81,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,64:$V91,65:47,66:48,67:156,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,94:153,95:$Vk,96:$Vl,97:$Vm,98:$Va1,101:154,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},o($VZ,[2,119]),o($VZ,[2,120],{27:158,28:$V1}),{25:[2,57]},{25:[2,58]},o($Vb1,[2,75]),o($Vb1,[2,78]),{7:159,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{7:160,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{7:161,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{7:163,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:162,25:$V41,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{27:168,28:$V1,51:169,65:170,66:171,71:164,83:$Vh,96:$V21,97:$Vm,121:165,122:[1,166],123:167},{120:172,124:[1,173],125:[1,174]},o([6,25,61,85],$Vc1,{31:72,84:175,47:176,48:177,50:178,10:179,29:180,27:181,51:182,28:$V1,30:$V2,32:$V3,33:$V4,53:$Vd,96:$V21}),o($Vd1,[2,26]),o($Vd1,[2,27]),o($VZ,[2,30]),{12:130,13:183,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:132,51:63,65:47,66:48,68:184,70:23,71:24,72:25,83:$Vh,90:$Vj,95:$Vk,96:$Vl,97:$Vm,108:$Vp},o($Ve1,[2,25]),o($Vd1,[2,28]),{4:185,5:3,7:4,8:5,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},o($VE,[2,5],{7:4,8:5,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,9:18,10:19,45:21,39:22,70:23,71:24,72:25,57:28,68:36,131:37,110:39,114:40,116:41,65:47,66:48,29:49,35:51,27:62,51:63,119:69,31:72,5:186,11:$V0,28:$V1,30:$V2,32:$V3,33:$V4,36:$V5,37:$V6,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,52:$Vc,53:$Vd,54:$Ve,58:$Vf,59:$Vg,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,111:$Vq,113:$Vr,115:$Vs,117:$Vt,126:$Vu,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC}),o($VQ,[2,207]),{7:187,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{7:188,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{7:189,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{7:190,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{7:191,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{7:192,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{7:193,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{7:194,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{7:195,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},o($VQ,[2,157]),o($VQ,[2,162]),{7:196,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},o($VQ,[2,156]),o($VQ,[2,161]),{89:197,92:$V$},o($Vb1,[2,76]),{92:[2,116]},{27:198,28:$V1},{27:199,28:$V1},o($Vb1,[2,91],{27:200,28:$V1}),{27:201,28:$V1},o($Vb1,[2,92]),{7:203,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,64:$Vf1,65:47,66:48,68:36,70:23,71:24,72:25,79:202,82:204,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,99:205,100:$Vg1,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{77:208,78:$VV,81:$VW},{89:209,92:$V$},o($Vb1,[2,77]),{6:[1,211],7:210,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,25:[1,212],27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},o($Vh1,[2,114]),{7:215,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,25:$V81,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,64:$V91,65:47,66:48,67:156,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,93:[1,213],94:214,95:$Vk,96:$Vl,97:$Vm,101:154,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},o([6,25],$Vi1,{60:218,56:[1,216],61:$Vj1}),o($Vk1,[2,62]),o($Vk1,[2,66],{46:[1,220],64:[1,219]}),o($Vk1,[2,69]),o($Vl1,[2,70]),o($Vl1,[2,71]),o($Vl1,[2,72]),o($Vl1,[2,73]),{27:158,28:$V1},{7:215,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,25:$V81,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,64:$V91,65:47,66:48,67:156,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,94:153,95:$Vk,96:$Vl,97:$Vm,98:$Va1,101:154,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},o($VQ,[2,56]),{4:222,5:3,7:4,8:5,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,26:[1,221],27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},o([1,6,25,26,34,56,61,64,80,85,93,98,100,109,111,112,113,117,118,133,136,137,143,144,145,146,147,148],[2,196],{119:69,110:89,116:90,142:$VI}),{110:92,111:$Vq,113:$Vr,116:93,117:$Vt,119:69,133:$VP},o($Vm1,[2,197],{119:69,110:89,116:90,142:$VI,144:$VK}),o($Vm1,[2,198],{119:69,110:89,116:90,142:$VI,144:$VK}),o($Vm1,[2,199],{119:69,110:89,116:90,142:$VI,144:$VK}),o($VQ,[2,200],{119:69,110:92,116:93}),o($Vn1,[2,201],{119:69,110:89,116:90,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),{7:223,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},o($VQ,[2,203],{73:$V61,74:$V61,75:$V61,76:$V61,78:$V61,81:$V61,91:$V61,92:$V61}),{69:95,73:$VR,74:$VS,75:$VT,76:$VU,77:101,78:$VV,81:$VW,88:94,91:$VX,92:$VY},{69:105,73:$VR,74:$VS,75:$VT,76:$VU,77:101,78:$VV,81:$VW,88:104,91:$VX,92:$VY},o($Vo1,$V_),o($VQ,[2,204],{73:$V61,74:$V61,75:$V61,76:$V61,78:$V61,81:$V61,91:$V61,92:$V61}),o($VQ,[2,205]),o($VQ,[2,206]),{6:[1,226],7:224,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,25:[1,225],27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{7:227,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{24:228,25:$V41,132:[1,229]},o($VQ,[2,141],{104:230,105:[1,231],106:[1,232]}),o($VQ,[2,155]),o($VQ,[2,163]),{25:[1,233],110:89,111:$Vq,113:$Vr,116:90,117:$Vt,119:69,133:$VF,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO},{127:234,129:235,130:$Vp1},o($VQ,[2,104]),{7:237,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},o($V71,[2,107],{24:238,25:$V41,73:$V61,74:$V61,75:$V61,76:$V61,78:$V61,81:$V61,91:$V61,92:$V61,87:[1,239]}),o($Vn1,[2,148],{119:69,110:89,116:90,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),o($Vn1,[2,52],{119:69,110:89,116:90,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),{6:$VD,109:[1,240]},{4:241,5:3,7:4,8:5,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},o([6,25,61,98],$Vq1,{119:69,110:89,116:90,99:242,64:[1,243],100:$Vg1,111:$Vq,113:$Vr,117:$Vt,133:$VF,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),o($Vr1,[2,122]),o([6,25,98],$Vi1,{60:244,61:$Vs1}),o($Vt1,[2,131]),{7:215,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,25:$V81,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,64:$V91,65:47,66:48,67:156,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,94:246,95:$Vk,96:$Vl,97:$Vm,101:154,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},o($Vt1,[2,137]),o($Vt1,[2,138]),o($Ve1,[2,121]),{24:247,25:$V41,110:89,111:$Vq,113:$Vr,116:90,117:$Vt,119:69,133:$VF,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO},o($Vu1,[2,151],{119:69,110:89,116:90,111:$Vq,112:[1,248],113:$Vr,117:$Vt,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),o($Vu1,[2,153],{119:69,110:89,116:90,111:$Vq,112:[1,249],113:$Vr,117:$Vt,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),o($VQ,[2,159]),o($Vv1,[2,160],{119:69,110:89,116:90,111:$Vq,113:$Vr,117:$Vt,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),o([1,6,25,26,34,56,61,64,80,85,93,98,100,109,111,112,113,117,133,136,137,142,143,144,145,146,147,148],[2,164],{118:[1,250]}),o($Vw1,[2,167]),{27:168,28:$V1,51:169,65:170,66:171,83:$Vh,96:$V21,97:$V31,121:251,123:167},o($Vw1,[2,173],{61:[1,252]}),o($Vx1,[2,169]),o($Vx1,[2,170]),o($Vx1,[2,171]),o($Vx1,[2,172]),o($VQ,[2,166]),{7:253,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{7:254,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},o([6,25,85],$Vi1,{60:255,61:$Vy1}),o($Vz1,[2,99]),o($Vz1,[2,42],{49:[1,257]}),o($VA1,[2,50],{46:[1,258]}),o($Vz1,[2,47]),o($VA1,[2,51]),o($VB1,[2,48]),o($VB1,[2,49]),{38:[1,259],69:105,73:$VR,74:$VS,75:$VT,76:$VU,77:101,78:$VV,81:$VW,88:104,91:$VX,92:$VY},o($Vo1,$V61),{6:$VD,34:[1,260]},o($VE,[2,4]),o($VC1,[2,208],{119:69,110:89,116:90,142:$VI,143:$VJ,144:$VK}),o($VC1,[2,209],{119:69,110:89,116:90,142:$VI,143:$VJ,144:$VK}),o($Vm1,[2,210],{119:69,110:89,116:90,142:$VI,144:$VK}),o($Vm1,[2,211],{119:69,110:89,116:90,142:$VI,144:$VK}),o([1,6,25,26,34,56,61,64,80,85,93,98,100,109,111,112,113,117,118,133,145,146,147,148],[2,212],{119:69,110:89,116:90,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK}),o([1,6,25,26,34,56,61,64,80,85,93,98,100,109,111,112,113,117,118,133,146,147],[2,213],{119:69,110:89,116:90,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,148:$VO}),o([1,6,25,26,34,56,61,64,80,85,93,98,100,109,111,112,113,117,118,133,147],[2,214],{119:69,110:89,116:90,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,148:$VO}),o([1,6,25,26,34,56,61,64,80,85,93,98,100,109,111,112,113,117,118,133,146,147,148],[2,215],{119:69,110:89,116:90,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL}),o($Vv1,[2,195],{119:69,110:89,116:90,111:$Vq,113:$Vr,117:$Vt,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),o($Vv1,[2,194],{119:69,110:89,116:90,111:$Vq,113:$Vr,117:$Vt,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),o($Vh1,[2,111]),o($Vb1,[2,87]),o($Vb1,[2,88]),o($Vb1,[2,89]),o($Vb1,[2,90]),{80:[1,261]},{64:$Vf1,80:[2,95],99:262,100:$Vg1,110:89,111:$Vq,113:$Vr,116:90,117:$Vt,119:69,133:$VF,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO},{80:[2,96]},{7:263,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,80:[2,130],83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},o($VD1,[2,124]),o($VD1,$VE1),o($Vb1,[2,94]),o($Vh1,[2,112]),o($Vn1,[2,39],{119:69,110:89,116:90,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),{7:264,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{7:265,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},o($Vh1,[2,117]),o([6,25,93],$Vi1,{60:266,61:$Vs1}),o($Vt1,$Vq1,{119:69,110:89,116:90,64:[1,267],111:$Vq,113:$Vr,117:$Vt,133:$VF,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),{57:268,58:$Vf,59:$Vg},o($VF1,$VG1,{63:111,27:113,51:114,65:115,66:116,62:269,28:$V1,64:$V11,83:$Vh,96:$V21,97:$V31}),{6:$VH1,25:$VI1},o($Vk1,[2,67]),{7:272,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},o($VJ1,[2,23]),{6:$VD,26:[1,273]},o($Vn1,[2,202],{119:69,110:89,116:90,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),o($Vn1,[2,216],{119:69,110:89,116:90,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),{7:274,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{7:275,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},o($Vn1,[2,219],{119:69,110:89,116:90,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),o($VQ,[2,193]),{7:276,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},o($VQ,[2,142],{105:[1,277]}),{24:278,25:$V41},{24:281,25:$V41,27:279,28:$V1,66:280,83:$Vh},{127:282,129:235,130:$Vp1},{26:[1,283],128:[1,284],129:285,130:$Vp1},o($VK1,[2,186]),{7:287,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,102:286,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},o($VL1,[2,105],{119:69,110:89,116:90,24:288,25:$V41,111:$Vq,113:$Vr,117:$Vt,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),o($VQ,[2,108]),{7:289,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},o($VZ,[2,149]),{6:$VD,26:[1,290]},{7:291,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},o([11,28,30,32,33,36,37,40,41,42,43,44,52,53,54,58,59,83,86,90,95,96,97,103,107,108,111,113,115,117,126,132,134,135,136,137,138,140,141],$VE1,{6:$VM1,25:$VM1,61:$VM1,98:$VM1}),{6:$VN1,25:$VO1,98:[1,292]},o([6,25,26,93,98],$VG1,{12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,9:18,10:19,45:21,39:22,70:23,71:24,72:25,57:28,68:36,131:37,110:39,114:40,116:41,65:47,66:48,29:49,35:51,27:62,51:63,119:69,31:72,8:122,67:156,7:215,101:295,11:$V0,28:$V1,30:$V2,32:$V3,33:$V4,36:$V5,37:$V6,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,52:$Vc,53:$Vd,54:$Ve,58:$Vf,59:$Vg,64:$V91,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,111:$Vq,113:$Vr,115:$Vs,117:$Vt,126:$Vu,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC}),o($VF1,$Vi1,{60:296,61:$Vs1}),o($VP1,[2,190]),{7:297,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{7:298,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{7:299,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},o($Vw1,[2,168]),{27:168,28:$V1,51:169,65:170,66:171,83:$Vh,96:$V21,97:$V31,123:300},o([1,6,25,26,34,56,61,64,80,85,93,98,100,109,111,113,117,133],[2,175],{119:69,110:89,116:90,112:[1,301],118:[1,302],136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),o($VQ1,[2,176],{119:69,110:89,116:90,112:[1,303],136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),{6:$VR1,25:$VS1,85:[1,304]},o([6,25,26,85],$VG1,{31:72,48:177,50:178,10:179,29:180,27:181,51:182,47:307,28:$V1,30:$V2,32:$V3,33:$V4,53:$Vd,96:$V21}),{7:308,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,25:[1,309],27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{7:310,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,25:[1,311],27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},o($VZ,[2,31]),o($Vd1,[2,29]),o($Vb1,[2,93]),{7:312,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,80:[2,128],83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{80:[2,129],110:89,111:$Vq,113:$Vr,116:90,117:$Vt,119:69,133:$VF,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO},o($Vn1,[2,40],{119:69,110:89,116:90,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),{26:[1,313],110:89,111:$Vq,113:$Vr,116:90,117:$Vt,119:69,133:$VF,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO},{6:$VN1,25:$VO1,93:[1,314]},o($Vt1,$VM1),{24:315,25:$V41},o($Vk1,[2,63]),{27:113,28:$V1,51:114,62:316,63:111,64:$V11,65:115,66:116,83:$Vh,96:$V21,97:$V31},o($VT1,$V01,{62:110,63:111,27:113,51:114,65:115,66:116,55:317,28:$V1,64:$V11,83:$Vh,96:$V21,97:$V31}),o($Vk1,[2,68],{119:69,110:89,116:90,111:$Vq,113:$Vr,117:$Vt,133:$VF,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),o($VJ1,[2,24]),{26:[1,318],110:89,111:$Vq,113:$Vr,116:90,117:$Vt,119:69,133:$VF,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO},o($Vn1,[2,218],{119:69,110:89,116:90,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),{24:319,25:$V41,110:89,111:$Vq,113:$Vr,116:90,117:$Vt,119:69,133:$VF,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO},{24:320,25:$V41},o($VQ,[2,143]),{24:321,25:$V41},{24:322,25:$V41},o($VU1,[2,147]),{26:[1,323],128:[1,324],129:285,130:$Vp1},o($VQ,[2,184]),{24:325,25:$V41},o($VK1,[2,187]),{24:326,25:$V41,61:[1,327]},o($VV1,[2,139],{119:69,110:89,116:90,111:$Vq,113:$Vr,117:$Vt,133:$VF,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),o($VQ,[2,106]),o($VL1,[2,109],{119:69,110:89,116:90,24:328,25:$V41,111:$Vq,113:$Vr,117:$Vt,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),{109:[1,329]},{98:[1,330],110:89,111:$Vq,113:$Vr,116:90,117:$Vt,119:69,133:$VF,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO},o($Vr1,[2,123]),{7:215,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,64:$V91,65:47,66:48,67:156,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,101:331,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{7:215,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,25:$V81,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,64:$V91,65:47,66:48,67:156,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,94:332,95:$Vk,96:$Vl,97:$Vm,101:154,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},o($Vt1,[2,132]),{6:$VN1,25:$VO1,26:[1,333]},o($Vv1,[2,152],{119:69,110:89,116:90,111:$Vq,113:$Vr,117:$Vt,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),o($Vv1,[2,154],{119:69,110:89,116:90,111:$Vq,113:$Vr,117:$Vt,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),o($Vv1,[2,165],{119:69,110:89,116:90,111:$Vq,113:$Vr,117:$Vt,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),o($Vw1,[2,174]),{7:334,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{7:335,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{7:336,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},o($Vr1,[2,97]),{10:179,27:181,28:$V1,29:180,30:$V2,31:72,32:$V3,33:$V4,47:337,48:177,50:178,51:182,53:$Vd,96:$V21},o($VT1,$Vc1,{31:72,47:176,48:177,50:178,10:179,29:180,27:181,51:182,84:338,28:$V1,30:$V2,32:$V3,33:$V4,53:$Vd,96:$V21}),o($Vz1,[2,100]),o($Vz1,[2,43],{119:69,110:89,116:90,111:$Vq,113:$Vr,117:$Vt,133:$VF,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),{7:339,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},o($Vz1,[2,45],{119:69,110:89,116:90,111:$Vq,113:$Vr,117:$Vt,133:$VF,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),{7:340,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{80:[2,127],110:89,111:$Vq,113:$Vr,116:90,117:$Vt,119:69,133:$VF,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO},o($VQ,[2,41]),o($Vh1,[2,118]),o($VQ,[2,55]),o($Vk1,[2,64]),o($VF1,$Vi1,{60:341,61:$Vj1}),o($VQ,[2,217]),o($VP1,[2,191]),o($VQ,[2,144]),o($VU1,[2,145]),o($VU1,[2,146]),o($VQ,[2,182]),{24:342,25:$V41},{26:[1,343]},o($VK1,[2,188],{6:[1,344]}),{7:345,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},o($VQ,[2,110]),o($VZ,[2,150]),o($VZ,[2,126]),o($Vt1,[2,133]),o($VF1,$Vi1,{60:346,61:$Vs1}),o($Vt1,[2,134]),o([1,6,25,26,34,56,61,64,80,85,93,98,100,109,111,112,113,117,133],[2,177],{119:69,110:89,116:90,118:[1,347],136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),o($VQ1,[2,179],{119:69,110:89,116:90,112:[1,348],136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),o($Vn1,[2,178],{119:69,110:89,116:90,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),o($Vz1,[2,101]),o($VF1,$Vi1,{60:349,61:$Vy1}),{26:[1,350],110:89,111:$Vq,113:$Vr,116:90,117:$Vt,119:69,133:$VF,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO},{26:[1,351],110:89,111:$Vq,113:$Vr,116:90,117:$Vt,119:69,133:$VF,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO},{6:$VH1,25:$VI1,26:[1,352]},{26:[1,353]},o($VQ,[2,185]),o($VK1,[2,189]),o($VV1,[2,140],{119:69,110:89,116:90,111:$Vq,113:$Vr,117:$Vt,133:$VF,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),{6:$VN1,25:$VO1,26:[1,354]},{7:355,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{7:356,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,51:63,52:$Vc,53:$Vd,54:$Ve,57:28,58:$Vf,59:$Vg,65:47,66:48,68:36,70:23,71:24,72:25,83:$Vh,86:$Vi,90:$Vj,95:$Vk,96:$Vl,97:$Vm,103:$Vn,107:$Vo,108:$Vp,110:39,111:$Vq,113:$Vr,114:40,115:$Vs,116:41,117:$Vt,119:69,126:$Vu,131:37,132:$Vv,134:$Vw,135:$Vx,136:$Vy,137:$Vz,138:$VA,140:$VB,141:$VC},{6:$VR1,25:$VS1,26:[1,357]},o($Vz1,[2,44]),o($Vz1,[2,46]),o($Vk1,[2,65]),o($VQ,[2,183]),o($Vt1,[2,135]),o($Vn1,[2,180],{119:69,110:89,116:90,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),o($Vn1,[2,181],{119:69,110:89,116:90,136:$VG,137:$VH,142:$VI,143:$VJ,144:$VK,145:$VL,146:$VM,147:$VN,148:$VO}),o($Vz1,[2,102])],
defaultActions: {60:[2,57],61:[2,58],96:[2,116],204:[2,96]},
parseError: function parseError(str, hash) {
    if (hash.recoverable) {
        this.trace(str);
    } else {
        throw new Error(str);
    }
},
parse: function parse(input) {
    var self = this, stack = [0], tstack = [], vstack = [null], lstack = [], table = this.table, yytext = '', yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1;
    var args = lstack.slice.call(arguments, 1);
    var lexer = Object.create(this.lexer);
    var sharedState = { yy: {} };
    for (var k in this.yy) {
        if (Object.prototype.hasOwnProperty.call(this.yy, k)) {
            sharedState.yy[k] = this.yy[k];
        }
    }
    lexer.setInput(input, sharedState.yy);
    sharedState.yy.lexer = lexer;
    sharedState.yy.parser = this;
    if (typeof lexer.yylloc == 'undefined') {
        lexer.yylloc = {};
    }
    var yyloc = lexer.yylloc;
    lstack.push(yyloc);
    var ranges = lexer.options && lexer.options.ranges;
    if (typeof sharedState.yy.parseError === 'function') {
        this.parseError = sharedState.yy.parseError;
    } else {
        this.parseError = Object.getPrototypeOf(this).parseError;
    }
    function popStack(n) {
        stack.length = stack.length - 2 * n;
        vstack.length = vstack.length - n;
        lstack.length = lstack.length - n;
    }
    _token_stack:
        function lex() {
            var token;
            token = lexer.lex() || EOF;
            if (typeof token !== 'number') {
                token = self.symbols_[token] || token;
            }
            return token;
        }
    var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected;
    while (true) {
        state = stack[stack.length - 1];
        if (this.defaultActions[state]) {
            action = this.defaultActions[state];
        } else {
            if (symbol === null || typeof symbol == 'undefined') {
                symbol = lex();
            }
            action = table[state] && table[state][symbol];
        }
                    if (typeof action === 'undefined' || !action.length || !action[0]) {
                var errStr = '';
                expected = [];
                for (p in table[state]) {
                    if (this.terminals_[p] && p > TERROR) {
                        expected.push('\'' + this.terminals_[p] + '\'');
                    }
                }
                if (lexer.showPosition) {
                    errStr = 'Parse error on line ' + (yylineno + 1) + ':\n' + lexer.showPosition() + '\nExpecting ' + expected.join(', ') + ', got \'' + (this.terminals_[symbol] || symbol) + '\'';
                } else {
                    errStr = 'Parse error on line ' + (yylineno + 1) + ': Unexpected ' + (symbol == EOF ? 'end of input' : '\'' + (this.terminals_[symbol] || symbol) + '\'');
                }
                this.parseError(errStr, {
                    text: lexer.match,
                    token: this.terminals_[symbol] || symbol,
                    line: lexer.yylineno,
                    loc: yyloc,
                    expected: expected
                });
            }
        if (action[0] instanceof Array && action.length > 1) {
            throw new Error('Parse Error: multiple actions possible at state: ' + state + ', token: ' + symbol);
        }
        switch (action[0]) {
        case 1:
            stack.push(symbol);
            vstack.push(lexer.yytext);
            lstack.push(lexer.yylloc);
            stack.push(action[1]);
            symbol = null;
            if (!preErrorSymbol) {
                yyleng = lexer.yyleng;
                yytext = lexer.yytext;
                yylineno = lexer.yylineno;
                yyloc = lexer.yylloc;
                if (recovering > 0) {
                    recovering--;
                }
            } else {
                symbol = preErrorSymbol;
                preErrorSymbol = null;
            }
            break;
        case 2:
            len = this.productions_[action[1]][1];
            yyval.$ = vstack[vstack.length - len];
            yyval._$ = {
                first_line: lstack[lstack.length - (len || 1)].first_line,
                last_line: lstack[lstack.length - 1].last_line,
                first_column: lstack[lstack.length - (len || 1)].first_column,
                last_column: lstack[lstack.length - 1].last_column
            };
            if (ranges) {
                yyval._$.range = [
                    lstack[lstack.length - (len || 1)].range[0],
                    lstack[lstack.length - 1].range[1]
                ];
            }
            r = this.performAction.apply(yyval, [
                yytext,
                yyleng,
                yylineno,
                sharedState.yy,
                action[1],
                vstack,
                lstack
            ].concat(args));
            if (typeof r !== 'undefined') {
                return r;
            }
            if (len) {
                stack = stack.slice(0, -1 * len * 2);
                vstack = vstack.slice(0, -1 * len);
                lstack = lstack.slice(0, -1 * len);
            }
            stack.push(this.productions_[action[1]][0]);
            vstack.push(yyval.$);
            lstack.push(yyval._$);
            newState = table[stack[stack.length - 2]][stack[stack.length - 1]];
            stack.push(newState);
            break;
        case 3:
            return true;
        }
    }
    return true;
}};

function Parser () {
  this.yy = {};
}
Parser.prototype = parser;parser.Parser = Parser;
return new Parser;
})();


if (typeof require !== 'undefined' && typeof exports !== 'undefined') {
exports.parser = parser;
exports.Parser = parser.Parser;
exports.parse = function () { return parser.parse.apply(parser, arguments); };
exports.main = function commonjsMain(args) {
    if (!args[1]) {
        console.log('Usage: '+args[0]+' FILE');
        process.exit(1);
    }
    var source = require('fs').readFileSync(require('path').normalize(args[1]), "utf8");
    return exports.parser.parse(source);
};
if (typeof module !== 'undefined' && require.main === module) {
  exports.main(process.argv.slice(1));
}
}
}).call(this,require('_process'))

},{"_process":"browserify/node_modules/process/browser","fs":"browserify/lib/_empty","path":"browserify/node_modules/path-browserify/index"}],"coffee-script/lib/coffee-script/register":[function(require,module,exports){
// Generated by CoffeeScript 1.10.0
(function() {
  var CoffeeScript, Module, binary, child_process, ext, findExtension, fork, helpers, i, len, loadFile, path, ref;

  CoffeeScript = require('./coffee-script');

  child_process = require('child_process');

  helpers = require('./helpers');

  path = require('path');

  loadFile = function(module, filename) {
    var answer;
    answer = CoffeeScript._compileFile(filename, false);
    return module._compile(answer, filename);
  };

  if (require.extensions) {
    ref = CoffeeScript.FILE_EXTENSIONS;
    for (i = 0, len = ref.length; i < len; i++) {
      ext = ref[i];
      require.extensions[ext] = loadFile;
    }
    Module = require('module');
    findExtension = function(filename) {
      var curExtension, extensions;
      extensions = path.basename(filename).split('.');
      if (extensions[0] === '') {
        extensions.shift();
      }
      while (extensions.shift()) {
        curExtension = '.' + extensions.join('.');
        if (Module._extensions[curExtension]) {
          return curExtension;
        }
      }
      return '.js';
    };
    Module.prototype.load = function(filename) {
      var extension;
      this.filename = filename;
      this.paths = Module._nodeModulePaths(path.dirname(filename));
      extension = findExtension(filename);
      Module._extensions[extension](this, filename);
      return this.loaded = true;
    };
  }

  if (child_process) {
    fork = child_process.fork;
    binary = require.resolve('../../bin/coffee');
    child_process.fork = function(path, args, options) {
      if (helpers.isCoffee(path)) {
        if (!Array.isArray(args)) {
          options = args || {};
          args = [];
        }
        args = [path].concat(args);
        path = binary;
      }
      return fork(path, args, options);
    };
  }

}).call(this);

},{"./coffee-script":"coffee-script","./helpers":"coffee-script/lib/coffee-script/helpers","child_process":"browserify/lib/_empty","module":"browserify/lib/_empty","path":"browserify/node_modules/path-browserify/index"}],"coffee-script/lib/coffee-script/rewriter":[function(require,module,exports){
// Generated by CoffeeScript 1.10.0
(function() {
  var BALANCED_PAIRS, CALL_CLOSERS, EXPRESSION_CLOSE, EXPRESSION_END, EXPRESSION_START, IMPLICIT_CALL, IMPLICIT_END, IMPLICIT_FUNC, IMPLICIT_UNSPACED_CALL, INVERSES, LINEBREAKS, SINGLE_CLOSERS, SINGLE_LINERS, generate, k, left, len, ref, rite,
    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; },
    slice = [].slice;

  generate = function(tag, value, origin) {
    var tok;
    tok = [tag, value];
    tok.generated = true;
    if (origin) {
      tok.origin = origin;
    }
    return tok;
  };

  exports.Rewriter = (function() {
    function Rewriter() {}

    Rewriter.prototype.rewrite = function(tokens1) {
      this.tokens = tokens1;
      this.removeLeadingNewlines();
      this.closeOpenCalls();
      this.closeOpenIndexes();
      this.normalizeLines();
      this.tagPostfixConditionals();
      this.addImplicitBracesAndParens();
      this.addLocationDataToGeneratedTokens();
      return this.tokens;
    };

    Rewriter.prototype.scanTokens = function(block) {
      var i, token, tokens;
      tokens = this.tokens;
      i = 0;
      while (token = tokens[i]) {
        i += block.call(this, token, i, tokens);
      }
      return true;
    };

    Rewriter.prototype.detectEnd = function(i, condition, action) {
      var levels, ref, ref1, token, tokens;
      tokens = this.tokens;
      levels = 0;
      while (token = tokens[i]) {
        if (levels === 0 && condition.call(this, token, i)) {
          return action.call(this, token, i);
        }
        if (!token || levels < 0) {
          return action.call(this, token, i - 1);
        }
        if (ref = token[0], indexOf.call(EXPRESSION_START, ref) >= 0) {
          levels += 1;
        } else if (ref1 = token[0], indexOf.call(EXPRESSION_END, ref1) >= 0) {
          levels -= 1;
        }
        i += 1;
      }
      return i - 1;
    };

    Rewriter.prototype.removeLeadingNewlines = function() {
      var i, k, len, ref, tag;
      ref = this.tokens;
      for (i = k = 0, len = ref.length; k < len; i = ++k) {
        tag = ref[i][0];
        if (tag !== 'TERMINATOR') {
          break;
        }
      }
      if (i) {
        return this.tokens.splice(0, i);
      }
    };

    Rewriter.prototype.closeOpenCalls = function() {
      var action, condition;
      condition = function(token, i) {
        var ref;
        return ((ref = token[0]) === ')' || ref === 'CALL_END') || token[0] === 'OUTDENT' && this.tag(i - 1) === ')';
      };
      action = function(token, i) {
        return this.tokens[token[0] === 'OUTDENT' ? i - 1 : i][0] = 'CALL_END';
      };
      return this.scanTokens(function(token, i) {
        if (token[0] === 'CALL_START') {
          this.detectEnd(i + 1, condition, action);
        }
        return 1;
      });
    };

    Rewriter.prototype.closeOpenIndexes = function() {
      var action, condition;
      condition = function(token, i) {
        var ref;
        return (ref = token[0]) === ']' || ref === 'INDEX_END';
      };
      action = function(token, i) {
        return token[0] = 'INDEX_END';
      };
      return this.scanTokens(function(token, i) {
        if (token[0] === 'INDEX_START') {
          this.detectEnd(i + 1, condition, action);
        }
        return 1;
      });
    };

    Rewriter.prototype.indexOfTag = function() {
      var fuzz, i, j, k, pattern, ref, ref1;
      i = arguments[0], pattern = 2 <= arguments.length ? slice.call(arguments, 1) : [];
      fuzz = 0;
      for (j = k = 0, ref = pattern.length; 0 <= ref ? k < ref : k > ref; j = 0 <= ref ? ++k : --k) {
        while (this.tag(i + j + fuzz) === 'HERECOMMENT') {
          fuzz += 2;
        }
        if (pattern[j] == null) {
          continue;
        }
        if (typeof pattern[j] === 'string') {
          pattern[j] = [pattern[j]];
        }
        if (ref1 = this.tag(i + j + fuzz), indexOf.call(pattern[j], ref1) < 0) {
          return -1;
        }
      }
      return i + j + fuzz - 1;
    };

    Rewriter.prototype.looksObjectish = function(j) {
      var end, index;
      if (this.indexOfTag(j, '@', null, ':') > -1 || this.indexOfTag(j, null, ':') > -1) {
        return true;
      }
      index = this.indexOfTag(j, EXPRESSION_START);
      if (index > -1) {
        end = null;
        this.detectEnd(index + 1, (function(token) {
          var ref;
          return ref = token[0], indexOf.call(EXPRESSION_END, ref) >= 0;
        }), (function(token, i) {
          return end = i;
        }));
        if (this.tag(end + 1) === ':') {
          return true;
        }
      }
      return false;
    };

    Rewriter.prototype.findTagsBackwards = function(i, tags) {
      var backStack, ref, ref1, ref2, ref3, ref4, ref5;
      backStack = [];
      while (i >= 0 && (backStack.length || (ref2 = this.tag(i), indexOf.call(tags, ref2) < 0) && ((ref3 = this.tag(i), indexOf.call(EXPRESSION_START, ref3) < 0) || this.tokens[i].generated) && (ref4 = this.tag(i), indexOf.call(LINEBREAKS, ref4) < 0))) {
        if (ref = this.tag(i), indexOf.call(EXPRESSION_END, ref) >= 0) {
          backStack.push(this.tag(i));
        }
        if ((ref1 = this.tag(i), indexOf.call(EXPRESSION_START, ref1) >= 0) && backStack.length) {
          backStack.pop();
        }
        i -= 1;
      }
      return ref5 = this.tag(i), indexOf.call(tags, ref5) >= 0;
    };

    Rewriter.prototype.addImplicitBracesAndParens = function() {
      var stack, start;
      stack = [];
      start = null;
      return this.scanTokens(function(token, i, tokens) {
        var endImplicitCall, endImplicitObject, forward, inImplicit, inImplicitCall, inImplicitControl, inImplicitObject, newLine, nextTag, offset, prevTag, prevToken, ref, ref1, ref2, ref3, ref4, ref5, s, sameLine, stackIdx, stackTag, stackTop, startIdx, startImplicitCall, startImplicitObject, startsLine, tag;
        tag = token[0];
        prevTag = (prevToken = i > 0 ? tokens[i - 1] : [])[0];
        nextTag = (i < tokens.length - 1 ? tokens[i + 1] : [])[0];
        stackTop = function() {
          return stack[stack.length - 1];
        };
        startIdx = i;
        forward = function(n) {
          return i - startIdx + n;
        };
        inImplicit = function() {
          var ref, ref1;
          return (ref = stackTop()) != null ? (ref1 = ref[2]) != null ? ref1.ours : void 0 : void 0;
        };
        inImplicitCall = function() {
          var ref;
          return inImplicit() && ((ref = stackTop()) != null ? ref[0] : void 0) === '(';
        };
        inImplicitObject = function() {
          var ref;
          return inImplicit() && ((ref = stackTop()) != null ? ref[0] : void 0) === '{';
        };
        inImplicitControl = function() {
          var ref;
          return inImplicit && ((ref = stackTop()) != null ? ref[0] : void 0) === 'CONTROL';
        };
        startImplicitCall = function(j) {
          var idx;
          idx = j != null ? j : i;
          stack.push([
            '(', idx, {
              ours: true
            }
          ]);
          tokens.splice(idx, 0, generate('CALL_START', '('));
          if (j == null) {
            return i += 1;
          }
        };
        endImplicitCall = function() {
          stack.pop();
          tokens.splice(i, 0, generate('CALL_END', ')', ['', 'end of input', token[2]]));
          return i += 1;
        };
        startImplicitObject = function(j, startsLine) {
          var idx, val;
          if (startsLine == null) {
            startsLine = true;
          }
          idx = j != null ? j : i;
          stack.push([
            '{', idx, {
              sameLine: true,
              startsLine: startsLine,
              ours: true
            }
          ]);
          val = new String('{');
          val.generated = true;
          tokens.splice(idx, 0, generate('{', val, token));
          if (j == null) {
            return i += 1;
          }
        };
        endImplicitObject = function(j) {
          j = j != null ? j : i;
          stack.pop();
          tokens.splice(j, 0, generate('}', '}', token));
          return i += 1;
        };
        if (inImplicitCall() && (tag === 'IF' || tag === 'TRY' || tag === 'FINALLY' || tag === 'CATCH' || tag === 'CLASS' || tag === 'SWITCH')) {
          stack.push([
            'CONTROL', i, {
              ours: true
            }
          ]);
          return forward(1);
        }
        if (tag === 'INDENT' && inImplicit()) {
          if (prevTag !== '=>' && prevTag !== '->' && prevTag !== '[' && prevTag !== '(' && prevTag !== ',' && prevTag !== '{' && prevTag !== 'TRY' && prevTag !== 'ELSE' && prevTag !== '=') {
            while (inImplicitCall()) {
              endImplicitCall();
            }
          }
          if (inImplicitControl()) {
            stack.pop();
          }
          stack.push([tag, i]);
          return forward(1);
        }
        if (indexOf.call(EXPRESSION_START, tag) >= 0) {
          stack.push([tag, i]);
          return forward(1);
        }
        if (indexOf.call(EXPRESSION_END, tag) >= 0) {
          while (inImplicit()) {
            if (inImplicitCall()) {
              endImplicitCall();
            } else if (inImplicitObject()) {
              endImplicitObject();
            } else {
              stack.pop();
            }
          }
          start = stack.pop();
        }
        if ((indexOf.call(IMPLICIT_FUNC, tag) >= 0 && token.spaced || tag === '?' && i > 0 && !tokens[i - 1].spaced) && (indexOf.call(IMPLICIT_CALL, nextTag) >= 0 || indexOf.call(IMPLICIT_UNSPACED_CALL, nextTag) >= 0 && !((ref = tokens[i + 1]) != null ? ref.spaced : void 0) && !((ref1 = tokens[i + 1]) != null ? ref1.newLine : void 0))) {
          if (tag === '?') {
            tag = token[0] = 'FUNC_EXIST';
          }
          startImplicitCall(i + 1);
          return forward(2);
        }
        if (indexOf.call(IMPLICIT_FUNC, tag) >= 0 && this.indexOfTag(i + 1, 'INDENT') > -1 && this.looksObjectish(i + 2) && !this.findTagsBackwards(i, ['CLASS', 'EXTENDS', 'IF', 'CATCH', 'SWITCH', 'LEADING_WHEN', 'FOR', 'WHILE', 'UNTIL'])) {
          startImplicitCall(i + 1);
          stack.push(['INDENT', i + 2]);
          return forward(3);
        }
        if (tag === ':') {
          s = (function() {
            var ref2;
            switch (false) {
              case ref2 = this.tag(i - 1), indexOf.call(EXPRESSION_END, ref2) < 0:
                return start[1];
              case this.tag(i - 2) !== '@':
                return i - 2;
              default:
                return i - 1;
            }
          }).call(this);
          while (this.tag(s - 2) === 'HERECOMMENT') {
            s -= 2;
          }
          this.insideForDeclaration = nextTag === 'FOR';
          startsLine = s === 0 || (ref2 = this.tag(s - 1), indexOf.call(LINEBREAKS, ref2) >= 0) || tokens[s - 1].newLine;
          if (stackTop()) {
            ref3 = stackTop(), stackTag = ref3[0], stackIdx = ref3[1];
            if ((stackTag === '{' || stackTag === 'INDENT' && this.tag(stackIdx - 1) === '{') && (startsLine || this.tag(s - 1) === ',' || this.tag(s - 1) === '{')) {
              return forward(1);
            }
          }
          startImplicitObject(s, !!startsLine);
          return forward(2);
        }
        if (inImplicitObject() && indexOf.call(LINEBREAKS, tag) >= 0) {
          stackTop()[2].sameLine = false;
        }
        newLine = prevTag === 'OUTDENT' || prevToken.newLine;
        if (indexOf.call(IMPLICIT_END, tag) >= 0 || indexOf.call(CALL_CLOSERS, tag) >= 0 && newLine) {
          while (inImplicit()) {
            ref4 = stackTop(), stackTag = ref4[0], stackIdx = ref4[1], (ref5 = ref4[2], sameLine = ref5.sameLine, startsLine = ref5.startsLine);
            if (inImplicitCall() && prevTag !== ',') {
              endImplicitCall();
            } else if (inImplicitObject() && !this.insideForDeclaration && sameLine && tag !== 'TERMINATOR' && prevTag !== ':') {
              endImplicitObject();
            } else if (inImplicitObject() && tag === 'TERMINATOR' && prevTag !== ',' && !(startsLine && this.looksObjectish(i + 1))) {
              if (nextTag === 'HERECOMMENT') {
                return forward(1);
              }
              endImplicitObject();
            } else {
              break;
            }
          }
        }
        if (tag === ',' && !this.looksObjectish(i + 1) && inImplicitObject() && !this.insideForDeclaration && (nextTag !== 'TERMINATOR' || !this.looksObjectish(i + 2))) {
          offset = nextTag === 'OUTDENT' ? 1 : 0;
          while (inImplicitObject()) {
            endImplicitObject(i + offset);
          }
        }
        return forward(1);
      });
    };

    Rewriter.prototype.addLocationDataToGeneratedTokens = function() {
      return this.scanTokens(function(token, i, tokens) {
        var column, line, nextLocation, prevLocation, ref, ref1;
        if (token[2]) {
          return 1;
        }
        if (!(token.generated || token.explicit)) {
          return 1;
        }
        if (token[0] === '{' && (nextLocation = (ref = tokens[i + 1]) != null ? ref[2] : void 0)) {
          line = nextLocation.first_line, column = nextLocation.first_column;
        } else if (prevLocation = (ref1 = tokens[i - 1]) != null ? ref1[2] : void 0) {
          line = prevLocation.last_line, column = prevLocation.last_column;
        } else {
          line = column = 0;
        }
        token[2] = {
          first_line: line,
          first_column: column,
          last_line: line,
          last_column: column
        };
        return 1;
      });
    };

    Rewriter.prototype.normalizeLines = function() {
      var action, condition, indent, outdent, starter;
      starter = indent = outdent = null;
      condition = function(token, i) {
        var ref, ref1, ref2, ref3;
        return token[1] !== ';' && (ref = token[0], indexOf.call(SINGLE_CLOSERS, ref) >= 0) && !(token[0] === 'TERMINATOR' && (ref1 = this.tag(i + 1), indexOf.call(EXPRESSION_CLOSE, ref1) >= 0)) && !(token[0] === 'ELSE' && starter !== 'THEN') && !(((ref2 = token[0]) === 'CATCH' || ref2 === 'FINALLY') && (starter === '->' || starter === '=>')) || (ref3 = token[0], indexOf.call(CALL_CLOSERS, ref3) >= 0) && this.tokens[i - 1].newLine;
      };
      action = function(token, i) {
        return this.tokens.splice((this.tag(i - 1) === ',' ? i - 1 : i), 0, outdent);
      };
      return this.scanTokens(function(token, i, tokens) {
        var j, k, ref, ref1, ref2, tag;
        tag = token[0];
        if (tag === 'TERMINATOR') {
          if (this.tag(i + 1) === 'ELSE' && this.tag(i - 1) !== 'OUTDENT') {
            tokens.splice.apply(tokens, [i, 1].concat(slice.call(this.indentation())));
            return 1;
          }
          if (ref = this.tag(i + 1), indexOf.call(EXPRESSION_CLOSE, ref) >= 0) {
            tokens.splice(i, 1);
            return 0;
          }
        }
        if (tag === 'CATCH') {
          for (j = k = 1; k <= 2; j = ++k) {
            if (!((ref1 = this.tag(i + j)) === 'OUTDENT' || ref1 === 'TERMINATOR' || ref1 === 'FINALLY')) {
              continue;
            }
            tokens.splice.apply(tokens, [i + j, 0].concat(slice.call(this.indentation())));
            return 2 + j;
          }
        }
        if (indexOf.call(SINGLE_LINERS, tag) >= 0 && this.tag(i + 1) !== 'INDENT' && !(tag === 'ELSE' && this.tag(i + 1) === 'IF')) {
          starter = tag;
          ref2 = this.indentation(tokens[i]), indent = ref2[0], outdent = ref2[1];
          if (starter === 'THEN') {
            indent.fromThen = true;
          }
          tokens.splice(i + 1, 0, indent);
          this.detectEnd(i + 2, condition, action);
          if (tag === 'THEN') {
            tokens.splice(i, 1);
          }
          return 1;
        }
        return 1;
      });
    };

    Rewriter.prototype.tagPostfixConditionals = function() {
      var action, condition, original;
      original = null;
      condition = function(token, i) {
        var prevTag, tag;
        tag = token[0];
        prevTag = this.tokens[i - 1][0];
        return tag === 'TERMINATOR' || (tag === 'INDENT' && indexOf.call(SINGLE_LINERS, prevTag) < 0);
      };
      action = function(token, i) {
        if (token[0] !== 'INDENT' || (token.generated && !token.fromThen)) {
          return original[0] = 'POST_' + original[0];
        }
      };
      return this.scanTokens(function(token, i) {
        if (token[0] !== 'IF') {
          return 1;
        }
        original = token;
        this.detectEnd(i + 1, condition, action);
        return 1;
      });
    };

    Rewriter.prototype.indentation = function(origin) {
      var indent, outdent;
      indent = ['INDENT', 2];
      outdent = ['OUTDENT', 2];
      if (origin) {
        indent.generated = outdent.generated = true;
        indent.origin = outdent.origin = origin;
      } else {
        indent.explicit = outdent.explicit = true;
      }
      return [indent, outdent];
    };

    Rewriter.prototype.generate = generate;

    Rewriter.prototype.tag = function(i) {
      var ref;
      return (ref = this.tokens[i]) != null ? ref[0] : void 0;
    };

    return Rewriter;

  })();

  BALANCED_PAIRS = [['(', ')'], ['[', ']'], ['{', '}'], ['INDENT', 'OUTDENT'], ['CALL_START', 'CALL_END'], ['PARAM_START', 'PARAM_END'], ['INDEX_START', 'INDEX_END'], ['STRING_START', 'STRING_END'], ['REGEX_START', 'REGEX_END']];

  exports.INVERSES = INVERSES = {};

  EXPRESSION_START = [];

  EXPRESSION_END = [];

  for (k = 0, len = BALANCED_PAIRS.length; k < len; k++) {
    ref = BALANCED_PAIRS[k], left = ref[0], rite = ref[1];
    EXPRESSION_START.push(INVERSES[rite] = left);
    EXPRESSION_END.push(INVERSES[left] = rite);
  }

  EXPRESSION_CLOSE = ['CATCH', 'THEN', 'ELSE', 'FINALLY'].concat(EXPRESSION_END);

  IMPLICIT_FUNC = ['IDENTIFIER', 'SUPER', ')', 'CALL_END', ']', 'INDEX_END', '@', 'THIS'];

  IMPLICIT_CALL = ['IDENTIFIER', 'NUMBER', 'STRING', 'STRING_START', 'JS', 'REGEX', 'REGEX_START', 'NEW', 'PARAM_START', 'CLASS', 'IF', 'TRY', 'SWITCH', 'THIS', 'BOOL', 'NULL', 'UNDEFINED', 'UNARY', 'YIELD', 'UNARY_MATH', 'SUPER', 'THROW', '@', '->', '=>', '[', '(', '{', '--', '++'];

  IMPLICIT_UNSPACED_CALL = ['+', '-'];

  IMPLICIT_END = ['POST_IF', 'FOR', 'WHILE', 'UNTIL', 'WHEN', 'BY', 'LOOP', 'TERMINATOR'];

  SINGLE_LINERS = ['ELSE', '->', '=>', 'TRY', 'FINALLY', 'THEN'];

  SINGLE_CLOSERS = ['TERMINATOR', 'CATCH', 'FINALLY', 'ELSE', 'OUTDENT', 'LEADING_WHEN'];

  LINEBREAKS = ['TERMINATOR', 'INDENT', 'OUTDENT'];

  CALL_CLOSERS = ['.', '?.', '::', '?::'];

}).call(this);

},{}],"coffee-script/lib/coffee-script/scope":[function(require,module,exports){
// Generated by CoffeeScript 1.10.0
(function() {
  var Scope,
    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; };

  exports.Scope = Scope = (function() {
    function Scope(parent, expressions, method, referencedVars) {
      var ref, ref1;
      this.parent = parent;
      this.expressions = expressions;
      this.method = method;
      this.referencedVars = referencedVars;
      this.variables = [
        {
          name: 'arguments',
          type: 'arguments'
        }
      ];
      this.positions = {};
      if (!this.parent) {
        this.utilities = {};
      }
      this.root = (ref = (ref1 = this.parent) != null ? ref1.root : void 0) != null ? ref : this;
    }

    Scope.prototype.add = function(name, type, immediate) {
      if (this.shared && !immediate) {
        return this.parent.add(name, type, immediate);
      }
      if (Object.prototype.hasOwnProperty.call(this.positions, name)) {
        return this.variables[this.positions[name]].type = type;
      } else {
        return this.positions[name] = this.variables.push({
          name: name,
          type: type
        }) - 1;
      }
    };

    Scope.prototype.namedMethod = function() {
      var ref;
      if (((ref = this.method) != null ? ref.name : void 0) || !this.parent) {
        return this.method;
      }
      return this.parent.namedMethod();
    };

    Scope.prototype.find = function(name) {
      if (this.check(name)) {
        return true;
      }
      this.add(name, 'var');
      return false;
    };

    Scope.prototype.parameter = function(name) {
      if (this.shared && this.parent.check(name, true)) {
        return;
      }
      return this.add(name, 'param');
    };

    Scope.prototype.check = function(name) {
      var ref;
      return !!(this.type(name) || ((ref = this.parent) != null ? ref.check(name) : void 0));
    };

    Scope.prototype.temporary = function(name, index, single) {
      if (single == null) {
        single = false;
      }
      if (single) {
        return (index + parseInt(name, 36)).toString(36).replace(/\d/g, 'a');
      } else {
        return name + (index || '');
      }
    };

    Scope.prototype.type = function(name) {
      var i, len, ref, v;
      ref = this.variables;
      for (i = 0, len = ref.length; i < len; i++) {
        v = ref[i];
        if (v.name === name) {
          return v.type;
        }
      }
      return null;
    };

    Scope.prototype.freeVariable = function(name, options) {
      var index, ref, temp;
      if (options == null) {
        options = {};
      }
      index = 0;
      while (true) {
        temp = this.temporary(name, index, options.single);
        if (!(this.check(temp) || indexOf.call(this.root.referencedVars, temp) >= 0)) {
          break;
        }
        index++;
      }
      if ((ref = options.reserve) != null ? ref : true) {
        this.add(temp, 'var', true);
      }
      return temp;
    };

    Scope.prototype.assign = function(name, value) {
      this.add(name, {
        value: value,
        assigned: true
      }, true);
      return this.hasAssignments = true;
    };

    Scope.prototype.hasDeclarations = function() {
      return !!this.declaredVariables().length;
    };

    Scope.prototype.declaredVariables = function() {
      var v;
      return ((function() {
        var i, len, ref, results;
        ref = this.variables;
        results = [];
        for (i = 0, len = ref.length; i < len; i++) {
          v = ref[i];
          if (v.type === 'var') {
            results.push(v.name);
          }
        }
        return results;
      }).call(this)).sort();
    };

    Scope.prototype.assignedVariables = function() {
      var i, len, ref, results, v;
      ref = this.variables;
      results = [];
      for (i = 0, len = ref.length; i < len; i++) {
        v = ref[i];
        if (v.type.assigned) {
          results.push(v.name + " = " + v.type.value);
        }
      }
      return results;
    };

    return Scope;

  })();

}).call(this);

},{}],"coffee-script/lib/coffee-script/sourcemap":[function(require,module,exports){
// Generated by CoffeeScript 1.10.0
(function() {
  var LineMap, SourceMap;

  LineMap = (function() {
    function LineMap(line1) {
      this.line = line1;
      this.columns = [];
    }

    LineMap.prototype.add = function(column, arg, options) {
      var sourceColumn, sourceLine;
      sourceLine = arg[0], sourceColumn = arg[1];
      if (options == null) {
        options = {};
      }
      if (this.columns[column] && options.noReplace) {
        return;
      }
      return this.columns[column] = {
        line: this.line,
        column: column,
        sourceLine: sourceLine,
        sourceColumn: sourceColumn
      };
    };

    LineMap.prototype.sourceLocation = function(column) {
      var mapping;
      while (!((mapping = this.columns[column]) || (column <= 0))) {
        column--;
      }
      return mapping && [mapping.sourceLine, mapping.sourceColumn];
    };

    return LineMap;

  })();

  SourceMap = (function() {
    var BASE64_CHARS, VLQ_CONTINUATION_BIT, VLQ_SHIFT, VLQ_VALUE_MASK;

    function SourceMap() {
      this.lines = [];
    }

    SourceMap.prototype.add = function(sourceLocation, generatedLocation, options) {
      var base, column, line, lineMap;
      if (options == null) {
        options = {};
      }
      line = generatedLocation[0], column = generatedLocation[1];
      lineMap = ((base = this.lines)[line] || (base[line] = new LineMap(line)));
      return lineMap.add(column, sourceLocation, options);
    };

    SourceMap.prototype.sourceLocation = function(arg) {
      var column, line, lineMap;
      line = arg[0], column = arg[1];
      while (!((lineMap = this.lines[line]) || (line <= 0))) {
        line--;
      }
      return lineMap && lineMap.sourceLocation(column);
    };

    SourceMap.prototype.generate = function(options, code) {
      var buffer, i, j, lastColumn, lastSourceColumn, lastSourceLine, len, len1, lineMap, lineNumber, mapping, needComma, ref, ref1, v3, writingline;
      if (options == null) {
        options = {};
      }
      if (code == null) {
        code = null;
      }
      writingline = 0;
      lastColumn = 0;
      lastSourceLine = 0;
      lastSourceColumn = 0;
      needComma = false;
      buffer = "";
      ref = this.lines;
      for (lineNumber = i = 0, len = ref.length; i < len; lineNumber = ++i) {
        lineMap = ref[lineNumber];
        if (lineMap) {
          ref1 = lineMap.columns;
          for (j = 0, len1 = ref1.length; j < len1; j++) {
            mapping = ref1[j];
            if (!(mapping)) {
              continue;
            }
            while (writingline < mapping.line) {
              lastColumn = 0;
              needComma = false;
              buffer += ";";
              writingline++;
            }
            if (needComma) {
              buffer += ",";
              needComma = false;
            }
            buffer += this.encodeVlq(mapping.column - lastColumn);
            lastColumn = mapping.column;
            buffer += this.encodeVlq(0);
            buffer += this.encodeVlq(mapping.sourceLine - lastSourceLine);
            lastSourceLine = mapping.sourceLine;
            buffer += this.encodeVlq(mapping.sourceColumn - lastSourceColumn);
            lastSourceColumn = mapping.sourceColumn;
            needComma = true;
          }
        }
      }
      v3 = {
        version: 3,
        file: options.generatedFile || '',
        sourceRoot: options.sourceRoot || '',
        sources: options.sourceFiles || [''],
        names: [],
        mappings: buffer
      };
      if (options.inline) {
        v3.sourcesContent = [code];
      }
      return JSON.stringify(v3, null, 2);
    };

    VLQ_SHIFT = 5;

    VLQ_CONTINUATION_BIT = 1 << VLQ_SHIFT;

    VLQ_VALUE_MASK = VLQ_CONTINUATION_BIT - 1;

    SourceMap.prototype.encodeVlq = function(value) {
      var answer, nextChunk, signBit, valueToEncode;
      answer = '';
      signBit = value < 0 ? 1 : 0;
      valueToEncode = (Math.abs(value) << 1) + signBit;
      while (valueToEncode || !answer) {
        nextChunk = valueToEncode & VLQ_VALUE_MASK;
        valueToEncode = valueToEncode >> VLQ_SHIFT;
        if (valueToEncode) {
          nextChunk |= VLQ_CONTINUATION_BIT;
        }
        answer += this.encodeBase64(nextChunk);
      }
      return answer;
    };

    BASE64_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';

    SourceMap.prototype.encodeBase64 = function(value) {
      return BASE64_CHARS[value] || (function() {
        throw new Error("Cannot Base64 encode value: " + value);
      })();
    };

    return SourceMap;

  })();

  module.exports = SourceMap;

}).call(this);

},{}],"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":"browserify/node_modules/process/browser"}],"hammerjs/hammer":[function(require,module,exports){
/*! Hammer.JS - v2.0.4 - 2014-09-28
 * http://hammerjs.github.io/
 *
 * Copyright (c) 2014 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);
        }
    }
}

/**
 * extend object.
 * means that properties in dest will be overwritten by the ones in src.
 * @param {Object} dest
 * @param {Object} src
 * @param {Boolean} [merge]
 * @returns {Object} dest
 */
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;
}

/**
 * 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
 */
function merge(dest, src) {
    return extend(dest, src, true);
}

/**
 * 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) {
        extend(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;
    return (doc.defaultView || doc.parentWindow);
}

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

    input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1;
    input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0;

    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 = last.deltaX - input.deltaX;
        var deltaY = last.deltaY - input.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.allow = true; // used by Input.TouchMouse to disable mouse 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, and mouse events are allowed (see the TouchMouse input)
        if (!this.pressed || !this.allow) {
            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) {
    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
 */
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);
}

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

        // when we're in a touch event, so  block all upcoming mouse events
        // most mobile browser also emit mouseevents, right after touchstart
        if (isTouch) {
            this.mouse.allow = false;
        } else if (isMouse && !this.mouse.allow) {
            return;
        }

        // reset the allowMouse when we're done
        if (inputEvent & (INPUT_END | INPUT_CANCEL)) {
            this.mouse.allow = true;
        }

        this.callback(manager, inputEvent, inputData);
    },

    /**
     * remove the event listeners
     */
    destroy: function destroy() {
        this.touch.destroy();
        this.mouse.destroy();
    }
});

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

/**
 * 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[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) {
        // not needed with native support for the touchAction property
        if (NATIVE_TOUCH_ACTION) {
            return;
        }

        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);
        var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y);
        var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X);

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

    // pan-x and pan-y can be combined
    if (hasPanX && hasPanY) {
        return TOUCH_ACTION_PAN_X + ' ' + TOUCH_ACTION_PAN_Y;
    }

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

/**
 * 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.id = uniqueId();

    this.manager = null;
    this.options = merge(options || {}, this.defaults);

    // 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) {
        extend(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(withState) {
            self.manager.emit(self.options.event + (withState ? stateStr(state) : ''), input);
        }

        // 'panstart' and 'panmove'
        if (state < STATE_ENDED) {
            emit(true);
        }

        emit(); // simple 'eventName' events

        // panend and pancancel
        if (state >= STATE_ENDED) {
            emit(true);
        }
    },

    /**
     * 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 = extend({}, 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) {
            this.manager.emit(this.options.event + direction, input);
        }

        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) {
        this._super.emit.call(this, input);
        if (input.scale !== 1) {
            var inOut = input.scale < 1 ? 'in' : 'out';
            this.manager.emit(this.options.event + inOut, 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: 500, // minimal time of the pointer to be pressed
        threshold: 5 // 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.65,
        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.velocity;
        } else if (direction & DIRECTION_HORIZONTAL) {
            velocity = input.velocityX;
        } else if (direction & DIRECTION_VERTICAL) {
            velocity = input.velocityY;
        }

        return this._super.attrTest.call(this, input) &&
            direction & input.direction &&
            input.distance > this.options.threshold &&
            abs(velocity) > this.options.velocity && input.eventType & INPUT_END;
    },

    emit: function(input) {
        var direction = directionStr(input.direction);
        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: 2, // 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 an 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.4';

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

    this.options = merge(options, Hammer.defaults);
    this.options.inputTarget = this.options.inputTarget || element;

    this.handlers = {};
    this.session = {};
    this.recognizers = [];

    this.element = element;
    this.input = createInputInstance(this);
    this.touchAction = new TouchAction(this, this.options.touchAction);

    toggleCssProps(this, true);

    each(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) {
        extend(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;
        }

        var recognizers = this.recognizers;
        recognizer = this.get(recognizer);
        recognizers.splice(inArray(recognizers, recognizer), 1);

        this.touchAction.update();
        return this;
    },

    /**
     * bind event
     * @param {String} events
     * @param {Function} handler
     * @returns {EventEmitter} this
     */
    on: function(events, handler) {
        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) {
        var handlers = this.handlers;
        each(splitStr(events), function(event) {
            if (!handler) {
                delete handlers[event];
            } else {
                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;
    each(manager.options.cssProps, function(value, name) {
        element.style[prefixed(element.style, name)] = add ? value : '';
    });
}

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

extend(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,
    inherit: inherit,
    bindFn: bindFn,
    prefixed: prefixed
});

if (typeof define == TYPE_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.1.4
 * http://jquery.com/
 *
 * Includes Sizzle.js
 * http://sizzlejs.com/
 *
 * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors
 * Released under the MIT license
 * http://jquery.org/license
 *
 * Date: 2015-04-28T16:01Z
 */

(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)
//

var arr = [];

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
	// Use the correct document accordingly with window argument (sandbox)
	document = window.document,

	version = "2.1.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.
	// (You can seed the arguments with an array of args, but this is
	// only used internally.)
	each: function( callback, args ) {
		return jQuery.each( this, callback, args );
	},

	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(null);
	},

	// 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)
		return !jQuery.isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 0;
	},

	isPlainObject: function( obj ) {
		// 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;
		}

		if ( obj.constructor &&
				!hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
			return false;
		}

		// If the function hasn't returned already, we're confident that
		// |obj| is a plain object, created by {} or constructed with new Object
		return true;
	},

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

	// args is for internal usage only
	each: function( obj, callback, args ) {
		var value,
			i = 0,
			length = obj.length,
			isArray = isArraylike( obj );

		if ( args ) {
			if ( isArray ) {
				for ( ; i < length; i++ ) {
					value = callback.apply( obj[ i ], args );

					if ( value === false ) {
						break;
					}
				}
			} else {
				for ( i in obj ) {
					value = callback.apply( obj[ i ], args );

					if ( value === false ) {
						break;
					}
				}
			}

		// A special, fast, case for the most common use of each
		} else {
			if ( isArray ) {
				for ( ; i < length; i++ ) {
					value = callback.call( obj[ i ], i, obj[ i ] );

					if ( value === false ) {
						break;
					}
				}
			} else {
				for ( i in obj ) {
					value = callback.call( obj[ i ], i, obj[ i ] );

					if ( value === 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 value,
			i = 0,
			length = elems.length,
			isArray = isArraylike( elems ),
			ret = [];

		// Go through the array, translating each of the items to their new values
		if ( isArray ) {
			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
});

// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".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 = "length" in obj && obj.length,
		type = jQuery.type( obj );

	if ( type === "function" || jQuery.isWindow( obj ) ) {
		return false;
	}

	if ( obj.nodeType === 1 && length ) {
		return true;
	}

	return type === "array" || length === 0 ||
		typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
var Sizzle =
/*!
 * Sizzle CSS Selector Engine v2.2.0-pre
 * http://sizzlejs.com/
 *
 * Copyright 2008, 2014 jQuery Foundation, Inc. and other contributors
 * Released under the MIT license
 * http://jquery.org/license
 *
 * Date: 2014-12-16
 */
(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

	// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
	whitespace = "[\\x20\\t\\r\\n\\f]",
	// http://www.w3.org/TR/css3-syntax/#characters
	characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",

	// Loosely modeled on CSS identifier characters
	// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
	// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
	identifier = characterEncoding.replace( "w", "w#" ),

	// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
	attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace +
		// Operator (capture 2)
		"*([*^$|!~]?=)" + whitespace +
		// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
		"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
		"*\\]",

	pseudos = ":(" + characterEncoding + ")(?:\\((" +
		// 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( "^#(" + characterEncoding + ")" ),
		"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
		"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
		"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 match, elem, m, nodeType,
		// QSA vars
		i, groups, old, nid, newContext, newSelector;

	if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
		setDocument( context );
	}

	context = context || document;
	results = results || [];
	nodeType = context.nodeType;

	if ( typeof selector !== "string" || !selector ||
		nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {

		return results;
	}

	if ( !seed && documentIsHTML ) {

		// Try to shortcut find operations when possible (e.g., not under DocumentFragment)
		if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) {
			// Speed-up: Sizzle("#ID")
			if ( (m = match[1]) ) {
				if ( nodeType === 9 ) {
					elem = context.getElementById( m );
					// Check parentNode to catch when Blackberry 4.6 returns
					// nodes that are no longer in the document (jQuery #6963)
					if ( elem && elem.parentNode ) {
						// Handle the case where IE, Opera, and Webkit return items
						// by name instead of ID
						if ( elem.id === m ) {
							results.push( elem );
							return results;
						}
					} else {
						return results;
					}
				} else {
					// Context is not a document
					if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
						contains( context, elem ) && elem.id === m ) {
						results.push( elem );
						return results;
					}
				}

			// Speed-up: Sizzle("TAG")
			} else if ( match[2] ) {
				push.apply( results, context.getElementsByTagName( selector ) );
				return results;

			// Speed-up: Sizzle(".CLASS")
			} else if ( (m = match[3]) && support.getElementsByClassName ) {
				push.apply( results, context.getElementsByClassName( m ) );
				return results;
			}
		}

		// QSA path
		if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
			nid = old = expando;
			newContext = context;
			newSelector = nodeType !== 1 && selector;

			// qSA works strangely on Element-rooted queries
			// We can work around this by specifying an extra ID on the root
			// and working up from there (Thanks to Andrew Dupont for the technique)
			// IE 8 doesn't work on object elements
			if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
				groups = tokenize( selector );

				if ( (old = context.getAttribute("id")) ) {
					nid = old.replace( rescape, "\\$&" );
				} else {
					context.setAttribute( "id", nid );
				}
				nid = "[id='" + nid + "'] ";

				i = groups.length;
				while ( i-- ) {
					groups[i] = nid + toSelector( groups[i] );
				}
				newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context;
				newSelector = groups.join(",");
			}

			if ( newSelector ) {
				try {
					push.apply( results,
						newContext.querySelectorAll( newSelector )
					);
					return results;
				} catch(qsaError) {
				} finally {
					if ( !old ) {
						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 = attrs.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;

	// If no document and documentElement is available, return
	if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
		return document;
	}

	// Set our document
	document = doc;
	docElem = doc.documentElement;
	parent = doc.defaultView;

	// Support: IE>8
	// If iframe document is assigned to "document" variable and if iframe has been reloaded,
	// IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
	// IE6-8 do not support the defaultView property so parent will be undefined
	if ( parent && parent !== parent.top ) {
		// IE11 does not have attachEvent, so all must suffer
		if ( parent.addEventListener ) {
			parent.addEventListener( "unload", unloadHandler, false );
		} else if ( parent.attachEvent ) {
			parent.attachEvent( "onunload", unloadHandler );
		}
	}

	/* Support tests
	---------------------------------------------------------------------- */
	documentIsHTML = !isXML( doc );

	/* 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( doc.createComment("") );
		return !div.getElementsByTagName("*").length;
	});

	// Support: IE<9
	support.getElementsByClassName = rnative.test( doc.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 !doc.getElementsByName || !doc.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 );
				// Check parentNode to catch when Blackberry 4.6 returns
				// nodes that are no longer in the document #6963
				return m && m.parentNode ? [ 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 ( 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( doc.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 + "-\f]' 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.2+, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.7+
			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 = doc.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 does not implement inclusive descendent
	// 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 === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
				return -1;
			}
			if ( b === doc || 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 === doc ? -1 :
				b === doc ? 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 doc;
};

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 &&
		( !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, outerCache, node, diff, nodeIndex, start,
						dir = simple !== forward ? "nextSibling" : "previousSibling",
						parent = elem.parentNode,
						name = ofType && elem.nodeName.toLowerCase(),
						useCache = !xml && !ofType;

					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
							outerCache = parent[ expando ] || (parent[ expando ] = {});
							cache = outerCache[ type ] || [];
							nodeIndex = cache[0] === dirruns && cache[1];
							diff = cache[0] === dirruns && 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 ) {
									outerCache[ type ] = [ dirruns, nodeIndex, diff ];
									break;
								}
							}

						// Use previously-cached element index if available
						} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
							diff = cache[1];

						// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
						} else {
							// 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 ) {
										(node[ expando ] || (node[ expando ] = {}))[ 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, outerCache,
				newCache = [ dirruns, doneName ];

			// We can't set arbitrary data on XML nodes, so they don't benefit from dir 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 ] = {});
						if ( (oldCache = outerCache[ 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
							outerCache[ 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;
			}

			// Add elements passing elementMatchers directly to results
			// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
			// 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;
					while ( (matcher = elementMatchers[j++]) ) {
						if ( matcher( elem, context, 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 );
					}
				}
			}

			// Apply set filters to unmatched elements
			matchedCount += i;
			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 no seed and only one group
	if ( match.length === 1 ) {

		// Take a shortcut and set the context if the root 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,
		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.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;



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 ) >= 0 ) !== 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 ) {
		var match, elem;

		// HANDLE: $(""), $(null), $(undefined), $(false)
		if ( !selector ) {
			return this;
		}

		// 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 || rootjQuery ).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 typeof rootjQuery.ready !== "undefined" ?
				rootjQuery.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.extend({
	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;
	},

	sibling: function( n, elem ) {
		var matched = [];

		for ( ; n; n = n.nextSibling ) {
			if ( n.nodeType === 1 && n !== elem ) {
				matched.push( n );
			}
		}

		return matched;
	}
});

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.unique( 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.unique(
				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 jQuery.dir( elem, "parentNode" );
	},
	parentsUntil: function( elem, i, until ) {
		return jQuery.dir( elem, "parentNode", until );
	},
	next: function( elem ) {
		return sibling( elem, "nextSibling" );
	},
	prev: function( elem ) {
		return sibling( elem, "previousSibling" );
	},
	nextAll: function( elem ) {
		return jQuery.dir( elem, "nextSibling" );
	},
	prevAll: function( elem ) {
		return jQuery.dir( elem, "previousSibling" );
	},
	nextUntil: function( elem, i, until ) {
		return jQuery.dir( elem, "nextSibling", until );
	},
	prevUntil: function( elem, i, until ) {
		return jQuery.dir( elem, "previousSibling", until );
	},
	siblings: function( elem ) {
		return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
	},
	children: function( elem ) {
		return jQuery.sibling( 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.unique( matched );
			}

			// Reverse order for parents* and prev-derivatives
			if ( rparentsprev.test( name ) ) {
				matched.reverse();
			}
		}

		return this.pushStack( matched );
	};
});
var rnotwhite = (/\S+/g);



// String to Object options format cache
var optionsCache = {};

// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
	var object = optionsCache[ options ] = {};
	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" ?
		( optionsCache[ options ] || createOptions( options ) ) :
		jQuery.extend( {}, options );

	var // Last fire value (for non-forgettable lists)
		memory,
		// Flag to know if list was already fired
		fired,
		// Flag to know if list is currently firing
		firing,
		// First callback to fire (used internally by add and fireWith)
		firingStart,
		// End of the loop when firing
		firingLength,
		// Index of currently firing callback (modified by remove if needed)
		firingIndex,
		// Actual callback list
		list = [],
		// Stack of fire calls for repeatable lists
		stack = !options.once && [],
		// Fire callbacks
		fire = function( data ) {
			memory = options.memory && data;
			fired = true;
			firingIndex = firingStart || 0;
			firingStart = 0;
			firingLength = list.length;
			firing = true;
			for ( ; list && firingIndex < firingLength; firingIndex++ ) {
				if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
					memory = false; // To prevent further calls using add
					break;
				}
			}
			firing = false;
			if ( list ) {
				if ( stack ) {
					if ( stack.length ) {
						fire( stack.shift() );
					}
				} else if ( memory ) {
					list = [];
				} else {
					self.disable();
				}
			}
		},
		// Actual Callbacks object
		self = {
			// Add a callback or a collection of callbacks to the list
			add: function() {
				if ( list ) {
					// First, we save the current length
					var start = list.length;
					(function add( args ) {
						jQuery.each( args, function( _, arg ) {
							var type = jQuery.type( arg );
							if ( type === "function" ) {
								if ( !options.unique || !self.has( arg ) ) {
									list.push( arg );
								}
							} else if ( arg && arg.length && type !== "string" ) {
								// Inspect recursively
								add( arg );
							}
						});
					})( arguments );
					// Do we need to add the callbacks to the
					// current firing batch?
					if ( firing ) {
						firingLength = list.length;
					// With memory, if we're not firing then
					// we should call right away
					} else if ( memory ) {
						firingStart = start;
						fire( memory );
					}
				}
				return this;
			},
			// Remove a callback from the list
			remove: function() {
				if ( list ) {
					jQuery.each( arguments, function( _, arg ) {
						var index;
						while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
							list.splice( index, 1 );
							// Handle firing indexes
							if ( firing ) {
								if ( index <= firingLength ) {
									firingLength--;
								}
								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 && list.length );
			},
			// Remove all callbacks from the list
			empty: function() {
				list = [];
				firingLength = 0;
				return this;
			},
			// Have the list do nothing anymore
			disable: function() {
				list = stack = memory = undefined;
				return this;
			},
			// Is it disabled?
			disabled: function() {
				return !list;
			},
			// Lock the list in its current state
			lock: function() {
				stack = undefined;
				if ( !memory ) {
					self.disable();
				}
				return this;
			},
			// Is it locked?
			locked: function() {
				return !stack;
			},
			// Call all callbacks with the given context and arguments
			fireWith: function( context, args ) {
				if ( list && ( !fired || stack ) ) {
					args = args || [];
					args = [ context, args.slice ? args.slice() : args ];
					if ( firing ) {
						stack.push( args );
					} else {
						fire( args );
					}
				}
				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()
										.done( newDefer.resolve )
										.fail( newDefer.reject )
										.progress( newDefer.notify );
								} 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()
						.done( updateFunc( i, resolveContexts, resolveValues ) )
						.fail( deferred.reject )
						.progress( updateFunc( i, progressContexts, progressValues ) );
				} 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, false );
	window.removeEventListener( "load", completed, false );
	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.
		// We once tried to use readyState "interactive" here, but it caused issues like the one
		// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
		if ( document.readyState === "complete" ) {
			// Handle it asynchronously to allow scripts the opportunity to delay ready
			setTimeout( jQuery.ready );

		} else {

			// Use the handy event callback
			document.addEventListener( "DOMContentLoaded", completed, false );

			// A fallback to window.onload, that will always work
			window.addEventListener( "load", completed, false );
		}
	}
	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 = jQuery.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 ) {
			jQuery.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;
};


/**
 * Determines whether an object can have data
 */
jQuery.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() {
	// Support: Android<4,
	// Old WebKit does not have Object.preventExtensions/freeze method,
	// return new empty object instead with no [[set]] accessor
	Object.defineProperty( this.cache = {}, 0, {
		get: function() {
			return {};
		}
	});

	this.expando = jQuery.expando + Data.uid++;
}

Data.uid = 1;
Data.accepts = jQuery.acceptData;

Data.prototype = {
	key: function( owner ) {
		// We can accept data for non-element nodes in modern browsers,
		// but we should not, see #8335.
		// Always return the key for a frozen object.
		if ( !Data.accepts( owner ) ) {
			return 0;
		}

		var descriptor = {},
			// Check if the owner object already has a cache key
			unlock = owner[ this.expando ];

		// If not, create one
		if ( !unlock ) {
			unlock = Data.uid++;

			// Secure it in a non-enumerable, non-writable property
			try {
				descriptor[ this.expando ] = { value: unlock };
				Object.defineProperties( owner, descriptor );

			// Support: Android<4
			// Fallback to a less secure definition
			} catch ( e ) {
				descriptor[ this.expando ] = unlock;
				jQuery.extend( owner, descriptor );
			}
		}

		// Ensure the cache object
		if ( !this.cache[ unlock ] ) {
			this.cache[ unlock ] = {};
		}

		return unlock;
	},
	set: function( owner, data, value ) {
		var prop,
			// There may be an unlock assigned to this node,
			// if there is no entry for this "owner", create one inline
			// and set the unlock as though an owner entry had always existed
			unlock = this.key( owner ),
			cache = this.cache[ unlock ];

		// Handle: [ owner, key, value ] args
		if ( typeof data === "string" ) {
			cache[ data ] = value;

		// Handle: [ owner, { properties } ] args
		} else {
			// Fresh assignments by object are shallow copied
			if ( jQuery.isEmptyObject( cache ) ) {
				jQuery.extend( this.cache[ unlock ], data );
			// Otherwise, copy the properties one-by-one to the cache object
			} else {
				for ( prop in data ) {
					cache[ prop ] = data[ prop ];
				}
			}
		}
		return cache;
	},
	get: function( owner, key ) {
		// Either a valid cache is found, or will be created.
		// New caches will be created and the unlock returned,
		// allowing direct access to the newly created
		// empty data object. A valid owner object must be provided.
		var cache = this.cache[ this.key( owner ) ];

		return key === undefined ?
			cache : cache[ 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,
			unlock = this.key( owner ),
			cache = this.cache[ unlock ];

		if ( key === undefined ) {
			this.cache[ unlock ] = {};

		} 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 ] ];
			}
		}
	},
	hasData: function( owner ) {
		return !jQuery.isEmptyObject(
			this.cache[ owner[ this.expando ] ] || {}
		);
	},
	discard: function( owner ) {
		if ( owner[ this.expando ] ) {
			delete this.cache[ owner[ this.expando ] ];
		}
	}
};
var data_priv = new Data();

var data_user = 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, "-$1" ).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
			data_user.set( elem, key, data );
		} else {
			data = undefined;
		}
	}
	return data;
}

jQuery.extend({
	hasData: function( elem ) {
		return data_user.hasData( elem ) || data_priv.hasData( elem );
	},

	data: function( elem, name, data ) {
		return data_user.access( elem, name, data );
	},

	removeData: function( elem, name ) {
		data_user.remove( elem, name );
	},

	// TODO: Now that all calls to _data and _removeData have been replaced
	// with direct calls to data_priv methods, these can be deprecated.
	_data: function( elem, name, data ) {
		return data_priv.access( elem, name, data );
	},

	_removeData: function( elem, name ) {
		data_priv.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 = data_user.get( elem );

				if ( elem.nodeType === 1 && !data_priv.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 ] );
							}
						}
					}
					data_priv.set( elem, "hasDataAttrs", true );
				}
			}

			return data;
		}

		// Sets multiple values
		if ( typeof key === "object" ) {
			return this.each(function() {
				data_user.set( this, key );
			});
		}

		return access( this, function( value ) {
			var data,
				camelKey = jQuery.camelCase( key );

			// 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 = data_user.get( elem, key );
				if ( data !== undefined ) {
					return data;
				}

				// Attempt to get data from the cache
				// with the key camelized
				data = data_user.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...
			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 = data_user.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...*
				data_user.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 ) {
					data_user.set( this, key, value );
				}
			});
		}, null, value, arguments.length > 1, null, true );
	},

	removeData: function( key ) {
		return this.each(function() {
			data_user.remove( this, key );
		});
	}
});


jQuery.extend({
	queue: function( elem, type, data ) {
		var queue;

		if ( elem ) {
			type = ( type || "fx" ) + "queue";
			queue = data_priv.get( elem, type );

			// Speed up dequeue by getting out quickly if this is just a lookup
			if ( data ) {
				if ( !queue || jQuery.isArray( data ) ) {
					queue = data_priv.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 data_priv.get( elem, key ) || data_priv.access( elem, key, {
			empty: jQuery.Callbacks("once memory").add(function() {
				data_priv.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 = data_priv.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 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 );
	};

var rcheckableType = (/^(?:checkbox|radio)$/i);



(function() {
	var fragment = document.createDocumentFragment(),
		div = fragment.appendChild( document.createElement( "div" ) ),
		input = document.createElement( "input" );

	// Support: 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 strundefined = typeof undefined;



support.focusinBubbles = "onfocusin" in window;


var
	rkeyEvent = /^key/,
	rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/,
	rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
	rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;

function returnTrue() {
	return true;
}

function returnFalse() {
	return false;
}

function safeActiveElement() {
	try {
		return document.activeElement;
	} catch ( err ) { }
}

/*
 * 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 = data_priv.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 !== strundefined && 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, false );
					}
				}
			}

			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 = data_priv.hasData( elem ) && data_priv.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 the expando if it's no longer used
		if ( jQuery.isEmptyObject( events ) ) {
			delete elemData.handle;
			data_priv.remove( elem, "events" );
		}
	},

	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(".") >= 0 ) {
			// 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.namespace_re = 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 = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" );
			if ( handle ) {
				handle.apply( cur, data );
			}

			// Native handler
			handle = ontype && cur[ ontype ];
			if ( handle && handle.apply && jQuery.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) &&
				jQuery.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;
	},

	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 = ( data_priv.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.namespace_re || event.namespace_re.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;

		// Find delegate handlers
		// Black-hole SVG <use> instance trees (#13180)
		// Avoid non-left-click bubbling in Firefox (#3861)
		if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {

			for ( ; cur !== this; cur = cur.parentNode || this ) {

				// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
				if ( 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 ) >= 0 :
								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 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;
				}
			}
		}
	},

	simulate: function( type, elem, event, bubble ) {
		// Piggyback on a donor event to simulate a different one.
		// Fake originalEvent to avoid donor's stopPropagation, but if the
		// simulated event prevents default then we do the same on the donor.
		var e = jQuery.extend(
			new jQuery.Event(),
			event,
			{
				type: type,
				isSimulated: true,
				originalEvent: {}
			}
		);
		if ( bubble ) {
			jQuery.event.trigger( e, null, elem );
		} else {
			jQuery.event.dispatch.call( elem, e );
		}
		if ( e.isDefaultPrevented() ) {
			event.preventDefault();
		}
	}
};

jQuery.removeEvent = function( elem, type, handle ) {
	if ( elem.removeEventListener ) {
		elem.removeEventListener( type, handle, false );
	}
};

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 = {
	isDefaultPrevented: returnFalse,
	isPropagationStopped: returnFalse,
	isImmediatePropagationStopped: returnFalse,

	preventDefault: function() {
		var e = this.originalEvent;

		this.isDefaultPrevented = returnTrue;

		if ( e && e.preventDefault ) {
			e.preventDefault();
		}
	},
	stopPropagation: function() {
		var e = this.originalEvent;

		this.isPropagationStopped = returnTrue;

		if ( e && e.stopPropagation ) {
			e.stopPropagation();
		}
	},
	stopImmediatePropagation: function() {
		var e = this.originalEvent;

		this.isImmediatePropagationStopped = returnTrue;

		if ( e && e.stopImmediatePropagation ) {
			e.stopImmediatePropagation();
		}

		this.stopPropagation();
	}
};

// Create mouseenter/leave events using mouseover/out and event-time checks
// Support: Chrome 15+
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 mousenter/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;
		}
	};
});

// Support: Firefox, Chrome, Safari
// Create "bubbling" focus and blur events
if ( !support.focusinBubbles ) {
	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 ), true );
			};

		jQuery.event.special[ fix ] = {
			setup: function() {
				var doc = this.ownerDocument || this,
					attaches = data_priv.access( doc, fix );

				if ( !attaches ) {
					doc.addEventListener( orig, handler, true );
				}
				data_priv.access( doc, fix, ( attaches || 0 ) + 1 );
			},
			teardown: function() {
				var doc = this.ownerDocument || this,
					attaches = data_priv.access( doc, fix ) - 1;

				if ( !attaches ) {
					doc.removeEventListener( orig, handler, true );
					data_priv.remove( doc, fix );

				} else {
					data_priv.access( doc, fix, attaches );
				}
			}
		};
	});
}

jQuery.fn.extend({

	on: function( types, selector, data, fn, /*INTERNAL*/ 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 ) {
				this.on( type, selector, data, types[ type ], one );
			}
			return this;
		}

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

		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 this.each( function() {
			jQuery.event.add( this, types, fn, data, selector );
		});
	},
	one: function( types, selector, data, fn ) {
		return this.on( 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 );
		});
	},

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


var
	rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
	rtagName = /<([\w:]+)/,
	rhtml = /<|&#?\w+;/,
	rnoInnerhtml = /<(?:script|style|link)/i,
	// checked="checked" or checked
	rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
	rscriptType = /^$|\/(?:java|ecma)script/i,
	rscriptTypeMasked = /^true\/(.*)/,
	rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,

	// We have to close these tags to support XHTML (#13200)
	wrapMap = {

		// Support: IE9
		option: [ 1, "<select multiple='multiple'>", "</select>" ],

		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;

// Support: 1.x compatibility
// 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;
}

// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
	var i = 0,
		l = elems.length;

	for ( ; i < l; i++ ) {
		data_priv.set(
			elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" )
		);
	}
}

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 ( data_priv.hasData( src ) ) {
		pdataOld = data_priv.access( src );
		pdataCur = data_priv.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 ( data_user.hasData( src ) ) {
		udataOld = data_user.access( src );
		udataCur = jQuery.extend( {}, udataOld );

		data_user.set( dest, udataCur );
	}
}

function getAll( context, tag ) {
	var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) :
			context.querySelectorAll ? context.querySelectorAll( tag || "*" ) :
			[];

	return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
		jQuery.merge( [ context ], ret ) :
		ret;
}

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

jQuery.extend({
	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;
	},

	buildFragment: function( elems, context, scripts, selection ) {
		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: QtWebKit, PhantomJS
					// 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 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ];

					// Descend through wrappers to the right content
					j = wrap[ 0 ];
					while ( j-- ) {
						tmp = tmp.lastChild;
					}

					// Support: QtWebKit, PhantomJS
					// 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++ ]) ) {

			// #4087 - If origin and destination elements are the same, and this is
			// that element, do not do anything
			if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
				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;
	},

	cleanData: function( elems ) {
		var data, elem, type, key,
			special = jQuery.event.special,
			i = 0;

		for ( ; (elem = elems[ i ]) !== undefined; i++ ) {
			if ( jQuery.acceptData( elem ) ) {
				key = elem[ data_priv.expando ];

				if ( key && (data = data_priv.cache[ key ]) ) {
					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 );
							}
						}
					}
					if ( data_priv.cache[ key ] ) {
						// Discard any remaining `private` data
						delete data_priv.cache[ key ];
					}
				}
			}
			// Discard any remaining `user` data
			delete data_user.cache[ elem[ data_user.expando ] ];
		}
	}
});

jQuery.fn.extend({
	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 this.domManip( arguments, function( elem ) {
			if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
				var target = manipulationTarget( this, elem );
				target.appendChild( elem );
			}
		});
	},

	prepend: function() {
		return this.domManip( 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 this.domManip( arguments, function( elem ) {
			if ( this.parentNode ) {
				this.parentNode.insertBefore( elem, this );
			}
		});
	},

	after: function() {
		return this.domManip( arguments, function( elem ) {
			if ( this.parentNode ) {
				this.parentNode.insertBefore( elem, this.nextSibling );
			}
		});
	},

	remove: function( selector, keepData /* Internal Use Only */ ) {
		var elem,
			elems = selector ? jQuery.filter( selector, this ) : this,
			i = 0;

		for ( ; (elem = elems[i]) != null; i++ ) {
			if ( !keepData && elem.nodeType === 1 ) {
				jQuery.cleanData( getAll( elem ) );
			}

			if ( elem.parentNode ) {
				if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
					setGlobalEval( getAll( elem, "script" ) );
				}
				elem.parentNode.removeChild( elem );
			}
		}

		return this;
	},

	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 = value.replace( rxhtmlTag, "<$1></$2>" );

				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 arg = arguments[ 0 ];

		// Make the changes, replacing each context element with the new content
		this.domManip( arguments, function( elem ) {
			arg = this.parentNode;

			jQuery.cleanData( getAll( this ) );

			if ( arg ) {
				arg.replaceChild( elem, this );
			}
		});

		// Force removal if there was no new content (e.g., from empty arguments)
		return arg && (arg.length || arg.nodeType) ? this : this.remove();
	},

	detach: function( selector ) {
		return this.remove( selector, true );
	},

	domManip: function( args, callback ) {

		// Flatten any nested arrays
		args = concat.apply( [], args );

		var fragment, first, scripts, hasScripts, node, doc,
			i = 0,
			l = this.length,
			set = this,
			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 this.each(function( index ) {
				var self = set.eq( index );
				if ( isFunction ) {
					args[ 0 ] = value.call( this, index, self.html() );
				}
				self.domManip( args, callback );
			});
		}

		if ( l ) {
			fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this );
			first = fragment.firstChild;

			if ( fragment.childNodes.length === 1 ) {
				fragment = first;
			}

			if ( first ) {
				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: QtWebKit
							// jQuery.merge because push.apply(_, arraylike) throws
							jQuery.merge( scripts, getAll( node, "script" ) );
						}
					}

					callback.call( this[ 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 || "" ) &&
							!data_priv.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 this;
	}
});

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

/**
 * 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 style,
		elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),

		// getDefaultComputedStyle might be reliably used only on attached element
		display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ?

			// Use of this method is a temporary fix (more like optimization) until something better comes along,
			// since it was removed from specification and supported only in FF
			style.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"
		if ( elem.ownerDocument.defaultView.opener ) {
			return elem.ownerDocument.defaultView.getComputedStyle( elem, null );
		}

		return window.getComputedStyle( elem, null );
	};



function curCSS( elem, name, computed ) {
	var width, minWidth, maxWidth, ret,
		style = elem.style;

	computed = computed || getStyles( elem );

	// Support: IE9
	// getPropertyValue is only needed for .css('filter') (#12537)
	if ( computed ) {
		ret = computed.getPropertyValue( name ) || computed[ name ];
	}

	if ( computed ) {

		if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
			ret = jQuery.style( elem, name );
		}

		// Support: iOS < 6
		// A tribute to the "awesome hack by Dean Edwards"
		// iOS < 6 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
		// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
		if ( 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: IE
		// 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 );
		}
	};
}


(function() {
	var pixelPositionVal, boxSizingReliableVal,
		docElem = document.documentElement,
		container = document.createElement( "div" ),
		div = document.createElement( "div" );

	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:0;height:0;top:0;left:-9999px;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 computePixelPositionAndBoxSizingReliable() {
		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;display:block;margin-top:1%;top:1%;" +
			"border:1px;padding:1px;width:4px;position:absolute";
		div.innerHTML = "";
		docElem.appendChild( container );

		var divStyle = window.getComputedStyle( div, null );
		pixelPositionVal = divStyle.top !== "1%";
		boxSizingReliableVal = divStyle.width === "4px";

		docElem.removeChild( container );
	}

	// Support: node.js jsdom
	// Don't assume that getComputedStyle is a property of the global object
	if ( window.getComputedStyle ) {
		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.
				computePixelPositionAndBoxSizingReliable();
				return pixelPositionVal;
			},
			boxSizingReliable: function() {
				if ( boxSizingReliableVal == null ) {
					computePixelPositionAndBoxSizingReliable();
				}
				return boxSizingReliableVal;
			},
			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: Firefox<29, Android 2.3
					// Vendor-prefix box-sizing
					"-webkit-box-sizing:content-box;-moz-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";
				docElem.appendChild( container );

				ret = !parseFloat( window.getComputedStyle( marginDiv, null ).marginRight );

				docElem.removeChild( container );
				div.removeChild( marginDiv );

				return ret;
			}
		});
	}
})();


// A method for quickly swapping in/out CSS properties to get correct calculations.
jQuery.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
	// 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]).+)/,
	rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ),
	rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ),

	cssShow = { position: "absolute", visibility: "hidden", display: "block" },
	cssNormalTransform = {
		letterSpacing: "0",
		fontWeight: "400"
	},

	cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];

// Return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {

	// Shortcut for names that are not vendor prefixed
	if ( name in style ) {
		return name;
	}

	// Check for vendor prefixed names
	var capName = name[0].toUpperCase() + name.slice(1),
		origName = name,
		i = cssPrefixes.length;

	while ( i-- ) {
		name = cssPrefixes[ i ] + capName;
		if ( name in style ) {
			return name;
		}
	}

	return origName;
}

function setPositiveNumber( elem, value, subtract ) {
	var matches = rnumsplit.exec( value );
	return matches ?
		// Guard against undefined "subtract", e.g., when used as in cssHooks
		Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "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 ] = data_priv.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 ] = data_priv.access( elem, "olddisplay", defaultDisplay(elem.nodeName) );
			}
		} else {
			hidden = isHidden( elem );

			if ( display !== "none" || !hidden ) {
				data_priv.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: {
		"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( style, 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 = rrelNum.exec( value )) ) {
				value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
				// 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, add 'px' to the (except for certain CSS properties)
			if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
				value += "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( elem.style, 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 || jQuery.isNumeric( 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 ?
					jQuery.swap( elem, cssShow, function() {
						return getWidthOrHeight( elem, name, extra );
					}) :
					getWidthOrHeight( elem, name, extra );
			}
		},

		set: function( elem, value, extra ) {
			var styles = extra && getStyles( elem );
			return setPositiveNumber( elem, value, extra ?
				augmentWidthOrHeight(
					elem,
					name,
					extra,
					jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
					styles
				) : 0
			);
		}
	};
});

// Support: Android 2.3
jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight,
	function( elem, computed ) {
		if ( computed ) {
			return jQuery.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 || "swing";
		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;

			if ( tween.elem[ tween.prop ] != null &&
				(!tween.elem.style || 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.style && ( 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;
	}
};

jQuery.fx = Tween.prototype.init;

// Back Compat <1.8 extension point
jQuery.fx.step = {};




var
	fxNow, timerId,
	rfxtypes = /^(?:toggle|show|hide)$/,
	rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ),
	rrun = /queueHooks$/,
	animationPrefilters = [ defaultPrefilter ],
	tweeners = {
		"*": [ function( prop, value ) {
			var tween = this.createTween( prop, value ),
				target = tween.cur(),
				parts = rfxnum.exec( value ),
				unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),

				// Starting value computation is required for potential unit mismatches
				start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) &&
					rfxnum.exec( jQuery.css( tween.elem, prop ) ),
				scale = 1,
				maxIterations = 20;

			if ( start && start[ 3 ] !== unit ) {
				// Trust units reported by jQuery.css
				unit = unit || start[ 3 ];

				// Make sure we update the tween properties later on
				parts = parts || [];

				// Iteratively approximate from a nonzero starting point
				start = +target || 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
					start = start / scale;
					jQuery.style( tween.elem, prop, start + 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 = tween.cur() / target) && scale !== 1 && --maxIterations );
			}

			// Update tween properties
			if ( parts ) {
				start = tween.start = +start || +target || 0;
				tween.unit = unit;
				// If a +=/-= token was provided, we're doing a relative animation
				tween.end = parts[ 1 ] ?
					start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
					+parts[ 2 ];
			}

			return tween;
		} ]
	};

// Animations created synchronously will run synchronously
function createFxNow() {
	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 = ( tweeners[ prop ] || [] ).concat( 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 = data_priv.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" ?
			data_priv.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 = data_priv.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;

			data_priv.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 = animationPrefilters.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: {} }, 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.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 = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
		if ( 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, {

	tweener: function( props, callback ) {
		if ( jQuery.isFunction( props ) ) {
			callback = props;
			props = [ "*" ];
		} else {
			props = props.split(" ");
		}

		var prop,
			index = 0,
			length = props.length;

		for ( ; index < length ; index++ ) {
			prop = props[ index ];
			tweeners[ prop ] = tweeners[ prop ] || [];
			tweeners[ prop ].unshift( callback );
		}
	},

	prefilter: function( callback, prepend ) {
		if ( prepend ) {
			animationPrefilters.unshift( callback );
		} else {
			animationPrefilters.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 || data_priv.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 = data_priv.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 = data_priv.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 = setInterval( jQuery.fx.tick, jQuery.fx.interval );
	}
};

jQuery.fx.stop = function() {
	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://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 = setTimeout( next, time );
		hooks.stop = function() {
			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 nodeHook, 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 hooks, ret,
			nType = elem.nodeType;

		// don't get/set attributes on text, comment and attribute nodes
		if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
			return;
		}

		// Fallback to prop when attributes are not supported
		if ( typeof elem.getAttribute === strundefined ) {
			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 : nodeHook );
		}

		if ( value !== undefined ) {

			if ( value === null ) {
				jQuery.removeAttr( elem, name );

			} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
				return ret;

			} else {
				elem.setAttribute( name, value + "" );
				return value;
			}

		} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
			return ret;

		} else {
			ret = jQuery.find.attr( elem, name );

			// Non-existent attributes return null, we normalize to undefined
			return ret == null ?
				undefined :
				ret;
		}
	},

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

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

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

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({
	propFix: {
		"for": "htmlFor",
		"class": "className"
	},

	prop: function( elem, name, value ) {
		var ret, hooks, notxml,
			nType = elem.nodeType;

		// Don't get/set properties on text, comment and attribute nodes
		if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
			return;
		}

		notxml = nType !== 1 || !jQuery.isXMLDoc( elem );

		if ( notxml ) {
			// Fix name and attach hooks
			name = jQuery.propFix[ name ] || name;
			hooks = jQuery.propHooks[ name ];
		}

		if ( value !== undefined ) {
			return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
				ret :
				( elem[ name ] = value );

		} else {
			return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
				ret :
				elem[ name ];
		}
	},

	propHooks: {
		tabIndex: {
			get: function( elem ) {
				return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ?
					elem.tabIndex :
					-1;
			}
		}
	}
});

if ( !support.optSelected ) {
	jQuery.propHooks.selected = {
		get: function( elem ) {
			var parent = elem.parentNode;
			if ( parent && parent.parentNode ) {
				parent.parentNode.selectedIndex;
			}
			return null;
		}
	};
}

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;

jQuery.fn.extend({
	addClass: function( value ) {
		var classes, elem, cur, clazz, j, finalValue,
			proceed = typeof value === "string" && value,
			i = 0,
			len = this.length;

		if ( jQuery.isFunction( value ) ) {
			return this.each(function( j ) {
				jQuery( this ).addClass( value.call( this, j, this.className ) );
			});
		}

		if ( proceed ) {
			// The disjunction here is for better compressibility (see removeClass)
			classes = ( value || "" ).match( rnotwhite ) || [];

			for ( ; i < len; i++ ) {
				elem = this[ i ];
				cur = elem.nodeType === 1 && ( elem.className ?
					( " " + elem.className + " " ).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 ( elem.className !== finalValue ) {
						elem.className = finalValue;
					}
				}
			}
		}

		return this;
	},

	removeClass: function( value ) {
		var classes, elem, cur, clazz, j, finalValue,
			proceed = arguments.length === 0 || typeof value === "string" && value,
			i = 0,
			len = this.length;

		if ( jQuery.isFunction( value ) ) {
			return this.each(function( j ) {
				jQuery( this ).removeClass( value.call( this, j, this.className ) );
			});
		}
		if ( proceed ) {
			classes = ( value || "" ).match( rnotwhite ) || [];

			for ( ; i < len; i++ ) {
				elem = this[ i ];
				// This expression is here for better compressibility (see addClass)
				cur = elem.nodeType === 1 && ( elem.className ?
					( " " + elem.className + " " ).replace( rclass, " " ) :
					""
				);

				if ( cur ) {
					j = 0;
					while ( (clazz = classes[j++]) ) {
						// Remove *all* instances
						while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
							cur = cur.replace( " " + clazz + " ", " " );
						}
					}

					// Only assign if different to avoid unneeded rendering.
					finalValue = value ? jQuery.trim( cur ) : "";
					if ( elem.className !== finalValue ) {
						elem.className = 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, this.className, stateVal), stateVal );
			});
		}

		return this.each(function() {
			if ( type === "string" ) {
				// Toggle individual class names
				var className,
					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 ( type === strundefined || type === "boolean" ) {
				if ( this.className ) {
					// store className if set
					data_priv.set( this, "__className__", this.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.
				this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || "";
			}
		});
	},

	hasClass: function( selector ) {
		var className = " " + selector + " ",
			i = 0,
			l = this.length;
		for ( ; i < l; i++ ) {
			if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
				return true;
			}
		}

		return false;
	}
});




var rreturn = /\r/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)
					jQuery.trim( jQuery.text( elem ) );
			}
		},
		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 ];

					// IE6-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( option.value, values ) >= 0) ) {
						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 ) >= 0 );
			}
		}
	};
	if ( !support.checkOn ) {
		jQuery.valHooks[ this ].get = function( elem ) {
			return elem.getAttribute("value") === null ? "on" : elem.value;
		};
	}
});




// Return jQuery for attributes-only inclusion


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

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


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, tmp;
	if ( !data || typeof data !== "string" ) {
		return null;
	}

	// Support: IE9
	try {
		tmp = new DOMParser();
		xml = tmp.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 = /^\/\//,
	rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,

	/* 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( "*" ),

	// Document location
	ajaxLocation = window.location.href,

	// Segment location into parts
	ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];

// 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: ajaxLocation,
		type: "GET",
		isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
		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: /xml/,
			html: /html/,
			json: /json/
		},

		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,
			// Cross-domain detection vars
			parts,
			// 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 || ajaxLocation ) + "" ).replace( rhash, "" )
			.replace( rprotocol, ajaxLocParts[ 1 ] + "//" );

		// 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 we have a protocol:host:port mismatch
		if ( s.crossDomain == null ) {
			parts = rurl.exec( s.url.toLowerCase() );
			s.crossDomain = !!( parts &&
				( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
					( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !==
						( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) )
			);
		}

		// 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 ] );
			}
			// Timeout
			if ( s.async && s.timeout > 0 ) {
				timeoutTimer = 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 ) {
				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;
		}

		return jQuery.ajax({
			url: url,
			type: method,
			dataType: type,
			data: data,
			success: callback
		});
	};
});


jQuery._evalUrl = function( url ) {
	return jQuery.ajax({
		url: url,
		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 ) {
	// Support: Opera <= 12.12
	// Opera reports offsetWidths and offsetHeights less than zero on some elements
	return elem.offsetWidth <= 0 && elem.offsetHeight <= 0;
};
jQuery.expr.filters.visible = function( elem ) {
	return !jQuery.expr.filters.hidden( elem );
};




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" ? 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 XMLHttpRequest();
	} catch( e ) {}
};

var xhrId = 0,
	xhrCallbacks = {},
	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: IE9
// Open requests must be manually aborted on unload (#5280)
// See https://support.microsoft.com/kb/2856746 for more info
if ( window.attachEvent ) {
	window.attachEvent( "onunload", function() {
		for ( var key in xhrCallbacks ) {
			xhrCallbacks[ key ]();
		}
	});
}

support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
support.ajax = xhrSupported = !!xhrSupported;

jQuery.ajaxTransport(function( options ) {
	var callback;

	// Cross domain only allowed if supported through XMLHttpRequest
	if ( support.cors || xhrSupported && !options.crossDomain ) {
		return {
			send: function( headers, complete ) {
				var i,
					xhr = options.xhr(),
					id = ++xhrId;

				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 ) {
							delete xhrCallbacks[ id ];
							callback = xhr.onload = xhr.onerror = null;

							if ( type === "abort" ) {
								xhr.abort();
							} else if ( type === "error" ) {
								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
									// Accessing binary-data responseText throws an exception
									// (#11426)
									typeof xhr.responseText === "string" ? {
										text: xhr.responseText
									} : undefined,
									xhr.getAllResponseHeaders()
								);
							}
						}
					};
				};

				// Listen to events
				xhr.onload = callback();
				xhr.onerror = callback("error");

				// Create the abort callback
				callback = xhrCallbacks[ id ] = 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: /(?:java|ecma)script/
	},
	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({
					async: true,
					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 );
						}
					}
				);
				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") && 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() {
			// Restore preexisting value
			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";
	}
});




// data: 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 = jQuery.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 >= 0 ) {
		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
			type: type,
			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 );

		}).complete( callback && function( jqXHR, status ) {
			self.each( callback, 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;
};




var docElem = window.document.documentElement;

/**
 * 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 ) ) {
			options = options.call( elem, i, 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;
		}

		// Support: BlackBerry 5, iOS 3 (original iPhone)
		// If we don't have gBCR, just use 0,0 rather than error
		if ( typeof elem.getBoundingClientRect !== strundefined ) {
			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 )
		};
	},

	offsetParent: function() {
		return this.map(function() {
			var offsetParent = this.offsetParent || docElem;

			while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) {
				offsetParent = offsetParent.offsetParent;
			}

			return offsetParent || docElem;
		});
	}
});

// 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 : window.pageXOffset,
					top ? val : window.pageYOffset
				);

			} else {
				elem[ method ] = val;
			}
		}, method, val, arguments.length, null );
	};
});

// Support: Safari<7+, Chrome<37+
// 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 );
		};
	});
});


// The number of elements contained in the matched element set
jQuery.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 ( typeof noGlobal === strundefined ) {
	window.jQuery = window.$ = jQuery;
}




return jQuery;

}));

},{}],"jsnlog":[function(require,module,exports){
/// <reference path="Definitions/jsnlog_interfaces.d.ts"/>
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 __();
};
function JL(loggerName) {
    // If name is empty, return the root logger
    if (!loggerName) {
        return JL.__;
    }

    // Implements Array.reduce. JSNLog supports IE8+ and reduce is not supported in that browser.
    // Same interface as the standard reduce, except that
    if (!Array.prototype.reduce) {
        Array.prototype.reduce = function (callback, initialValue) {
            var previousValue = initialValue;
            for (var i = 0; i < this.length; i++) {
                previousValue = callback(previousValue, this[i], i, this);
            }

            return previousValue;
        };
    }

    var accumulatedLoggerName = '';
    var logger = ('.' + loggerName).split('.').reduce(function (prev, curr, idx, arr) {
        // if loggername is a.b.c, than currentLogger will be set to the loggers
        // root   (prev: JL, curr: '')
        // a      (prev: JL.__, curr: 'a')
        // a.b    (prev: JL.__.__a, curr: 'b')
        // a.b.c  (prev: JL.__.__a.__a.b, curr: 'c')
        // Note that when a new logger name is encountered (such as 'a.b.c'),
        // a new logger object is created and added as a property to the parent ('a.b').
        // The root logger is added as a property of the JL object itself.
        // It is essential that the name of the property containing the child logger
        // contains the full 'path' name of the child logger ('a.b.c') instead of
        // just the bit after the last period ('c').
        // This is because the parent inherits properties from its ancestors.
        // So if the root has a child logger 'c' (stored in a property 'c' of the root logger),
        // then logger 'a.b' has that same property 'c' through inheritance.
        // The names of the logger properties start with __, so the root logger
        // (which has name ''), has a nice property name '__'.
        // accumulatedLoggerName evaluates false ('' is falsy) in first iteration when prev is the root logger.
        // accumulatedLoggerName will be the logger name corresponding with the logger in currentLogger.
        // Keep in mind that the currentLogger may not be defined yet, so can't get the name from
        // the currentLogger object itself.
        if (accumulatedLoggerName) {
            accumulatedLoggerName += '.' + curr;
        } else {
            accumulatedLoggerName = curr;
        }

        var currentLogger = prev['__' + accumulatedLoggerName];

        // If the currentLogger (or the actual logger being sought) does not yet exist,
        // create it now.
        if (currentLogger === undefined) {
            // Set the prototype of the Logger constructor function to the parent of the logger
            // to be created. This way, __proto of the new logger object will point at the parent.
            // When logger.level is evaluated and is not present, the JavaScript runtime will
            // walk down the prototype chain to find the first ancestor with a level property.
            //
            // Note that prev at this point refers to the parent logger.
            JL.Logger.prototype = prev;

            currentLogger = new JL.Logger(accumulatedLoggerName);
            prev['__' + accumulatedLoggerName] = currentLogger;
        }

        return currentLogger;
    }, JL.__);

    return logger;
}

var JL;
(function (JL) {
    JL.enabled;
    JL.maxMessages;
    JL.defaultAjaxUrl;
    JL.clientIP;
    JL.defaultBeforeSend;

    // Initialise requestId to empty string. If you don't do this and the user
    // does not set it via setOptions, then the JSNLog-RequestId header will
    // have value "undefined", which doesn't look good in a log.
    //
    // Note that you always want to send a requestId as part of log requests,
    // otherwise the server side component doesn't know this is a log request
    // and may create a new request id for the log request, causing confusion
    // in the log.
    JL.requestId = '';

    /**
    Copies the value of a property from one object to the other.
    This is used to copy property values as part of setOption for loggers and appenders.
    
    Because loggers inherit property values from their parents, it is important never to
    create a property on a logger if the intent is to inherit from the parent.
    
    Copying rules:
    1) if the from property is undefined (for example, not mentioned in a JSON object), the
    to property is not affected at all.
    2) if the from property is null, the to property is deleted (so the logger will inherit from
    its parent).
    3) Otherwise, the from property is copied to the to property.
    */
    function copyProperty(propertyName, from, to) {
        if (from[propertyName] === undefined) {
            return;
        }
        if (from[propertyName] === null) {
            delete to[propertyName];
            return;
        }
        to[propertyName] = from[propertyName];
    }

    /**
    Returns true if a log should go ahead.
    Does not check level.
    
    @param filters
    Filters that determine whether a log can go ahead.
    */
    function allow(filters) {
        // If enabled is not null or undefined, then if it is false, then return false
        // Note that undefined==null (!)
        if (!(JL.enabled == null)) {
            if (!JL.enabled) {
                return false;
            }
        }

        // If maxMessages is not null or undefined, then if it is 0, then return false.
        // Note that maxMessages contains number of messages that are still allowed to send.
        // It is decremented each time messages are sent. It can be negative when batch size > 1.
        // Note that undefined==null (!)
        if (!(JL.maxMessages == null)) {
            if (JL.maxMessages < 1) {
                return false;
            }
        }

        try  {
            if (filters.userAgentRegex) {
                if (!new RegExp(filters.userAgentRegex).test(navigator.userAgent)) {
                    return false;
                }
            }
        } catch (e) {
        }

        try  {
            if (filters.ipRegex && JL.clientIP) {
                if (!new RegExp(filters.ipRegex).test(JL.clientIP)) {
                    return false;
                }
            }
        } catch (e) {
        }

        return true;
    }

    /**
    Returns true if a log should go ahead, based on the message.
    
    @param filters
    Filters that determine whether a log can go ahead.
    
    @param message
    Message to be logged.
    */
    function allowMessage(filters, message) {
        try  {
            if (filters.disallow) {
                if (new RegExp(filters.disallow).test(message)) {
                    return false;
                }
            }
        } catch (e) {
        }

        return true;
    }

    // If logObject is a function, the function is evaluated (without parameters)
    // and the result returned.
    // Otherwise, logObject itself is returned.
    function stringifyLogObjectFunction(logObject) {
        if (typeof logObject == "function") {
            if (logObject instanceof RegExp) {
                return logObject.toString();
            } else {
                return logObject();
            }
        }

        return logObject;
    }

    var StringifiedLogObject = (function () {
        // * msg -
        //      if the logObject is a scalar (after possible function evaluation), this is set to
        //      string representing the scalar. Otherwise it is left undefined.
        // * meta -
        //      if the logObject is an object (after possible function evaluation), this is set to
        //      that object. Otherwise it is left undefined.
        // * finalString -
        //      This is set to the string representation of logObject (after possible function evaluation),
        //      regardless of whether it is an scalar or an object. An object is stringified to a JSON string.
        //      Note that you can't call this field "final", because as some point this was a reserved
        //      JavaScript keyword and using final trips up some minifiers.
        function StringifiedLogObject(msg, meta, finalString) {
            this.msg = msg;
            this.meta = meta;
            this.finalString = finalString;
        }
        return StringifiedLogObject;
    })();

    // Takes a logObject, which can be
    // * a scalar
    // * an object
    // * a parameterless function, which returns the scalar or object to log.
    // Returns a stringifiedLogObject
    function stringifyLogObject(logObject) {
        // Note that this works if logObject is null.
        // typeof null is object.
        // JSON.stringify(null) returns "null".
        var actualLogObject = stringifyLogObjectFunction(logObject);
        var finalString;

        switch (typeof actualLogObject) {
            case "string":
                return new StringifiedLogObject(actualLogObject, null, actualLogObject);
            case "number":
                finalString = actualLogObject.toString();
                return new StringifiedLogObject(finalString, null, finalString);
            case "boolean":
                finalString = actualLogObject.toString();
                return new StringifiedLogObject(finalString, null, finalString);
            case "undefined":
                return new StringifiedLogObject("undefined", null, "undefined");
            case "object":
                if ((actualLogObject instanceof RegExp) || (actualLogObject instanceof String) || (actualLogObject instanceof Number) || (actualLogObject instanceof Boolean)) {
                    finalString = actualLogObject.toString();
                    return new StringifiedLogObject(finalString, null, finalString);
                } else {
                    return new StringifiedLogObject(null, actualLogObject, JSON.stringify(actualLogObject));
                }
            default:
                return new StringifiedLogObject("unknown", null, "unknown");
        }
    }

    function setOptions(options) {
        copyProperty("enabled", options, this);
        copyProperty("maxMessages", options, this);
        copyProperty("defaultAjaxUrl", options, this);
        copyProperty("clientIP", options, this);
        copyProperty("requestId", options, this);
        copyProperty("defaultBeforeSend", options, this);
        return this;
    }
    JL.setOptions = setOptions;

    function getAllLevel() {
        return -2147483648;
    }
    JL.getAllLevel = getAllLevel;
    function getTraceLevel() {
        return 1000;
    }
    JL.getTraceLevel = getTraceLevel;
    function getDebugLevel() {
        return 2000;
    }
    JL.getDebugLevel = getDebugLevel;
    function getInfoLevel() {
        return 3000;
    }
    JL.getInfoLevel = getInfoLevel;
    function getWarnLevel() {
        return 4000;
    }
    JL.getWarnLevel = getWarnLevel;
    function getErrorLevel() {
        return 5000;
    }
    JL.getErrorLevel = getErrorLevel;
    function getFatalLevel() {
        return 6000;
    }
    JL.getFatalLevel = getFatalLevel;
    function getOffLevel() {
        return 2147483647;
    }
    JL.getOffLevel = getOffLevel;

    function levelToString(level) {
        if (level <= 1000) {
            return "trace";
        }
        if (level <= 2000) {
            return "debug";
        }
        if (level <= 3000) {
            return "info";
        }
        if (level <= 4000) {
            return "warn";
        }
        if (level <= 5000) {
            return "error";
        }
        return "fatal";
    }

    // ---------------------
    var Exception = (function () {
        // data replaces message. It takes not just strings, but also objects and functions, just like the log function.
        // internally, the string representation is stored in the message property (inherited from Error)
        //
        // inner: inner exception. Can be null or undefined.
        function Exception(data, inner) {
            this.inner = inner;
            this.name = "JL.Exception";
            this.message = stringifyLogObject(data).finalString;
        }
        return Exception;
    })();
    JL.Exception = Exception;

    // Derive Exception from Error (a Host object), so browsers
    // are more likely to produce a stack trace for it in their console.
    //
    // Note that instanceof against an object created with this constructor
    // will return true in these cases:
    // <object> instanceof JL.Exception);
    // <object> instanceof Error);
    Exception.prototype = new Error();

    // ---------------------
    var LogItem = (function () {
        // l: level
        // m: message
        // n: logger name
        // t (timeStamp) is number of milliseconds since 1 January 1970 00:00:00 UTC
        //
        // Keeping the property names really short, because they will be sent in the
        // JSON payload to the server.
        function LogItem(l, m, n, t) {
            this.l = l;
            this.m = m;
            this.n = n;
            this.t = t;
        }
        return LogItem;
    })();
    JL.LogItem = LogItem;

    // ---------------------
    var Appender = (function () {
        // sendLogItems takes an array of log items. It will be called when
        // the appender has items to process (such as, send to the server).
        // Note that after sendLogItems returns, the appender may truncate
        // the LogItem array, so the function has to copy the content of the array
        // in some fashion (eg. serialize) before returning.
        function Appender(appenderName, sendLogItems) {
            this.appenderName = appenderName;
            this.sendLogItems = sendLogItems;
            this.level = JL.getTraceLevel();
            // set to super high level, so if user increases level, level is unlikely to get
            // above sendWithBufferLevel
            this.sendWithBufferLevel = 2147483647;
            this.storeInBufferLevel = -2147483648;
            this.bufferSize = 0;
            this.batchSize = 1;
            // Holds all log items with levels higher than storeInBufferLevel
            // but lower than level. These items may never be sent.
            this.buffer = [];
            // Holds all items that we do want to send, until we have a full
            // batch (as determined by batchSize).
            this.batchBuffer = [];
        }
        Appender.prototype.setOptions = function (options) {
            copyProperty("level", options, this);
            copyProperty("ipRegex", options, this);
            copyProperty("userAgentRegex", options, this);
            copyProperty("disallow", options, this);
            copyProperty("sendWithBufferLevel", options, this);
            copyProperty("storeInBufferLevel", options, this);
            copyProperty("bufferSize", options, this);
            copyProperty("batchSize", options, this);

            if (this.bufferSize < this.buffer.length) {
                this.buffer.length = this.bufferSize;
            }

            return this;
        };

        /**
        Called by a logger to log a log item.
        If in response to this call one or more log items need to be processed
        (eg., sent to the server), this method calls this.sendLogItems
        with an array with all items to be processed.
        
        Note that the name and parameters of this function must match those of the log function of
        a Winston transport object, so that users can use these transports as appenders.
        That is why there are many parameters that are not actually used by this function.
        
        level - string with the level ("trace", "debug", etc.) Only used by Winston transports.
        msg - human readable message. Undefined if the log item is an object. Only used by Winston transports.
        meta - log object. Always defined, because at least it contains the logger name. Only used by Winston transports.
        callback - function that is called when the log item has been logged. Only used by Winston transports.
        levelNbr - level as a number. Not used by Winston transports.
        message - log item. If the user logged an object, this is the JSON string.  Not used by Winston transports.
        loggerName: name of the logger.  Not used by Winston transports.
        */
        Appender.prototype.log = function (level, msg, meta, callback, levelNbr, message, loggerName) {
            var logItem;

            if (!allow(this)) {
                return;
            }
            if (!allowMessage(this, message)) {
                return;
            }

            if (levelNbr < this.storeInBufferLevel) {
                // Ignore the log item completely
                return;
            }

            logItem = new LogItem(levelNbr, message, loggerName, (new Date).getTime());

            if (levelNbr < this.level) {
                // Store in the hold buffer. Do not send.
                if (this.bufferSize > 0) {
                    this.buffer.push(logItem);

                    // If we exceeded max buffer size, remove oldest item
                    if (this.buffer.length > this.bufferSize) {
                        this.buffer.shift();
                    }
                }

                return;
            }

            if (levelNbr < this.sendWithBufferLevel) {
                // Want to send the item, but not the contents of the buffer
                this.batchBuffer.push(logItem);
            } else {
                // Want to send both the item and the contents of the buffer.
                // Send contents of buffer first, because logically they happened first.
                if (this.buffer.length) {
                    this.batchBuffer = this.batchBuffer.concat(this.buffer);
                    this.buffer.length = 0;
                }
                this.batchBuffer.push(logItem);
            }

            if (this.batchBuffer.length >= this.batchSize) {
                this.sendBatch();
                return;
            }
        };

        // Processes the batch buffer
        Appender.prototype.sendBatch = function () {
            if (this.batchBuffer.length == 0) {
                return;
            }

            if (!(JL.maxMessages == null)) {
                if (JL.maxMessages < 1) {
                    return;
                }
            }

            // If maxMessages is not null or undefined, then decrease it by the batch size.
            // This can result in a negative maxMessages.
            // Note that undefined==null (!)
            if (!(JL.maxMessages == null)) {
                JL.maxMessages -= this.batchBuffer.length;
            }

            this.sendLogItems(this.batchBuffer);
            this.batchBuffer.length = 0;
        };
        return Appender;
    })();
    JL.Appender = Appender;

    // ---------------------
    var AjaxAppender = (function (_super) {
        __extends(AjaxAppender, _super);
        function AjaxAppender(appenderName) {
            _super.call(this, appenderName, AjaxAppender.prototype.sendLogItemsAjax);
        }
        AjaxAppender.prototype.setOptions = function (options) {
            copyProperty("url", options, this);
            copyProperty("beforeSend", options, this);
            _super.prototype.setOptions.call(this, options);
            return this;
        };

        AjaxAppender.prototype.sendLogItemsAjax = function (logItems) {
            try  {
                // Only determine the url right before you send a log request.
                // Do not set the url when constructing the appender.
                //
                // This is because the server side component sets defaultAjaxUrl
                // in a call to setOptions, AFTER the JL object and the default appender
                // have been created.
                var ajaxUrl = "/jsnlog.logger";

                // This evaluates to true if defaultAjaxUrl is null or undefined
                if (!(JL.defaultAjaxUrl == null)) {
                    ajaxUrl = JL.defaultAjaxUrl;
                }

                if (this.url) {
                    ajaxUrl = this.url;
                }

                var json = JSON.stringify({
                    r: JL.requestId,
                    lg: logItems
                });

                // Send the json to the server.
                // Note that there is no event handling here. If the send is not
                // successful, nothing can be done about it.
                var xhr = this.getXhr(ajaxUrl);

                // call beforeSend callback
                // first try the callback on the appender
                // then the global defaultBeforeSend callback
                if (typeof this.beforeSend === 'function') {
                    this.beforeSend(xhr);
                } else if (typeof JL.defaultBeforeSend === 'function') {
                    JL.defaultBeforeSend(xhr);
                }

                xhr.send(json);
            } catch (e) {
            }
        };

        // Creates the Xhr object to use to send the log request.
        // Sets out to create an Xhr object that can be used for CORS.
        // However, if there seems to be no CORS support on the browser,
        // returns a non-CORS capable Xhr.
        AjaxAppender.prototype.getXhr = function (ajaxUrl) {
            var xhr = new XMLHttpRequest();

            // Check whether this xhr is CORS capable by checking whether it has
            // withCredentials.
            // "withCredentials" only exists on XMLHTTPRequest2 objects.
            if (!("withCredentials" in xhr)) {
                // Just found that no XMLHttpRequest2 available.
                // Check if XDomainRequest is available.
                // This only exists in IE, and is IE's way of making CORS requests.
                if (typeof XDomainRequest != "undefined") {
                    // Note that here we're not setting request headers on the XDomainRequest
                    // object. This is because this object doesn't let you do that:
                    // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
                    // This means that for IE8 and IE9, CORS logging requests do not carry request ids.
                    var xdr = new XDomainRequest();
                    xdr.open('POST', ajaxUrl);
                    return xdr;
                }
            }

            // At this point, we're going with XMLHttpRequest, whether it is CORS capable or not.
            // If it is not CORS capable, at least will handle the non-CORS requests.
            xhr.open('POST', ajaxUrl);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.setRequestHeader('JSNLog-RequestId', JL.requestId);

            return xhr;
        };
        return AjaxAppender;
    })(Appender);
    JL.AjaxAppender = AjaxAppender;

    // ---------------------
    var ConsoleAppender = (function (_super) {
        __extends(ConsoleAppender, _super);
        function ConsoleAppender(appenderName) {
            _super.call(this, appenderName, ConsoleAppender.prototype.sendLogItemsConsole);
        }
        ConsoleAppender.prototype.clog = function (logEntry) {
            console.log(logEntry);
        };

        ConsoleAppender.prototype.cerror = function (logEntry) {
            if (console.error) {
                console.error(logEntry);
            } else {
                this.clog(logEntry);
            }
        };

        ConsoleAppender.prototype.cwarn = function (logEntry) {
            if (console.warn) {
                console.warn(logEntry);
            } else {
                this.clog(logEntry);
            }
        };

        ConsoleAppender.prototype.cinfo = function (logEntry) {
            if (console.info) {
                console.info(logEntry);
            } else {
                this.clog(logEntry);
            }
        };

        // IE11 has a console.debug function. But its console doesn't have
        // the option to show/hide debug messages (the same way Chrome and FF do),
        // even though it does have such buttons for Error, Warn, Info.
        //
        // For now, this means that debug messages can not be hidden on IE.
        // Live with this, seeing that it works fine on FF and Chrome, which
        // will be much more popular with developers.
        ConsoleAppender.prototype.cdebug = function (logEntry) {
            if (console.debug) {
                console.debug(logEntry);
            } else {
                this.cinfo(logEntry);
            }
        };

        ConsoleAppender.prototype.sendLogItemsConsole = function (logItems) {
            try  {
                if (!console) {
                    return;
                }

                var i;
                for (i = 0; i < logItems.length; ++i) {
                    var li = logItems[i];
                    var msg = li.n + ": " + li.m;

                    // Only log the timestamp if we're on the server
                    // (window is undefined). On the browser, the user
                    // sees the log entry probably immediately, so in that case
                    // the timestamp is clutter.
                    if (typeof window === 'undefined') {
                        msg = new Date(li.t) + " | " + msg;
                    }

                    if (li.l <= JL.getDebugLevel()) {
                        this.cdebug(msg);
                    } else if (li.l <= JL.getInfoLevel()) {
                        this.cinfo(msg);
                    } else if (li.l <= JL.getWarnLevel()) {
                        this.cwarn(msg);
                    } else {
                        this.cerror(msg);
                    }
                }
            } catch (e) {
            }
        };
        return ConsoleAppender;
    })(Appender);
    JL.ConsoleAppender = ConsoleAppender;

    // --------------------
    var Logger = (function () {
        function Logger(loggerName) {
            this.loggerName = loggerName;
            // Create seenRexes, otherwise this logger will use the seenRexes
            // of its parent via the prototype chain.
            this.seenRegexes = [];
        }
        Logger.prototype.setOptions = function (options) {
            copyProperty("level", options, this);
            copyProperty("userAgentRegex", options, this);
            copyProperty("disallow", options, this);
            copyProperty("ipRegex", options, this);
            copyProperty("appenders", options, this);
            copyProperty("onceOnly", options, this);

            // Reset seenRegexes, in case onceOnly has been changed.
            this.seenRegexes = [];

            return this;
        };

        // Turns an exception into an object that can be sent to the server.
        Logger.prototype.buildExceptionObject = function (e) {
            var excObject = {};

            if (e.stack) {
                excObject.stack = e.stack;
            } else {
                excObject.e = e;
            }
            if (e.message) {
                excObject.message = e.message;
            }
            if (e.name) {
                excObject.name = e.name;
            }
            if (e.data) {
                excObject.data = e.data;
            }
            if (e.inner) {
                excObject.inner = this.buildExceptionObject(e.inner);
            }

            return excObject;
        };

        // Logs a log item.
        // Parameter e contains an exception (or null or undefined).
        //
        // Reason that processing exceptions is done at this low level is that
        // 1) no need to spend the cpu cycles if the logger is switched off
        // 2) fatalException takes both a logObject and an exception, and the logObject
        //    may be a function that should only be executed if the logger is switched on.
        //
        // If an exception is passed in, the contents of logObject is attached to the exception
        // object in a new property logData.
        // The resulting exception object is than worked into a message to the server.
        //
        // If there is no exception, logObject itself is worked into the message to the server.
        Logger.prototype.log = function (level, logObject, e) {
            var i = 0;
            var compositeMessage;
            var excObject;

            // If we can't find any appenders, do nothing
            if (!this.appenders) {
                return this;
            }

            if (((level >= this.level)) && allow(this)) {
                if (e) {
                    excObject = this.buildExceptionObject(e);
                    excObject.logData = stringifyLogObjectFunction(logObject);
                } else {
                    excObject = logObject;
                }

                compositeMessage = stringifyLogObject(excObject);

                if (allowMessage(this, compositeMessage.finalString)) {
                    // See whether message is a duplicate
                    if (this.onceOnly) {
                        i = this.onceOnly.length - 1;
                        while (i >= 0) {
                            if (new RegExp(this.onceOnly[i]).test(compositeMessage.finalString)) {
                                if (this.seenRegexes[i]) {
                                    return this;
                                }

                                this.seenRegexes[i] = true;
                            }

                            i--;
                        }
                    }

                    // Pass message to all appenders
                    // Note that these appenders could be Winston transports
                    // https://github.com/flatiron/winston
                    //
                    // These transports do not take the logger name as a parameter.
                    // So add it to the meta information, so even Winston transports will
                    // store this info.
                    compositeMessage.meta = compositeMessage.meta || {};
                    compositeMessage.meta.loggerName = this.loggerName;

                    i = this.appenders.length - 1;
                    while (i >= 0) {
                        this.appenders[i].log(levelToString(level), compositeMessage.msg, compositeMessage.meta, function () {
                        }, level, compositeMessage.finalString, this.loggerName);
                        i--;
                    }
                }
            }

            return this;
        };

        Logger.prototype.trace = function (logObject) {
            return this.log(getTraceLevel(), logObject);
        };
        Logger.prototype.debug = function (logObject) {
            return this.log(getDebugLevel(), logObject);
        };
        Logger.prototype.info = function (logObject) {
            return this.log(getInfoLevel(), logObject);
        };
        Logger.prototype.warn = function (logObject) {
            return this.log(getWarnLevel(), logObject);
        };
        Logger.prototype.error = function (logObject) {
            return this.log(getErrorLevel(), logObject);
        };
        Logger.prototype.fatal = function (logObject) {
            return this.log(getFatalLevel(), logObject);
        };
        Logger.prototype.fatalException = function (logObject, e) {
            return this.log(getFatalLevel(), logObject, e);
        };
        return Logger;
    })();
    JL.Logger = Logger;

    function createAjaxAppender(appenderName) {
        return new AjaxAppender(appenderName);
    }
    JL.createAjaxAppender = createAjaxAppender;

    function createConsoleAppender(appenderName) {
        return new ConsoleAppender(appenderName);
    }
    JL.createConsoleAppender = createConsoleAppender;

    // -----------------------
    // In the browser, the default appender is the AjaxAppender.
    // Under nodejs (where there is no "window"), use the ConsoleAppender instead.
    var defaultAppender = new AjaxAppender("");
    if (typeof window === 'undefined') {
        defaultAppender = new ConsoleAppender("");
    }

    // Create root logger
    //
    // Note that this is the parent of all other loggers.
    // Logger "x" will be stored at
    // JL.__.x
    // Logger "x.y" at
    // JL.__.x.y
    JL.__ = new JL.Logger("");
    JL.__.setOptions({
        level: JL.getDebugLevel(),
        appenders: [defaultAppender]
    });
})(JL || (JL = {}));

// Support CommonJS module format
var exports;
if (typeof exports !== 'undefined') {
    exports.JL = JL;
}

// Support AMD module format
var define;
if (typeof define == 'function' && define.amd) {
    define('jsnlog', [], function () {
        return JL;
    });
}

// If the __jsnlog_configure global function has been
// created, call it now. This allows you to create a global function
// setting logger options etc. inline in the page before jsnlog.js
// has been loaded.
if (typeof __jsnlog_configure == 'function') {
    __jsnlog_configure(JL);
}


},{}],"proj4/lib/Point":[function(require,module,exports){
var mgrs = require('mgrs');

function Point(x, y, z) {
  if (!(this instanceof Point)) {
    return new Point(x, y, z);
  }
  if (Array.isArray(x)) {
    this.x = x[0];
    this.y = x[1];
    this.z = x[2] || 0.0;
  }else if(typeof x === 'object'){
    this.x = x.x;
    this.y = x.y;
    this.z = x.z || 0.0;
  } else if (typeof x === 'string' && typeof y === 'undefined') {
    var coords = x.split(',');
    this.x = parseFloat(coords[0], 10);
    this.y = parseFloat(coords[1], 10);
    this.z = parseFloat(coords[2], 10) || 0.0;
  }
  else {
    this.x = x;
    this.y = y;
    this.z = z || 0.0;
  }
  console.warn('proj4.Point will be removed in version 3, use proj4.toPoint');
}

Point.fromMGRS = function(mgrsStr) {
  return new Point(mgrs.toPoint(mgrsStr));
};
Point.prototype.toMGRS = function(accuracy) {
  return mgrs.forward([this.x, this.y], accuracy);
};
module.exports = Point;
},{"mgrs":"proj4/node_modules/mgrs/mgrs"}],"proj4/lib/Proj":[function(require,module,exports){
var parseCode = require("./parseCode");
var extend = require('./extend');
var projections = require('./projections');
var deriveConstants = require('./deriveConstants');

function Projection(srsCode,callback) {
  if (!(this instanceof Projection)) {
    return new Projection(srsCode);
  }
  callback = callback || function(error){
    if(error){
      throw error;
    }
  };
  var json = parseCode(srsCode);
  if(typeof json !== 'object'){
    callback(srsCode);
    return;
  }
  var modifiedJSON = deriveConstants(json);
  var ourProj = Projection.projections.get(modifiedJSON.projName);
  if(ourProj){
    extend(this, modifiedJSON);
    extend(this, ourProj);
    this.init();
    callback(null, this);
  }else{
    callback(srsCode);
  }
}
Projection.projections = projections;
Projection.projections.start();
module.exports = Projection;

},{"./deriveConstants":"proj4/lib/deriveConstants","./extend":"proj4/lib/extend","./parseCode":"proj4/lib/parseCode","./projections":"proj4/lib/projections"}],"proj4/lib/adjust_axis":[function(require,module,exports){
module.exports = function(crs, denorm, point) {
  var xin = point.x,
    yin = point.y,
    zin = point.z || 0.0;
  var v, t, i;
  for (i = 0; i < 3; i++) {
    if (denorm && i === 2 && point.z === undefined) {
      continue;
    }
    if (i === 0) {
      v = xin;
      t = 'x';
    }
    else if (i === 1) {
      v = yin;
      t = 'y';
    }
    else {
      v = zin;
      t = 'z';
    }
    switch (crs.axis[i]) {
    case 'e':
      point[t] = v;
      break;
    case 'w':
      point[t] = -v;
      break;
    case 'n':
      point[t] = v;
      break;
    case 's':
      point[t] = -v;
      break;
    case 'u':
      if (point[t] !== undefined) {
        point.z = v;
      }
      break;
    case 'd':
      if (point[t] !== undefined) {
        point.z = -v;
      }
      break;
    default:
      //console.log("ERROR: unknow axis ("+crs.axis[i]+") - check definition of "+crs.projName);
      return null;
    }
  }
  return point;
};

},{}],"proj4/lib/common/adjust_lat":[function(require,module,exports){
var HALF_PI = Math.PI/2;
var sign = require('./sign');

module.exports = function(x) {
  return (Math.abs(x) < HALF_PI) ? x : (x - (sign(x) * Math.PI));
};
},{"./sign":"proj4/lib/common/sign"}],"proj4/lib/common/adjust_lon":[function(require,module,exports){
var TWO_PI = Math.PI * 2;
// SPI is slightly greater than Math.PI, so values that exceed the -180..180
// degree range by a tiny amount don't get wrapped. This prevents points that
// have drifted from their original location along the 180th meridian (due to
// floating point error) from changing their sign.
var SPI = 3.14159265359;
var sign = require('./sign');

module.exports = function(x) {
  return (Math.abs(x) <= SPI) ? x : (x - (sign(x) * TWO_PI));
};
},{"./sign":"proj4/lib/common/sign"}],"proj4/lib/common/asinz":[function(require,module,exports){
module.exports = function(x) {
  if (Math.abs(x) > 1) {
    x = (x > 1) ? 1 : -1;
  }
  return Math.asin(x);
};
},{}],"proj4/lib/common/e0fn":[function(require,module,exports){
module.exports = function(x) {
  return (1 - 0.25 * x * (1 + x / 16 * (3 + 1.25 * x)));
};
},{}],"proj4/lib/common/e1fn":[function(require,module,exports){
module.exports = function(x) {
  return (0.375 * x * (1 + 0.25 * x * (1 + 0.46875 * x)));
};
},{}],"proj4/lib/common/e2fn":[function(require,module,exports){
module.exports = function(x) {
  return (0.05859375 * x * x * (1 + 0.75 * x));
};
},{}],"proj4/lib/common/e3fn":[function(require,module,exports){
module.exports = function(x) {
  return (x * x * x * (35 / 3072));
};
},{}],"proj4/lib/common/gN":[function(require,module,exports){
module.exports = function(a, e, sinphi) {
  var temp = e * sinphi;
  return a / Math.sqrt(1 - temp * temp);
};
},{}],"proj4/lib/common/imlfn":[function(require,module,exports){
module.exports = function(ml, e0, e1, e2, e3) {
  var phi;
  var dphi;

  phi = ml / e0;
  for (var i = 0; i < 15; i++) {
    dphi = (ml - (e0 * phi - e1 * Math.sin(2 * phi) + e2 * Math.sin(4 * phi) - e3 * Math.sin(6 * phi))) / (e0 - 2 * e1 * Math.cos(2 * phi) + 4 * e2 * Math.cos(4 * phi) - 6 * e3 * Math.cos(6 * phi));
    phi += dphi;
    if (Math.abs(dphi) <= 0.0000000001) {
      return phi;
    }
  }

  //..reportError("IMLFN-CONV:Latitude failed to converge after 15 iterations");
  return NaN;
};
},{}],"proj4/lib/common/iqsfnz":[function(require,module,exports){
var HALF_PI = Math.PI/2;

module.exports = function(eccent, q) {
  var temp = 1 - (1 - eccent * eccent) / (2 * eccent) * Math.log((1 - eccent) / (1 + eccent));
  if (Math.abs(Math.abs(q) - temp) < 1.0E-6) {
    if (q < 0) {
      return (-1 * HALF_PI);
    }
    else {
      return HALF_PI;
    }
  }
  //var phi = 0.5* q/(1-eccent*eccent);
  var phi = Math.asin(0.5 * q);
  var dphi;
  var sin_phi;
  var cos_phi;
  var con;
  for (var i = 0; i < 30; i++) {
    sin_phi = Math.sin(phi);
    cos_phi = Math.cos(phi);
    con = eccent * sin_phi;
    dphi = Math.pow(1 - con * con, 2) / (2 * cos_phi) * (q / (1 - eccent * eccent) - sin_phi / (1 - con * con) + 0.5 / eccent * Math.log((1 - con) / (1 + con)));
    phi += dphi;
    if (Math.abs(dphi) <= 0.0000000001) {
      return phi;
    }
  }

  //console.log("IQSFN-CONV:Latitude failed to converge after 30 iterations");
  return NaN;
};
},{}],"proj4/lib/common/mlfn":[function(require,module,exports){
module.exports = function(e0, e1, e2, e3, phi) {
  return (e0 * phi - e1 * Math.sin(2 * phi) + e2 * Math.sin(4 * phi) - e3 * Math.sin(6 * phi));
};
},{}],"proj4/lib/common/msfnz":[function(require,module,exports){
module.exports = function(eccent, sinphi, cosphi) {
  var con = eccent * sinphi;
  return cosphi / (Math.sqrt(1 - con * con));
};
},{}],"proj4/lib/common/phi2z":[function(require,module,exports){
var HALF_PI = Math.PI/2;
module.exports = function(eccent, ts) {
  var eccnth = 0.5 * eccent;
  var con, dphi;
  var phi = HALF_PI - 2 * Math.atan(ts);
  for (var i = 0; i <= 15; i++) {
    con = eccent * Math.sin(phi);
    dphi = HALF_PI - 2 * Math.atan(ts * (Math.pow(((1 - con) / (1 + con)), eccnth))) - phi;
    phi += dphi;
    if (Math.abs(dphi) <= 0.0000000001) {
      return phi;
    }
  }
  //console.log("phi2z has NoConvergence");
  return -9999;
};
},{}],"proj4/lib/common/pj_enfn":[function(require,module,exports){
var C00 = 1;
var C02 = 0.25;
var C04 = 0.046875;
var C06 = 0.01953125;
var C08 = 0.01068115234375;
var C22 = 0.75;
var C44 = 0.46875;
var C46 = 0.01302083333333333333;
var C48 = 0.00712076822916666666;
var C66 = 0.36458333333333333333;
var C68 = 0.00569661458333333333;
var C88 = 0.3076171875;

module.exports = function(es) {
  var en = [];
  en[0] = C00 - es * (C02 + es * (C04 + es * (C06 + es * C08)));
  en[1] = es * (C22 - es * (C04 + es * (C06 + es * C08)));
  var t = es * es;
  en[2] = t * (C44 - es * (C46 + es * C48));
  t *= es;
  en[3] = t * (C66 - es * C68);
  en[4] = t * es * C88;
  return en;
};
},{}],"proj4/lib/common/pj_inv_mlfn":[function(require,module,exports){
var pj_mlfn = require("./pj_mlfn");
var EPSLN = 1.0e-10;
var MAX_ITER = 20;
module.exports = function(arg, es, en) {
  var k = 1 / (1 - es);
  var phi = arg;
  for (var i = MAX_ITER; i; --i) { /* rarely goes over 2 iterations */
    var s = Math.sin(phi);
    var t = 1 - es * s * s;
    //t = this.pj_mlfn(phi, s, Math.cos(phi), en) - arg;
    //phi -= t * (t * Math.sqrt(t)) * k;
    t = (pj_mlfn(phi, s, Math.cos(phi), en) - arg) * (t * Math.sqrt(t)) * k;
    phi -= t;
    if (Math.abs(t) < EPSLN) {
      return phi;
    }
  }
  //..reportError("cass:pj_inv_mlfn: Convergence error");
  return phi;
};
},{"./pj_mlfn":"proj4/lib/common/pj_mlfn"}],"proj4/lib/common/pj_mlfn":[function(require,module,exports){
module.exports = function(phi, sphi, cphi, en) {
  cphi *= sphi;
  sphi *= sphi;
  return (en[0] * phi - cphi * (en[1] + sphi * (en[2] + sphi * (en[3] + sphi * en[4]))));
};
},{}],"proj4/lib/common/qsfnz":[function(require,module,exports){
module.exports = function(eccent, sinphi) {
  var con;
  if (eccent > 1.0e-7) {
    con = eccent * sinphi;
    return ((1 - eccent * eccent) * (sinphi / (1 - con * con) - (0.5 / eccent) * Math.log((1 - con) / (1 + con))));
  }
  else {
    return (2 * sinphi);
  }
};
},{}],"proj4/lib/common/sign":[function(require,module,exports){
module.exports = function(x) {
  return x<0 ? -1 : 1;
};
},{}],"proj4/lib/common/srat":[function(require,module,exports){
module.exports = function(esinp, exp) {
  return (Math.pow((1 - esinp) / (1 + esinp), exp));
};
},{}],"proj4/lib/common/toPoint":[function(require,module,exports){
module.exports = function (array){
  var out = {
    x: array[0],
    y: array[1]
  };
  if (array.length>2) {
    out.z = array[2];
  }
  if (array.length>3) {
    out.m = array[3];
  }
  return out;
};
},{}],"proj4/lib/common/tsfnz":[function(require,module,exports){
var HALF_PI = Math.PI/2;

module.exports = function(eccent, phi, sinphi) {
  var con = eccent * sinphi;
  var com = 0.5 * eccent;
  con = Math.pow(((1 - con) / (1 + con)), com);
  return (Math.tan(0.5 * (HALF_PI - phi)) / con);
};
},{}],"proj4/lib/constants/Datum":[function(require,module,exports){
exports.wgs84 = {
  towgs84: "0,0,0",
  ellipse: "WGS84",
  datumName: "WGS84"
};
exports.ch1903 = {
  towgs84: "674.374,15.056,405.346",
  ellipse: "bessel",
  datumName: "swiss"
};
exports.ggrs87 = {
  towgs84: "-199.87,74.79,246.62",
  ellipse: "GRS80",
  datumName: "Greek_Geodetic_Reference_System_1987"
};
exports.nad83 = {
  towgs84: "0,0,0",
  ellipse: "GRS80",
  datumName: "North_American_Datum_1983"
};
exports.nad27 = {
  nadgrids: "@conus,@alaska,@ntv2_0.gsb,@ntv1_can.dat",
  ellipse: "clrk66",
  datumName: "North_American_Datum_1927"
};
exports.potsdam = {
  towgs84: "606.0,23.0,413.0",
  ellipse: "bessel",
  datumName: "Potsdam Rauenberg 1950 DHDN"
};
exports.carthage = {
  towgs84: "-263.0,6.0,431.0",
  ellipse: "clark80",
  datumName: "Carthage 1934 Tunisia"
};
exports.hermannskogel = {
  towgs84: "653.0,-212.0,449.0",
  ellipse: "bessel",
  datumName: "Hermannskogel"
};
exports.ire65 = {
  towgs84: "482.530,-130.596,564.557,-1.042,-0.214,-0.631,8.15",
  ellipse: "mod_airy",
  datumName: "Ireland 1965"
};
exports.rassadiran = {
  towgs84: "-133.63,-157.5,-158.62",
  ellipse: "intl",
  datumName: "Rassadiran"
};
exports.nzgd49 = {
  towgs84: "59.47,-5.04,187.44,0.47,-0.1,1.024,-4.5993",
  ellipse: "intl",
  datumName: "New Zealand Geodetic Datum 1949"
};
exports.osgb36 = {
  towgs84: "446.448,-125.157,542.060,0.1502,0.2470,0.8421,-20.4894",
  ellipse: "airy",
  datumName: "Airy 1830"
};
exports.s_jtsk = {
  towgs84: "589,76,480",
  ellipse: 'bessel',
  datumName: 'S-JTSK (Ferro)'
};
exports.beduaram = {
  towgs84: '-106,-87,188',
  ellipse: 'clrk80',
  datumName: 'Beduaram'
};
exports.gunung_segara = {
  towgs84: '-403,684,41',
  ellipse: 'bessel',
  datumName: 'Gunung Segara Jakarta'
};
exports.rnb72 = {
  towgs84: "106.869,-52.2978,103.724,-0.33657,0.456955,-1.84218,1",
  ellipse: "intl",
  datumName: "Reseau National Belge 1972"
};
},{}],"proj4/lib/constants/Ellipsoid":[function(require,module,exports){
exports.MERIT = {
  a: 6378137.0,
  rf: 298.257,
  ellipseName: "MERIT 1983"
};
exports.SGS85 = {
  a: 6378136.0,
  rf: 298.257,
  ellipseName: "Soviet Geodetic System 85"
};
exports.GRS80 = {
  a: 6378137.0,
  rf: 298.257222101,
  ellipseName: "GRS 1980(IUGG, 1980)"
};
exports.IAU76 = {
  a: 6378140.0,
  rf: 298.257,
  ellipseName: "IAU 1976"
};
exports.airy = {
  a: 6377563.396,
  b: 6356256.910,
  ellipseName: "Airy 1830"
};
exports.APL4 = {
  a: 6378137,
  rf: 298.25,
  ellipseName: "Appl. Physics. 1965"
};
exports.NWL9D = {
  a: 6378145.0,
  rf: 298.25,
  ellipseName: "Naval Weapons Lab., 1965"
};
exports.mod_airy = {
  a: 6377340.189,
  b: 6356034.446,
  ellipseName: "Modified Airy"
};
exports.andrae = {
  a: 6377104.43,
  rf: 300.0,
  ellipseName: "Andrae 1876 (Den., Iclnd.)"
};
exports.aust_SA = {
  a: 6378160.0,
  rf: 298.25,
  ellipseName: "Australian Natl & S. Amer. 1969"
};
exports.GRS67 = {
  a: 6378160.0,
  rf: 298.2471674270,
  ellipseName: "GRS 67(IUGG 1967)"
};
exports.bessel = {
  a: 6377397.155,
  rf: 299.1528128,
  ellipseName: "Bessel 1841"
};
exports.bess_nam = {
  a: 6377483.865,
  rf: 299.1528128,
  ellipseName: "Bessel 1841 (Namibia)"
};
exports.clrk66 = {
  a: 6378206.4,
  b: 6356583.8,
  ellipseName: "Clarke 1866"
};
exports.clrk80 = {
  a: 6378249.145,
  rf: 293.4663,
  ellipseName: "Clarke 1880 mod."
};
exports.clrk58 = {
  a: 6378293.645208759,
  rf: 294.2606763692654,
  ellipseName: "Clarke 1858"
};
exports.CPM = {
  a: 6375738.7,
  rf: 334.29,
  ellipseName: "Comm. des Poids et Mesures 1799"
};
exports.delmbr = {
  a: 6376428.0,
  rf: 311.5,
  ellipseName: "Delambre 1810 (Belgium)"
};
exports.engelis = {
  a: 6378136.05,
  rf: 298.2566,
  ellipseName: "Engelis 1985"
};
exports.evrst30 = {
  a: 6377276.345,
  rf: 300.8017,
  ellipseName: "Everest 1830"
};
exports.evrst48 = {
  a: 6377304.063,
  rf: 300.8017,
  ellipseName: "Everest 1948"
};
exports.evrst56 = {
  a: 6377301.243,
  rf: 300.8017,
  ellipseName: "Everest 1956"
};
exports.evrst69 = {
  a: 6377295.664,
  rf: 300.8017,
  ellipseName: "Everest 1969"
};
exports.evrstSS = {
  a: 6377298.556,
  rf: 300.8017,
  ellipseName: "Everest (Sabah & Sarawak)"
};
exports.fschr60 = {
  a: 6378166.0,
  rf: 298.3,
  ellipseName: "Fischer (Mercury Datum) 1960"
};
exports.fschr60m = {
  a: 6378155.0,
  rf: 298.3,
  ellipseName: "Fischer 1960"
};
exports.fschr68 = {
  a: 6378150.0,
  rf: 298.3,
  ellipseName: "Fischer 1968"
};
exports.helmert = {
  a: 6378200.0,
  rf: 298.3,
  ellipseName: "Helmert 1906"
};
exports.hough = {
  a: 6378270.0,
  rf: 297.0,
  ellipseName: "Hough"
};
exports.intl = {
  a: 6378388.0,
  rf: 297.0,
  ellipseName: "International 1909 (Hayford)"
};
exports.kaula = {
  a: 6378163.0,
  rf: 298.24,
  ellipseName: "Kaula 1961"
};
exports.lerch = {
  a: 6378139.0,
  rf: 298.257,
  ellipseName: "Lerch 1979"
};
exports.mprts = {
  a: 6397300.0,
  rf: 191.0,
  ellipseName: "Maupertius 1738"
};
exports.new_intl = {
  a: 6378157.5,
  b: 6356772.2,
  ellipseName: "New International 1967"
};
exports.plessis = {
  a: 6376523.0,
  rf: 6355863.0,
  ellipseName: "Plessis 1817 (France)"
};
exports.krass = {
  a: 6378245.0,
  rf: 298.3,
  ellipseName: "Krassovsky, 1942"
};
exports.SEasia = {
  a: 6378155.0,
  b: 6356773.3205,
  ellipseName: "Southeast Asia"
};
exports.walbeck = {
  a: 6376896.0,
  b: 6355834.8467,
  ellipseName: "Walbeck"
};
exports.WGS60 = {
  a: 6378165.0,
  rf: 298.3,
  ellipseName: "WGS 60"
};
exports.WGS66 = {
  a: 6378145.0,
  rf: 298.25,
  ellipseName: "WGS 66"
};
exports.WGS7 = {
  a: 6378135.0,
  rf: 298.26,
  ellipseName: "WGS 72"
};
exports.WGS84 = {
  a: 6378137.0,
  rf: 298.257223563,
  ellipseName: "WGS 84"
};
exports.sphere = {
  a: 6370997.0,
  b: 6370997.0,
  ellipseName: "Normal Sphere (r=6370997)"
};
},{}],"proj4/lib/constants/PrimeMeridian":[function(require,module,exports){
exports.greenwich = 0.0; //"0dE",
exports.lisbon = -9.131906111111; //"9d07'54.862\"W",
exports.paris = 2.337229166667; //"2d20'14.025\"E",
exports.bogota = -74.080916666667; //"74d04'51.3\"W",
exports.madrid = -3.687938888889; //"3d41'16.58\"W",
exports.rome = 12.452333333333; //"12d27'8.4\"E",
exports.bern = 7.439583333333; //"7d26'22.5\"E",
exports.jakarta = 106.807719444444; //"106d48'27.79\"E",
exports.ferro = -17.666666666667; //"17d40'W",
exports.brussels = 4.367975; //"4d22'4.71\"E",
exports.stockholm = 18.058277777778; //"18d3'29.8\"E",
exports.athens = 23.7163375; //"23d42'58.815\"E",
exports.oslo = 10.722916666667; //"10d43'22.5\"E"
},{}],"proj4/lib/constants/units":[function(require,module,exports){
exports.ft = {to_meter: 0.3048};
exports['us-ft'] = {to_meter: 1200 / 3937};

},{}],"proj4/lib/core":[function(require,module,exports){
var proj = require('./Proj');
var transform = require('./transform');
var wgs84 = proj('WGS84');

function transformer(from, to, coords) {
  var transformedArray;
  if (Array.isArray(coords)) {
    transformedArray = transform(from, to, coords);
    if (coords.length === 3) {
      return [transformedArray.x, transformedArray.y, transformedArray.z];
    }
    else {
      return [transformedArray.x, transformedArray.y];
    }
  }
  else {
    return transform(from, to, coords);
  }
}

function checkProj(item) {
  if (item instanceof proj) {
    return item;
  }
  if (item.oProj) {
    return item.oProj;
  }
  return proj(item);
}
function proj4(fromProj, toProj, coord) {
  fromProj = checkProj(fromProj);
  var single = false;
  var obj;
  if (typeof toProj === 'undefined') {
    toProj = fromProj;
    fromProj = wgs84;
    single = true;
  }
  else if (typeof toProj.x !== 'undefined' || Array.isArray(toProj)) {
    coord = toProj;
    toProj = fromProj;
    fromProj = wgs84;
    single = true;
  }
  toProj = checkProj(toProj);
  if (coord) {
    return transformer(fromProj, toProj, coord);
  }
  else {
    obj = {
      forward: function(coords) {
        return transformer(fromProj, toProj, coords);
      },
      inverse: function(coords) {
        return transformer(toProj, fromProj, coords);
      }
    };
    if (single) {
      obj.oProj = toProj;
    }
    return obj;
  }
}
module.exports = proj4;
},{"./Proj":"proj4/lib/Proj","./transform":"proj4/lib/transform"}],"proj4/lib/datum":[function(require,module,exports){
var HALF_PI = Math.PI/2;
var PJD_3PARAM = 1;
var PJD_7PARAM = 2;
var PJD_GRIDSHIFT = 3;
var PJD_WGS84 = 4; // WGS84 or equivalent
var PJD_NODATUM = 5; // WGS84 or equivalent
var SEC_TO_RAD = 4.84813681109535993589914102357e-6;
var AD_C = 1.0026000;
var COS_67P5 = 0.38268343236508977;
var datum = function(proj) {
  if (!(this instanceof datum)) {
    return new datum(proj);
  }
  this.datum_type = PJD_WGS84; //default setting
  if (!proj) {
    return;
  }
  if (proj.datumCode && proj.datumCode === 'none') {
    this.datum_type = PJD_NODATUM;
  }

  if (proj.datum_params) {
    this.datum_params = proj.datum_params.map(parseFloat);
    if (this.datum_params[0] !== 0 || this.datum_params[1] !== 0 || this.datum_params[2] !== 0) {
      this.datum_type = PJD_3PARAM;
    }
    if (this.datum_params.length > 3) {
      if (this.datum_params[3] !== 0 || this.datum_params[4] !== 0 || this.datum_params[5] !== 0 || this.datum_params[6] !== 0) {
        this.datum_type = PJD_7PARAM;
        this.datum_params[3] *= SEC_TO_RAD;
        this.datum_params[4] *= SEC_TO_RAD;
        this.datum_params[5] *= SEC_TO_RAD;
        this.datum_params[6] = (this.datum_params[6] / 1000000.0) + 1.0;
      }
    }
  }

  // DGR 2011-03-21 : nadgrids support
  this.datum_type = proj.grids ? PJD_GRIDSHIFT : this.datum_type;

  this.a = proj.a; //datum object also uses these values
  this.b = proj.b;
  this.es = proj.es;
  this.ep2 = proj.ep2;
  if (this.datum_type === PJD_GRIDSHIFT) {
    this.grids = proj.grids;
  }
};
datum.prototype = {


  /****************************************************************/
  // cs_compare_datums()
  //   Returns TRUE if the two datums match, otherwise FALSE.
  compare_datums: function(dest) {
    if (this.datum_type !== dest.datum_type) {
      return false; // false, datums are not equal
    }
    else if (this.a !== dest.a || Math.abs(this.es - dest.es) > 0.000000000050) {
      // the tolerence for es is to ensure that GRS80 and WGS84
      // are considered identical
      return false;
    }
    else if (this.datum_type === PJD_3PARAM) {
      return (this.datum_params[0] === dest.datum_params[0] && this.datum_params[1] === dest.datum_params[1] && this.datum_params[2] === dest.datum_params[2]);
    }
    else if (this.datum_type === PJD_7PARAM) {
      return (this.datum_params[0] === dest.datum_params[0] && this.datum_params[1] === dest.datum_params[1] && this.datum_params[2] === dest.datum_params[2] && this.datum_params[3] === dest.datum_params[3] && this.datum_params[4] === dest.datum_params[4] && this.datum_params[5] === dest.datum_params[5] && this.datum_params[6] === dest.datum_params[6]);
    }
    else if (this.datum_type === PJD_GRIDSHIFT || dest.datum_type === PJD_GRIDSHIFT) {
      //alert("ERROR: Grid shift transformations are not implemented.");
      //return false
      //DGR 2012-07-29 lazy ...
      return this.nadgrids === dest.nadgrids;
    }
    else {
      return true; // datums are equal
    }
  }, // cs_compare_datums()

  /*
   * The function Convert_Geodetic_To_Geocentric converts geodetic coordinates
   * (latitude, longitude, and height) to geocentric coordinates (X, Y, Z),
   * according to the current ellipsoid parameters.
   *
   *    Latitude  : Geodetic latitude in radians                     (input)
   *    Longitude : Geodetic longitude in radians                    (input)
   *    Height    : Geodetic height, in meters                       (input)
   *    X         : Calculated Geocentric X coordinate, in meters    (output)
   *    Y         : Calculated Geocentric Y coordinate, in meters    (output)
   *    Z         : Calculated Geocentric Z coordinate, in meters    (output)
   *
   */
  geodetic_to_geocentric: function(p) {
    var Longitude = p.x;
    var Latitude = p.y;
    var Height = p.z ? p.z : 0; //Z value not always supplied
    var X; // output
    var Y;
    var Z;

    var Error_Code = 0; //  GEOCENT_NO_ERROR;
    var Rn; /*  Earth radius at location  */
    var Sin_Lat; /*  Math.sin(Latitude)  */
    var Sin2_Lat; /*  Square of Math.sin(Latitude)  */
    var Cos_Lat; /*  Math.cos(Latitude)  */

    /*
     ** Don't blow up if Latitude is just a little out of the value
     ** range as it may just be a rounding issue.  Also removed longitude
     ** test, it should be wrapped by Math.cos() and Math.sin().  NFW for PROJ.4, Sep/2001.
     */
    if (Latitude < -HALF_PI && Latitude > -1.001 * HALF_PI) {
      Latitude = -HALF_PI;
    }
    else if (Latitude > HALF_PI && Latitude < 1.001 * HALF_PI) {
      Latitude = HALF_PI;
    }
    else if ((Latitude < -HALF_PI) || (Latitude > HALF_PI)) {
      /* Latitude out of range */
      //..reportError('geocent:lat out of range:' + Latitude);
      return null;
    }

    if (Longitude > Math.PI) {
      Longitude -= (2 * Math.PI);
    }
    Sin_Lat = Math.sin(Latitude);
    Cos_Lat = Math.cos(Latitude);
    Sin2_Lat = Sin_Lat * Sin_Lat;
    Rn = this.a / (Math.sqrt(1.0e0 - this.es * Sin2_Lat));
    X = (Rn + Height) * Cos_Lat * Math.cos(Longitude);
    Y = (Rn + Height) * Cos_Lat * Math.sin(Longitude);
    Z = ((Rn * (1 - this.es)) + Height) * Sin_Lat;

    p.x = X;
    p.y = Y;
    p.z = Z;
    return Error_Code;
  }, // cs_geodetic_to_geocentric()


  geocentric_to_geodetic: function(p) {
    /* local defintions and variables */
    /* end-criterium of loop, accuracy of sin(Latitude) */
    var genau = 1e-12;
    var genau2 = (genau * genau);
    var maxiter = 30;

    var P; /* distance between semi-minor axis and location */
    var RR; /* distance between center and location */
    var CT; /* sin of geocentric latitude */
    var ST; /* cos of geocentric latitude */
    var RX;
    var RK;
    var RN; /* Earth radius at location */
    var CPHI0; /* cos of start or old geodetic latitude in iterations */
    var SPHI0; /* sin of start or old geodetic latitude in iterations */
    var CPHI; /* cos of searched geodetic latitude */
    var SPHI; /* sin of searched geodetic latitude */
    var SDPHI; /* end-criterium: addition-theorem of sin(Latitude(iter)-Latitude(iter-1)) */
    var At_Pole; /* indicates location is in polar region */
    var iter; /* # of continous iteration, max. 30 is always enough (s.a.) */

    var X = p.x;
    var Y = p.y;
    var Z = p.z ? p.z : 0.0; //Z value not always supplied
    var Longitude;
    var Latitude;
    var Height;

    At_Pole = false;
    P = Math.sqrt(X * X + Y * Y);
    RR = Math.sqrt(X * X + Y * Y + Z * Z);

    /*      special cases for latitude and longitude */
    if (P / this.a < genau) {

      /*  special case, if P=0. (X=0., Y=0.) */
      At_Pole = true;
      Longitude = 0.0;

      /*  if (X,Y,Z)=(0.,0.,0.) then Height becomes semi-minor axis
       *  of ellipsoid (=center of mass), Latitude becomes PI/2 */
      if (RR / this.a < genau) {
        Latitude = HALF_PI;
        Height = -this.b;
        return;
      }
    }
    else {
      /*  ellipsoidal (geodetic) longitude
       *  interval: -PI < Longitude <= +PI */
      Longitude = Math.atan2(Y, X);
    }

    /* --------------------------------------------------------------
     * Following iterative algorithm was developped by
     * "Institut for Erdmessung", University of Hannover, July 1988.
     * Internet: www.ife.uni-hannover.de
     * Iterative computation of CPHI,SPHI and Height.
     * Iteration of CPHI and SPHI to 10**-12 radian resp.
     * 2*10**-7 arcsec.
     * --------------------------------------------------------------
     */
    CT = Z / RR;
    ST = P / RR;
    RX = 1.0 / Math.sqrt(1.0 - this.es * (2.0 - this.es) * ST * ST);
    CPHI0 = ST * (1.0 - this.es) * RX;
    SPHI0 = CT * RX;
    iter = 0;

    /* loop to find sin(Latitude) resp. Latitude
     * until |sin(Latitude(iter)-Latitude(iter-1))| < genau */
    do {
      iter++;
      RN = this.a / Math.sqrt(1.0 - this.es * SPHI0 * SPHI0);

      /*  ellipsoidal (geodetic) height */
      Height = P * CPHI0 + Z * SPHI0 - RN * (1.0 - this.es * SPHI0 * SPHI0);

      RK = this.es * RN / (RN + Height);
      RX = 1.0 / Math.sqrt(1.0 - RK * (2.0 - RK) * ST * ST);
      CPHI = ST * (1.0 - RK) * RX;
      SPHI = CT * RX;
      SDPHI = SPHI * CPHI0 - CPHI * SPHI0;
      CPHI0 = CPHI;
      SPHI0 = SPHI;
    }
    while (SDPHI * SDPHI > genau2 && iter < maxiter);

    /*      ellipsoidal (geodetic) latitude */
    Latitude = Math.atan(SPHI / Math.abs(CPHI));

    p.x = Longitude;
    p.y = Latitude;
    p.z = Height;
    return p;
  }, // cs_geocentric_to_geodetic()

  /** Convert_Geocentric_To_Geodetic
   * The method used here is derived from 'An Improved Algorithm for
   * Geocentric to Geodetic Coordinate Conversion', by Ralph Toms, Feb 1996
   */
  geocentric_to_geodetic_noniter: function(p) {
    var X = p.x;
    var Y = p.y;
    var Z = p.z ? p.z : 0; //Z value not always supplied
    var Longitude;
    var Latitude;
    var Height;

    var W; /* distance from Z axis */
    var W2; /* square of distance from Z axis */
    var T0; /* initial estimate of vertical component */
    var T1; /* corrected estimate of vertical component */
    var S0; /* initial estimate of horizontal component */
    var S1; /* corrected estimate of horizontal component */
    var Sin_B0; /* Math.sin(B0), B0 is estimate of Bowring aux variable */
    var Sin3_B0; /* cube of Math.sin(B0) */
    var Cos_B0; /* Math.cos(B0) */
    var Sin_p1; /* Math.sin(phi1), phi1 is estimated latitude */
    var Cos_p1; /* Math.cos(phi1) */
    var Rn; /* Earth radius at location */
    var Sum; /* numerator of Math.cos(phi1) */
    var At_Pole; /* indicates location is in polar region */

    X = parseFloat(X); // cast from string to float
    Y = parseFloat(Y);
    Z = parseFloat(Z);

    At_Pole = false;
    if (X !== 0.0) {
      Longitude = Math.atan2(Y, X);
    }
    else {
      if (Y > 0) {
        Longitude = HALF_PI;
      }
      else if (Y < 0) {
        Longitude = -HALF_PI;
      }
      else {
        At_Pole = true;
        Longitude = 0.0;
        if (Z > 0.0) { /* north pole */
          Latitude = HALF_PI;
        }
        else if (Z < 0.0) { /* south pole */
          Latitude = -HALF_PI;
        }
        else { /* center of earth */
          Latitude = HALF_PI;
          Height = -this.b;
          return;
        }
      }
    }
    W2 = X * X + Y * Y;
    W = Math.sqrt(W2);
    T0 = Z * AD_C;
    S0 = Math.sqrt(T0 * T0 + W2);
    Sin_B0 = T0 / S0;
    Cos_B0 = W / S0;
    Sin3_B0 = Sin_B0 * Sin_B0 * Sin_B0;
    T1 = Z + this.b * this.ep2 * Sin3_B0;
    Sum = W - this.a * this.es * Cos_B0 * Cos_B0 * Cos_B0;
    S1 = Math.sqrt(T1 * T1 + Sum * Sum);
    Sin_p1 = T1 / S1;
    Cos_p1 = Sum / S1;
    Rn = this.a / Math.sqrt(1.0 - this.es * Sin_p1 * Sin_p1);
    if (Cos_p1 >= COS_67P5) {
      Height = W / Cos_p1 - Rn;
    }
    else if (Cos_p1 <= -COS_67P5) {
      Height = W / -Cos_p1 - Rn;
    }
    else {
      Height = Z / Sin_p1 + Rn * (this.es - 1.0);
    }
    if (At_Pole === false) {
      Latitude = Math.atan(Sin_p1 / Cos_p1);
    }

    p.x = Longitude;
    p.y = Latitude;
    p.z = Height;
    return p;
  }, // geocentric_to_geodetic_noniter()

  /****************************************************************/
  // pj_geocentic_to_wgs84( p )
  //  p = point to transform in geocentric coordinates (x,y,z)
  geocentric_to_wgs84: function(p) {

    if (this.datum_type === PJD_3PARAM) {
      // if( x[io] === HUGE_VAL )
      //    continue;
      p.x += this.datum_params[0];
      p.y += this.datum_params[1];
      p.z += this.datum_params[2];

    }
    else if (this.datum_type === PJD_7PARAM) {
      var Dx_BF = this.datum_params[0];
      var Dy_BF = this.datum_params[1];
      var Dz_BF = this.datum_params[2];
      var Rx_BF = this.datum_params[3];
      var Ry_BF = this.datum_params[4];
      var Rz_BF = this.datum_params[5];
      var M_BF = this.datum_params[6];
      // if( x[io] === HUGE_VAL )
      //    continue;
      var x_out = M_BF * (p.x - Rz_BF * p.y + Ry_BF * p.z) + Dx_BF;
      var y_out = M_BF * (Rz_BF * p.x + p.y - Rx_BF * p.z) + Dy_BF;
      var z_out = M_BF * (-Ry_BF * p.x + Rx_BF * p.y + p.z) + Dz_BF;
      p.x = x_out;
      p.y = y_out;
      p.z = z_out;
    }
  }, // cs_geocentric_to_wgs84

  /****************************************************************/
  // pj_geocentic_from_wgs84()
  //  coordinate system definition,
  //  point to transform in geocentric coordinates (x,y,z)
  geocentric_from_wgs84: function(p) {

    if (this.datum_type === PJD_3PARAM) {
      //if( x[io] === HUGE_VAL )
      //    continue;
      p.x -= this.datum_params[0];
      p.y -= this.datum_params[1];
      p.z -= this.datum_params[2];

    }
    else if (this.datum_type === PJD_7PARAM) {
      var Dx_BF = this.datum_params[0];
      var Dy_BF = this.datum_params[1];
      var Dz_BF = this.datum_params[2];
      var Rx_BF = this.datum_params[3];
      var Ry_BF = this.datum_params[4];
      var Rz_BF = this.datum_params[5];
      var M_BF = this.datum_params[6];
      var x_tmp = (p.x - Dx_BF) / M_BF;
      var y_tmp = (p.y - Dy_BF) / M_BF;
      var z_tmp = (p.z - Dz_BF) / M_BF;
      //if( x[io] === HUGE_VAL )
      //    continue;

      p.x = x_tmp + Rz_BF * y_tmp - Ry_BF * z_tmp;
      p.y = -Rz_BF * x_tmp + y_tmp + Rx_BF * z_tmp;
      p.z = Ry_BF * x_tmp - Rx_BF * y_tmp + z_tmp;
    } //cs_geocentric_from_wgs84()
  }
};

/** point object, nothing fancy, just allows values to be
    passed back and forth by reference rather than by value.
    Other point classes may be used as long as they have
    x and y properties, which will get modified in the transform method.
*/
module.exports = datum;

},{}],"proj4/lib/datum_transform":[function(require,module,exports){
var PJD_3PARAM = 1;
var PJD_7PARAM = 2;
var PJD_GRIDSHIFT = 3;
var PJD_NODATUM = 5; // WGS84 or equivalent
var SRS_WGS84_SEMIMAJOR = 6378137; // only used in grid shift transforms
var SRS_WGS84_ESQUARED = 0.006694379990141316; //DGR: 2012-07-29
module.exports = function(source, dest, point) {
  var wp, i, l;

  function checkParams(fallback) {
    return (fallback === PJD_3PARAM || fallback === PJD_7PARAM);
  }
  // Short cut if the datums are identical.
  if (source.compare_datums(dest)) {
    return point; // in this case, zero is sucess,
    // whereas cs_compare_datums returns 1 to indicate TRUE
    // confusing, should fix this
  }

  // Explicitly skip datum transform by setting 'datum=none' as parameter for either source or dest
  if (source.datum_type === PJD_NODATUM || dest.datum_type === PJD_NODATUM) {
    return point;
  }

  //DGR: 2012-07-29 : add nadgrids support (begin)
  var src_a = source.a;
  var src_es = source.es;

  var dst_a = dest.a;
  var dst_es = dest.es;

  var fallback = source.datum_type;
  // If this datum requires grid shifts, then apply it to geodetic coordinates.
  if (fallback === PJD_GRIDSHIFT) {
    if (this.apply_gridshift(source, 0, point) === 0) {
      source.a = SRS_WGS84_SEMIMAJOR;
      source.es = SRS_WGS84_ESQUARED;
    }
    else {
      // try 3 or 7 params transformation or nothing ?
      if (!source.datum_params) {
        source.a = src_a;
        source.es = source.es;
        return point;
      }
      wp = 1;
      for (i = 0, l = source.datum_params.length; i < l; i++) {
        wp *= source.datum_params[i];
      }
      if (wp === 0) {
        source.a = src_a;
        source.es = source.es;
        return point;
      }
      if (source.datum_params.length > 3) {
        fallback = PJD_7PARAM;
      }
      else {
        fallback = PJD_3PARAM;
      }
    }
  }
  if (dest.datum_type === PJD_GRIDSHIFT) {
    dest.a = SRS_WGS84_SEMIMAJOR;
    dest.es = SRS_WGS84_ESQUARED;
  }
  // Do we need to go through geocentric coordinates?
  if (source.es !== dest.es || source.a !== dest.a || checkParams(fallback) || checkParams(dest.datum_type)) {
    //DGR: 2012-07-29 : add nadgrids support (end)
    // Convert to geocentric coordinates.
    source.geodetic_to_geocentric(point);
    // CHECK_RETURN;
    // Convert between datums
    if (checkParams(source.datum_type)) {
      source.geocentric_to_wgs84(point);
      // CHECK_RETURN;
    }
    if (checkParams(dest.datum_type)) {
      dest.geocentric_from_wgs84(point);
      // CHECK_RETURN;
    }
    // Convert back to geodetic coordinates
    dest.geocentric_to_geodetic(point);
    // CHECK_RETURN;
  }
  // Apply grid shift to destination if required
  if (dest.datum_type === PJD_GRIDSHIFT) {
    this.apply_gridshift(dest, 1, point);
    // CHECK_RETURN;
  }

  source.a = src_a;
  source.es = src_es;
  dest.a = dst_a;
  dest.es = dst_es;

  return point;
};


},{}],"proj4/lib/defs":[function(require,module,exports){
var globals = require('./global');
var parseProj = require('./projString');
var wkt = require('./wkt');

function defs(name) {
  /*global console*/
  var that = this;
  if (arguments.length === 2) {
    var def = arguments[1];
    if (typeof def === 'string') {
      if (def.charAt(0) === '+') {
        defs[name] = parseProj(arguments[1]);
      }
      else {
        defs[name] = wkt(arguments[1]);
      }
    } else {
      defs[name] = def;
    }
  }
  else if (arguments.length === 1) {
    if (Array.isArray(name)) {
      return name.map(function(v) {
        if (Array.isArray(v)) {
          defs.apply(that, v);
        }
        else {
          defs(v);
        }
      });
    }
    else if (typeof name === 'string') {
      if (name in defs) {
        return defs[name];
      }
    }
    else if ('EPSG' in name) {
      defs['EPSG:' + name.EPSG] = name;
    }
    else if ('ESRI' in name) {
      defs['ESRI:' + name.ESRI] = name;
    }
    else if ('IAU2000' in name) {
      defs['IAU2000:' + name.IAU2000] = name;
    }
    else {
      console.log(name);
    }
    return;
  }


}
globals(defs);
module.exports = defs;

},{"./global":"proj4/lib/global","./projString":"proj4/lib/projString","./wkt":"proj4/lib/wkt"}],"proj4/lib/deriveConstants":[function(require,module,exports){
var Datum = require('./constants/Datum');
var Ellipsoid = require('./constants/Ellipsoid');
var extend = require('./extend');
var datum = require('./datum');
var EPSLN = 1.0e-10;
// ellipoid pj_set_ell.c
var SIXTH = 0.1666666666666666667;
/* 1/6 */
var RA4 = 0.04722222222222222222;
/* 17/360 */
var RA6 = 0.02215608465608465608;
module.exports = function(json) {
  // DGR 2011-03-20 : nagrids -> nadgrids
  if (json.datumCode && json.datumCode !== 'none') {
    var datumDef = Datum[json.datumCode];
    if (datumDef) {
      json.datum_params = datumDef.towgs84 ? datumDef.towgs84.split(',') : null;
      json.ellps = datumDef.ellipse;
      json.datumName = datumDef.datumName ? datumDef.datumName : json.datumCode;
    }
  }
  if (!json.a) { // do we have an ellipsoid?
    var ellipse = Ellipsoid[json.ellps] ? Ellipsoid[json.ellps] : Ellipsoid.WGS84;
    extend(json, ellipse);
  }
  if (json.rf && !json.b) {
    json.b = (1.0 - 1.0 / json.rf) * json.a;
  }
  if (json.rf === 0 || Math.abs(json.a - json.b) < EPSLN) {
    json.sphere = true;
    json.b = json.a;
  }
  json.a2 = json.a * json.a; // used in geocentric
  json.b2 = json.b * json.b; // used in geocentric
  json.es = (json.a2 - json.b2) / json.a2; // e ^ 2
  json.e = Math.sqrt(json.es); // eccentricity
  if (json.R_A) {
    json.a *= 1 - json.es * (SIXTH + json.es * (RA4 + json.es * RA6));
    json.a2 = json.a * json.a;
    json.b2 = json.b * json.b;
    json.es = 0;
  }
  json.ep2 = (json.a2 - json.b2) / json.b2; // used in geocentric
  if (!json.k0) {
    json.k0 = 1.0; //default value
  }
  //DGR 2010-11-12: axis
  if (!json.axis) {
    json.axis = "enu";
  }

  if (!json.datum) {
    json.datum = datum(json);
  }
  return json;
};

},{"./constants/Datum":"proj4/lib/constants/Datum","./constants/Ellipsoid":"proj4/lib/constants/Ellipsoid","./datum":"proj4/lib/datum","./extend":"proj4/lib/extend"}],"proj4/lib/extend":[function(require,module,exports){
module.exports = function(destination, source) {
  destination = destination || {};
  var value, property;
  if (!source) {
    return destination;
  }
  for (property in source) {
    value = source[property];
    if (value !== undefined) {
      destination[property] = value;
    }
  }
  return destination;
};

},{}],"proj4/lib/global":[function(require,module,exports){
module.exports = function(defs) {
  defs('EPSG:4326', "+title=WGS 84 (long/lat) +proj=longlat +ellps=WGS84 +datum=WGS84 +units=degrees");
  defs('EPSG:4269', "+title=NAD83 (long/lat) +proj=longlat +a=6378137.0 +b=6356752.31414036 +ellps=GRS80 +datum=NAD83 +units=degrees");
  defs('EPSG:3857', "+title=WGS 84 / Pseudo-Mercator +proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs");

  defs.WGS84 = defs['EPSG:4326'];
  defs['EPSG:3785'] = defs['EPSG:3857']; // maintain backward compat, official code is 3857
  defs.GOOGLE = defs['EPSG:3857'];
  defs['EPSG:900913'] = defs['EPSG:3857'];
  defs['EPSG:102113'] = defs['EPSG:3857'];
};

},{}],"proj4/lib/includedProjections":[function(require,module,exports){
var projs = [
  require('./projections/tmerc'),
  require('./projections/utm'),
  require('./projections/sterea'),
  require('./projections/stere'),
  require('./projections/somerc'),
  require('./projections/omerc'),
  require('./projections/lcc'),
  require('./projections/krovak'),
  require('./projections/cass'),
  require('./projections/laea'),
  require('./projections/aea'),
  require('./projections/gnom'),
  require('./projections/cea'),
  require('./projections/eqc'),
  require('./projections/poly'),
  require('./projections/nzmg'),
  require('./projections/mill'),
  require('./projections/sinu'),
  require('./projections/moll'),
  require('./projections/eqdc'),
  require('./projections/vandg'),
  require('./projections/aeqd')
];
module.exports = function(proj4){
  projs.forEach(function(proj){
    proj4.Proj.projections.add(proj);
  });
};
},{"./projections/aea":"proj4/lib/projections/aea","./projections/aeqd":"proj4/lib/projections/aeqd","./projections/cass":"proj4/lib/projections/cass","./projections/cea":"proj4/lib/projections/cea","./projections/eqc":"proj4/lib/projections/eqc","./projections/eqdc":"proj4/lib/projections/eqdc","./projections/gnom":"proj4/lib/projections/gnom","./projections/krovak":"proj4/lib/projections/krovak","./projections/laea":"proj4/lib/projections/laea","./projections/lcc":"proj4/lib/projections/lcc","./projections/mill":"proj4/lib/projections/mill","./projections/moll":"proj4/lib/projections/moll","./projections/nzmg":"proj4/lib/projections/nzmg","./projections/omerc":"proj4/lib/projections/omerc","./projections/poly":"proj4/lib/projections/poly","./projections/sinu":"proj4/lib/projections/sinu","./projections/somerc":"proj4/lib/projections/somerc","./projections/stere":"proj4/lib/projections/stere","./projections/sterea":"proj4/lib/projections/sterea","./projections/tmerc":"proj4/lib/projections/tmerc","./projections/utm":"proj4/lib/projections/utm","./projections/vandg":"proj4/lib/projections/vandg"}],"proj4":[function(require,module,exports){
var proj4 = require('./core');
proj4.defaultDatum = 'WGS84'; //default datum
proj4.Proj = require('./Proj');
proj4.WGS84 = new proj4.Proj('WGS84');
proj4.Point = require('./Point');
proj4.toPoint = require("./common/toPoint");
proj4.defs = require('./defs');
proj4.transform = require('./transform');
proj4.mgrs = require('mgrs');
proj4.version = require('../package.json').version;
require('./includedProjections')(proj4);
module.exports = proj4;
},{"../package.json":"proj4/package.json","./Point":"proj4/lib/Point","./Proj":"proj4/lib/Proj","./common/toPoint":"proj4/lib/common/toPoint","./core":"proj4/lib/core","./defs":"proj4/lib/defs","./includedProjections":"proj4/lib/includedProjections","./transform":"proj4/lib/transform","mgrs":"proj4/node_modules/mgrs/mgrs"}],"proj4/lib/parseCode":[function(require,module,exports){
var defs = require('./defs');
var wkt = require('./wkt');
var projStr = require('./projString');
function testObj(code){
  return typeof code === 'string';
}
function testDef(code){
  return code in defs;
}
function testWKT(code){
  var codeWords = ['GEOGCS','GEOCCS','PROJCS','LOCAL_CS'];
  return codeWords.reduce(function(a,b){
    return a+1+code.indexOf(b);
  },0);
}
function testProj(code){
  return code[0] === '+';
}
function parse(code){
  if (testObj(code)) {
    //check to see if this is a WKT string
    if (testDef(code)) {
      return defs[code];
    }
    else if (testWKT(code)) {
      return wkt(code);
    }
    else if (testProj(code)) {
      return projStr(code);
    }
  }else{
    return code;
  }
}

module.exports = parse;
},{"./defs":"proj4/lib/defs","./projString":"proj4/lib/projString","./wkt":"proj4/lib/wkt"}],"proj4/lib/projString":[function(require,module,exports){
var D2R = 0.01745329251994329577;
var PrimeMeridian = require('./constants/PrimeMeridian');
var units = require('./constants/units');

module.exports = function(defData) {
  var self = {};
  var paramObj = {};
  defData.split("+").map(function(v) {
    return v.trim();
  }).filter(function(a) {
    return a;
  }).forEach(function(a) {
    var split = a.split("=");
    split.push(true);
    paramObj[split[0].toLowerCase()] = split[1];
  });
  var paramName, paramVal, paramOutname;
  var params = {
    proj: 'projName',
    datum: 'datumCode',
    rf: function(v) {
      self.rf = parseFloat(v);
    },
    lat_0: function(v) {
      self.lat0 = v * D2R;
    },
    lat_1: function(v) {
      self.lat1 = v * D2R;
    },
    lat_2: function(v) {
      self.lat2 = v * D2R;
    },
    lat_ts: function(v) {
      self.lat_ts = v * D2R;
    },
    lon_0: function(v) {
      self.long0 = v * D2R;
    },
    lon_1: function(v) {
      self.long1 = v * D2R;
    },
    lon_2: function(v) {
      self.long2 = v * D2R;
    },
    alpha: function(v) {
      self.alpha = parseFloat(v) * D2R;
    },
    lonc: function(v) {
      self.longc = v * D2R;
    },
    x_0: function(v) {
      self.x0 = parseFloat(v);
    },
    y_0: function(v) {
      self.y0 = parseFloat(v);
    },
    k_0: function(v) {
      self.k0 = parseFloat(v);
    },
    k: function(v) {
      self.k0 = parseFloat(v);
    },
    a: function(v) {
      self.a = parseFloat(v);
    },
    b: function(v) {
      self.b = parseFloat(v);
    },
    r_a: function() {
      self.R_A = true;
    },
    zone: function(v) {
      self.zone = parseInt(v, 10);
    },
    south: function() {
      self.utmSouth = true;
    },
    towgs84: function(v) {
      self.datum_params = v.split(",").map(function(a) {
        return parseFloat(a);
      });
    },
    to_meter: function(v) {
      self.to_meter = parseFloat(v);
    },
    units: function(v) {
      self.units = v;
      if (units[v]) {
        self.to_meter = units[v].to_meter;
      }
    },
    from_greenwich: function(v) {
      self.from_greenwich = v * D2R;
    },
    pm: function(v) {
      self.from_greenwich = (PrimeMeridian[v] ? PrimeMeridian[v] : parseFloat(v)) * D2R;
    },
    nadgrids: function(v) {
      if (v === '@null') {
        self.datumCode = 'none';
      }
      else {
        self.nadgrids = v;
      }
    },
    axis: function(v) {
      var legalAxis = "ewnsud";
      if (v.length === 3 && legalAxis.indexOf(v.substr(0, 1)) !== -1 && legalAxis.indexOf(v.substr(1, 1)) !== -1 && legalAxis.indexOf(v.substr(2, 1)) !== -1) {
        self.axis = v;
      }
    }
  };
  for (paramName in paramObj) {
    paramVal = paramObj[paramName];
    if (paramName in params) {
      paramOutname = params[paramName];
      if (typeof paramOutname === 'function') {
        paramOutname(paramVal);
      }
      else {
        self[paramOutname] = paramVal;
      }
    }
    else {
      self[paramName] = paramVal;
    }
  }
  if(typeof self.datumCode === 'string' && self.datumCode !== "WGS84"){
    self.datumCode = self.datumCode.toLowerCase();
  }
  return self;
};

},{"./constants/PrimeMeridian":"proj4/lib/constants/PrimeMeridian","./constants/units":"proj4/lib/constants/units"}],"proj4/lib/projections":[function(require,module,exports){
var projs = [
  require('./projections/merc'),
  require('./projections/longlat')
];
var names = {};
var projStore = [];

function add(proj, i) {
  var len = projStore.length;
  if (!proj.names) {
    console.log(i);
    return true;
  }
  projStore[len] = proj;
  proj.names.forEach(function(n) {
    names[n.toLowerCase()] = len;
  });
  return this;
}

exports.add = add;

exports.get = function(name) {
  if (!name) {
    return false;
  }
  var n = name.toLowerCase();
  if (typeof names[n] !== 'undefined' && projStore[names[n]]) {
    return projStore[names[n]];
  }
};
exports.start = function() {
  projs.forEach(add);
};

},{"./projections/longlat":"proj4/lib/projections/longlat","./projections/merc":"proj4/lib/projections/merc"}],"proj4/lib/projections/aea":[function(require,module,exports){
var EPSLN = 1.0e-10;
var msfnz = require('../common/msfnz');
var qsfnz = require('../common/qsfnz');
var adjust_lon = require('../common/adjust_lon');
var asinz = require('../common/asinz');
exports.init = function() {

  if (Math.abs(this.lat1 + this.lat2) < EPSLN) {
    return;
  }
  this.temp = this.b / this.a;
  this.es = 1 - Math.pow(this.temp, 2);
  this.e3 = Math.sqrt(this.es);

  this.sin_po = Math.sin(this.lat1);
  this.cos_po = Math.cos(this.lat1);
  this.t1 = this.sin_po;
  this.con = this.sin_po;
  this.ms1 = msfnz(this.e3, this.sin_po, this.cos_po);
  this.qs1 = qsfnz(this.e3, this.sin_po, this.cos_po);

  this.sin_po = Math.sin(this.lat2);
  this.cos_po = Math.cos(this.lat2);
  this.t2 = this.sin_po;
  this.ms2 = msfnz(this.e3, this.sin_po, this.cos_po);
  this.qs2 = qsfnz(this.e3, this.sin_po, this.cos_po);

  this.sin_po = Math.sin(this.lat0);
  this.cos_po = Math.cos(this.lat0);
  this.t3 = this.sin_po;
  this.qs0 = qsfnz(this.e3, this.sin_po, this.cos_po);

  if (Math.abs(this.lat1 - this.lat2) > EPSLN) {
    this.ns0 = (this.ms1 * this.ms1 - this.ms2 * this.ms2) / (this.qs2 - this.qs1);
  }
  else {
    this.ns0 = this.con;
  }
  this.c = this.ms1 * this.ms1 + this.ns0 * this.qs1;
  this.rh = this.a * Math.sqrt(this.c - this.ns0 * this.qs0) / this.ns0;
};

/* Albers Conical Equal Area forward equations--mapping lat,long to x,y
  -------------------------------------------------------------------*/
exports.forward = function(p) {

  var lon = p.x;
  var lat = p.y;

  this.sin_phi = Math.sin(lat);
  this.cos_phi = Math.cos(lat);

  var qs = qsfnz(this.e3, this.sin_phi, this.cos_phi);
  var rh1 = this.a * Math.sqrt(this.c - this.ns0 * qs) / this.ns0;
  var theta = this.ns0 * adjust_lon(lon - this.long0);
  var x = rh1 * Math.sin(theta) + this.x0;
  var y = this.rh - rh1 * Math.cos(theta) + this.y0;

  p.x = x;
  p.y = y;
  return p;
};


exports.inverse = function(p) {
  var rh1, qs, con, theta, lon, lat;

  p.x -= this.x0;
  p.y = this.rh - p.y + this.y0;
  if (this.ns0 >= 0) {
    rh1 = Math.sqrt(p.x * p.x + p.y * p.y);
    con = 1;
  }
  else {
    rh1 = -Math.sqrt(p.x * p.x + p.y * p.y);
    con = -1;
  }
  theta = 0;
  if (rh1 !== 0) {
    theta = Math.atan2(con * p.x, con * p.y);
  }
  con = rh1 * this.ns0 / this.a;
  if (this.sphere) {
    lat = Math.asin((this.c - con * con) / (2 * this.ns0));
  }
  else {
    qs = (this.c - con * con) / this.ns0;
    lat = this.phi1z(this.e3, qs);
  }

  lon = adjust_lon(theta / this.ns0 + this.long0);
  p.x = lon;
  p.y = lat;
  return p;
};

/* Function to compute phi1, the latitude for the inverse of the
   Albers Conical Equal-Area projection.
-------------------------------------------*/
exports.phi1z = function(eccent, qs) {
  var sinphi, cosphi, con, com, dphi;
  var phi = asinz(0.5 * qs);
  if (eccent < EPSLN) {
    return phi;
  }

  var eccnts = eccent * eccent;
  for (var i = 1; i <= 25; i++) {
    sinphi = Math.sin(phi);
    cosphi = Math.cos(phi);
    con = eccent * sinphi;
    com = 1 - con * con;
    dphi = 0.5 * com * com / cosphi * (qs / (1 - eccnts) - sinphi / com + 0.5 / eccent * Math.log((1 - con) / (1 + con)));
    phi = phi + dphi;
    if (Math.abs(dphi) <= 1e-7) {
      return phi;
    }
  }
  return null;
};
exports.names = ["Albers_Conic_Equal_Area", "Albers", "aea"];

},{"../common/adjust_lon":"proj4/lib/common/adjust_lon","../common/asinz":"proj4/lib/common/asinz","../common/msfnz":"proj4/lib/common/msfnz","../common/qsfnz":"proj4/lib/common/qsfnz"}],"proj4/lib/projections/aeqd":[function(require,module,exports){
var adjust_lon = require('../common/adjust_lon');
var HALF_PI = Math.PI/2;
var EPSLN = 1.0e-10;
var mlfn = require('../common/mlfn');
var e0fn = require('../common/e0fn');
var e1fn = require('../common/e1fn');
var e2fn = require('../common/e2fn');
var e3fn = require('../common/e3fn');
var gN = require('../common/gN');
var asinz = require('../common/asinz');
var imlfn = require('../common/imlfn');
exports.init = function() {
  this.sin_p12 = Math.sin(this.lat0);
  this.cos_p12 = Math.cos(this.lat0);
};

exports.forward = function(p) {
  var lon = p.x;
  var lat = p.y;
  var sinphi = Math.sin(p.y);
  var cosphi = Math.cos(p.y);
  var dlon = adjust_lon(lon - this.long0);
  var e0, e1, e2, e3, Mlp, Ml, tanphi, Nl1, Nl, psi, Az, G, H, GH, Hs, c, kp, cos_c, s, s2, s3, s4, s5;
  if (this.sphere) {
    if (Math.abs(this.sin_p12 - 1) <= EPSLN) {
      //North Pole case
      p.x = this.x0 + this.a * (HALF_PI - lat) * Math.sin(dlon);
      p.y = this.y0 - this.a * (HALF_PI - lat) * Math.cos(dlon);
      return p;
    }
    else if (Math.abs(this.sin_p12 + 1) <= EPSLN) {
      //South Pole case
      p.x = this.x0 + this.a * (HALF_PI + lat) * Math.sin(dlon);
      p.y = this.y0 + this.a * (HALF_PI + lat) * Math.cos(dlon);
      return p;
    }
    else {
      //default case
      cos_c = this.sin_p12 * sinphi + this.cos_p12 * cosphi * Math.cos(dlon);
      c = Math.acos(cos_c);
      kp = c / Math.sin(c);
      p.x = this.x0 + this.a * kp * cosphi * Math.sin(dlon);
      p.y = this.y0 + this.a * kp * (this.cos_p12 * sinphi - this.sin_p12 * cosphi * Math.cos(dlon));
      return p;
    }
  }
  else {
    e0 = e0fn(this.es);
    e1 = e1fn(this.es);
    e2 = e2fn(this.es);
    e3 = e3fn(this.es);
    if (Math.abs(this.sin_p12 - 1) <= EPSLN) {
      //North Pole case
      Mlp = this.a * mlfn(e0, e1, e2, e3, HALF_PI);
      Ml = this.a * mlfn(e0, e1, e2, e3, lat);
      p.x = this.x0 + (Mlp - Ml) * Math.sin(dlon);
      p.y = this.y0 - (Mlp - Ml) * Math.cos(dlon);
      return p;
    }
    else if (Math.abs(this.sin_p12 + 1) <= EPSLN) {
      //South Pole case
      Mlp = this.a * mlfn(e0, e1, e2, e3, HALF_PI);
      Ml = this.a * mlfn(e0, e1, e2, e3, lat);
      p.x = this.x0 + (Mlp + Ml) * Math.sin(dlon);
      p.y = this.y0 + (Mlp + Ml) * Math.cos(dlon);
      return p;
    }
    else {
      //Default case
      tanphi = sinphi / cosphi;
      Nl1 = gN(this.a, this.e, this.sin_p12);
      Nl = gN(this.a, this.e, sinphi);
      psi = Math.atan((1 - this.es) * tanphi + this.es * Nl1 * this.sin_p12 / (Nl * cosphi));
      Az = Math.atan2(Math.sin(dlon), this.cos_p12 * Math.tan(psi) - this.sin_p12 * Math.cos(dlon));
      if (Az === 0) {
        s = Math.asin(this.cos_p12 * Math.sin(psi) - this.sin_p12 * Math.cos(psi));
      }
      else if (Math.abs(Math.abs(Az) - Math.PI) <= EPSLN) {
        s = -Math.asin(this.cos_p12 * Math.sin(psi) - this.sin_p12 * Math.cos(psi));
      }
      else {
        s = Math.asin(Math.sin(dlon) * Math.cos(psi) / Math.sin(Az));
      }
      G = this.e * this.sin_p12 / Math.sqrt(1 - this.es);
      H = this.e * this.cos_p12 * Math.cos(Az) / Math.sqrt(1 - this.es);
      GH = G * H;
      Hs = H * H;
      s2 = s * s;
      s3 = s2 * s;
      s4 = s3 * s;
      s5 = s4 * s;
      c = Nl1 * s * (1 - s2 * Hs * (1 - Hs) / 6 + s3 / 8 * GH * (1 - 2 * Hs) + s4 / 120 * (Hs * (4 - 7 * Hs) - 3 * G * G * (1 - 7 * Hs)) - s5 / 48 * GH);
      p.x = this.x0 + c * Math.sin(Az);
      p.y = this.y0 + c * Math.cos(Az);
      return p;
    }
  }


};

exports.inverse = function(p) {
  p.x -= this.x0;
  p.y -= this.y0;
  var rh, z, sinz, cosz, lon, lat, con, e0, e1, e2, e3, Mlp, M, N1, psi, Az, cosAz, tmp, A, B, D, Ee, F;
  if (this.sphere) {
    rh = Math.sqrt(p.x * p.x + p.y * p.y);
    if (rh > (2 * HALF_PI * this.a)) {
      return;
    }
    z = rh / this.a;

    sinz = Math.sin(z);
    cosz = Math.cos(z);

    lon = this.long0;
    if (Math.abs(rh) <= EPSLN) {
      lat = this.lat0;
    }
    else {
      lat = asinz(cosz * this.sin_p12 + (p.y * sinz * this.cos_p12) / rh);
      con = Math.abs(this.lat0) - HALF_PI;
      if (Math.abs(con) <= EPSLN) {
        if (this.lat0 >= 0) {
          lon = adjust_lon(this.long0 + Math.atan2(p.x, - p.y));
        }
        else {
          lon = adjust_lon(this.long0 - Math.atan2(-p.x, p.y));
        }
      }
      else {
        /*con = cosz - this.sin_p12 * Math.sin(lat);
        if ((Math.abs(con) < EPSLN) && (Math.abs(p.x) < EPSLN)) {
          //no-op, just keep the lon value as is
        } else {
          var temp = Math.atan2((p.x * sinz * this.cos_p12), (con * rh));
          lon = adjust_lon(this.long0 + Math.atan2((p.x * sinz * this.cos_p12), (con * rh)));
        }*/
        lon = adjust_lon(this.long0 + Math.atan2(p.x * sinz, rh * this.cos_p12 * cosz - p.y * this.sin_p12 * sinz));
      }
    }

    p.x = lon;
    p.y = lat;
    return p;
  }
  else {
    e0 = e0fn(this.es);
    e1 = e1fn(this.es);
    e2 = e2fn(this.es);
    e3 = e3fn(this.es);
    if (Math.abs(this.sin_p12 - 1) <= EPSLN) {
      //North pole case
      Mlp = this.a * mlfn(e0, e1, e2, e3, HALF_PI);
      rh = Math.sqrt(p.x * p.x + p.y * p.y);
      M = Mlp - rh;
      lat = imlfn(M / this.a, e0, e1, e2, e3);
      lon = adjust_lon(this.long0 + Math.atan2(p.x, - 1 * p.y));
      p.x = lon;
      p.y = lat;
      return p;
    }
    else if (Math.abs(this.sin_p12 + 1) <= EPSLN) {
      //South pole case
      Mlp = this.a * mlfn(e0, e1, e2, e3, HALF_PI);
      rh = Math.sqrt(p.x * p.x + p.y * p.y);
      M = rh - Mlp;

      lat = imlfn(M / this.a, e0, e1, e2, e3);
      lon = adjust_lon(this.long0 + Math.atan2(p.x, p.y));
      p.x = lon;
      p.y = lat;
      return p;
    }
    else {
      //default case
      rh = Math.sqrt(p.x * p.x + p.y * p.y);
      Az = Math.atan2(p.x, p.y);
      N1 = gN(this.a, this.e, this.sin_p12);
      cosAz = Math.cos(Az);
      tmp = this.e * this.cos_p12 * cosAz;
      A = -tmp * tmp / (1 - this.es);
      B = 3 * this.es * (1 - A) * this.sin_p12 * this.cos_p12 * cosAz / (1 - this.es);
      D = rh / N1;
      Ee = D - A * (1 + A) * Math.pow(D, 3) / 6 - B * (1 + 3 * A) * Math.pow(D, 4) / 24;
      F = 1 - A * Ee * Ee / 2 - D * Ee * Ee * Ee / 6;
      psi = Math.asin(this.sin_p12 * Math.cos(Ee) + this.cos_p12 * Math.sin(Ee) * cosAz);
      lon = adjust_lon(this.long0 + Math.asin(Math.sin(Az) * Math.sin(Ee) / Math.cos(psi)));
      lat = Math.atan((1 - this.es * F * this.sin_p12 / Math.sin(psi)) * Math.tan(psi) / (1 - this.es));
      p.x = lon;
      p.y = lat;
      return p;
    }
  }

};
exports.names = ["Azimuthal_Equidistant", "aeqd"];

},{"../common/adjust_lon":"proj4/lib/common/adjust_lon","../common/asinz":"proj4/lib/common/asinz","../common/e0fn":"proj4/lib/common/e0fn","../common/e1fn":"proj4/lib/common/e1fn","../common/e2fn":"proj4/lib/common/e2fn","../common/e3fn":"proj4/lib/common/e3fn","../common/gN":"proj4/lib/common/gN","../common/imlfn":"proj4/lib/common/imlfn","../common/mlfn":"proj4/lib/common/mlfn"}],"proj4/lib/projections/cass":[function(require,module,exports){
var mlfn = require('../common/mlfn');
var e0fn = require('../common/e0fn');
var e1fn = require('../common/e1fn');
var e2fn = require('../common/e2fn');
var e3fn = require('../common/e3fn');
var gN = require('../common/gN');
var adjust_lon = require('../common/adjust_lon');
var adjust_lat = require('../common/adjust_lat');
var imlfn = require('../common/imlfn');
var HALF_PI = Math.PI/2;
var EPSLN = 1.0e-10;
exports.init = function() {
  if (!this.sphere) {
    this.e0 = e0fn(this.es);
    this.e1 = e1fn(this.es);
    this.e2 = e2fn(this.es);
    this.e3 = e3fn(this.es);
    this.ml0 = this.a * mlfn(this.e0, this.e1, this.e2, this.e3, this.lat0);
  }
};



/* Cassini forward equations--mapping lat,long to x,y
  -----------------------------------------------------------------------*/
exports.forward = function(p) {

  /* Forward equations
      -----------------*/
  var x, y;
  var lam = p.x;
  var phi = p.y;
  lam = adjust_lon(lam - this.long0);

  if (this.sphere) {
    x = this.a * Math.asin(Math.cos(phi) * Math.sin(lam));
    y = this.a * (Math.atan2(Math.tan(phi), Math.cos(lam)) - this.lat0);
  }
  else {
    //ellipsoid
    var sinphi = Math.sin(phi);
    var cosphi = Math.cos(phi);
    var nl = gN(this.a, this.e, sinphi);
    var tl = Math.tan(phi) * Math.tan(phi);
    var al = lam * Math.cos(phi);
    var asq = al * al;
    var cl = this.es * cosphi * cosphi / (1 - this.es);
    var ml = this.a * mlfn(this.e0, this.e1, this.e2, this.e3, phi);

    x = nl * al * (1 - asq * tl * (1 / 6 - (8 - tl + 8 * cl) * asq / 120));
    y = ml - this.ml0 + nl * sinphi / cosphi * asq * (0.5 + (5 - tl + 6 * cl) * asq / 24);


  }

  p.x = x + this.x0;
  p.y = y + this.y0;
  return p;
};

/* Inverse equations
  -----------------*/
exports.inverse = function(p) {
  p.x -= this.x0;
  p.y -= this.y0;
  var x = p.x / this.a;
  var y = p.y / this.a;
  var phi, lam;

  if (this.sphere) {
    var dd = y + this.lat0;
    phi = Math.asin(Math.sin(dd) * Math.cos(x));
    lam = Math.atan2(Math.tan(x), Math.cos(dd));
  }
  else {
    /* ellipsoid */
    var ml1 = this.ml0 / this.a + y;
    var phi1 = imlfn(ml1, this.e0, this.e1, this.e2, this.e3);
    if (Math.abs(Math.abs(phi1) - HALF_PI) <= EPSLN) {
      p.x = this.long0;
      p.y = HALF_PI;
      if (y < 0) {
        p.y *= -1;
      }
      return p;
    }
    var nl1 = gN(this.a, this.e, Math.sin(phi1));

    var rl1 = nl1 * nl1 * nl1 / this.a / this.a * (1 - this.es);
    var tl1 = Math.pow(Math.tan(phi1), 2);
    var dl = x * this.a / nl1;
    var dsq = dl * dl;
    phi = phi1 - nl1 * Math.tan(phi1) / rl1 * dl * dl * (0.5 - (1 + 3 * tl1) * dl * dl / 24);
    lam = dl * (1 - dsq * (tl1 / 3 + (1 + 3 * tl1) * tl1 * dsq / 15)) / Math.cos(phi1);

  }

  p.x = adjust_lon(lam + this.long0);
  p.y = adjust_lat(phi);
  return p;

};
exports.names = ["Cassini", "Cassini_Soldner", "cass"];
},{"../common/adjust_lat":"proj4/lib/common/adjust_lat","../common/adjust_lon":"proj4/lib/common/adjust_lon","../common/e0fn":"proj4/lib/common/e0fn","../common/e1fn":"proj4/lib/common/e1fn","../common/e2fn":"proj4/lib/common/e2fn","../common/e3fn":"proj4/lib/common/e3fn","../common/gN":"proj4/lib/common/gN","../common/imlfn":"proj4/lib/common/imlfn","../common/mlfn":"proj4/lib/common/mlfn"}],"proj4/lib/projections/cea":[function(require,module,exports){
var adjust_lon = require('../common/adjust_lon');
var qsfnz = require('../common/qsfnz');
var msfnz = require('../common/msfnz');
var iqsfnz = require('../common/iqsfnz');
/*
  reference:  
    "Cartographic Projection Procedures for the UNIX Environment-
    A User's Manual" by Gerald I. Evenden,
    USGS Open File Report 90-284and Release 4 Interim Reports (2003)
*/
exports.init = function() {
  //no-op
  if (!this.sphere) {
    this.k0 = msfnz(this.e, Math.sin(this.lat_ts), Math.cos(this.lat_ts));
  }
};


/* Cylindrical Equal Area forward equations--mapping lat,long to x,y
    ------------------------------------------------------------*/
exports.forward = function(p) {
  var lon = p.x;
  var lat = p.y;
  var x, y;
  /* Forward equations
      -----------------*/
  var dlon = adjust_lon(lon - this.long0);
  if (this.sphere) {
    x = this.x0 + this.a * dlon * Math.cos(this.lat_ts);
    y = this.y0 + this.a * Math.sin(lat) / Math.cos(this.lat_ts);
  }
  else {
    var qs = qsfnz(this.e, Math.sin(lat));
    x = this.x0 + this.a * this.k0 * dlon;
    y = this.y0 + this.a * qs * 0.5 / this.k0;
  }

  p.x = x;
  p.y = y;
  return p;
};

/* Cylindrical Equal Area inverse equations--mapping x,y to lat/long
    ------------------------------------------------------------*/
exports.inverse = function(p) {
  p.x -= this.x0;
  p.y -= this.y0;
  var lon, lat;

  if (this.sphere) {
    lon = adjust_lon(this.long0 + (p.x / this.a) / Math.cos(this.lat_ts));
    lat = Math.asin((p.y / this.a) * Math.cos(this.lat_ts));
  }
  else {
    lat = iqsfnz(this.e, 2 * p.y * this.k0 / this.a);
    lon = adjust_lon(this.long0 + p.x / (this.a * this.k0));
  }

  p.x = lon;
  p.y = lat;
  return p;
};
exports.names = ["cea"];

},{"../common/adjust_lon":"proj4/lib/common/adjust_lon","../common/iqsfnz":"proj4/lib/common/iqsfnz","../common/msfnz":"proj4/lib/common/msfnz","../common/qsfnz":"proj4/lib/common/qsfnz"}],"proj4/lib/projections/eqc":[function(require,module,exports){
var adjust_lon = require('../common/adjust_lon');
var adjust_lat = require('../common/adjust_lat');
exports.init = function() {

  this.x0 = this.x0 || 0;
  this.y0 = this.y0 || 0;
  this.lat0 = this.lat0 || 0;
  this.long0 = this.long0 || 0;
  this.lat_ts = this.lat_ts || 0;
  this.title = this.title || "Equidistant Cylindrical (Plate Carre)";

  this.rc = Math.cos(this.lat_ts);
};


// forward equations--mapping lat,long to x,y
// -----------------------------------------------------------------
exports.forward = function(p) {

  var lon = p.x;
  var lat = p.y;

  var dlon = adjust_lon(lon - this.long0);
  var dlat = adjust_lat(lat - this.lat0);
  p.x = this.x0 + (this.a * dlon * this.rc);
  p.y = this.y0 + (this.a * dlat);
  return p;
};

// inverse equations--mapping x,y to lat/long
// -----------------------------------------------------------------
exports.inverse = function(p) {

  var x = p.x;
  var y = p.y;

  p.x = adjust_lon(this.long0 + ((x - this.x0) / (this.a * this.rc)));
  p.y = adjust_lat(this.lat0 + ((y - this.y0) / (this.a)));
  return p;
};
exports.names = ["Equirectangular", "Equidistant_Cylindrical", "eqc"];

},{"../common/adjust_lat":"proj4/lib/common/adjust_lat","../common/adjust_lon":"proj4/lib/common/adjust_lon"}],"proj4/lib/projections/eqdc":[function(require,module,exports){
var e0fn = require('../common/e0fn');
var e1fn = require('../common/e1fn');
var e2fn = require('../common/e2fn');
var e3fn = require('../common/e3fn');
var msfnz = require('../common/msfnz');
var mlfn = require('../common/mlfn');
var adjust_lon = require('../common/adjust_lon');
var adjust_lat = require('../common/adjust_lat');
var imlfn = require('../common/imlfn');
var EPSLN = 1.0e-10;
exports.init = function() {

  /* Place parameters in static storage for common use
      -------------------------------------------------*/
  // Standard Parallels cannot be equal and on opposite sides of the equator
  if (Math.abs(this.lat1 + this.lat2) < EPSLN) {
    return;
  }
  this.lat2 = this.lat2 || this.lat1;
  this.temp = this.b / this.a;
  this.es = 1 - Math.pow(this.temp, 2);
  this.e = Math.sqrt(this.es);
  this.e0 = e0fn(this.es);
  this.e1 = e1fn(this.es);
  this.e2 = e2fn(this.es);
  this.e3 = e3fn(this.es);

  this.sinphi = Math.sin(this.lat1);
  this.cosphi = Math.cos(this.lat1);

  this.ms1 = msfnz(this.e, this.sinphi, this.cosphi);
  this.ml1 = mlfn(this.e0, this.e1, this.e2, this.e3, this.lat1);

  if (Math.abs(this.lat1 - this.lat2) < EPSLN) {
    this.ns = this.sinphi;
  }
  else {
    this.sinphi = Math.sin(this.lat2);
    this.cosphi = Math.cos(this.lat2);
    this.ms2 = msfnz(this.e, this.sinphi, this.cosphi);
    this.ml2 = mlfn(this.e0, this.e1, this.e2, this.e3, this.lat2);
    this.ns = (this.ms1 - this.ms2) / (this.ml2 - this.ml1);
  }
  this.g = this.ml1 + this.ms1 / this.ns;
  this.ml0 = mlfn(this.e0, this.e1, this.e2, this.e3, this.lat0);
  this.rh = this.a * (this.g - this.ml0);
};


/* Equidistant Conic forward equations--mapping lat,long to x,y
  -----------------------------------------------------------*/
exports.forward = function(p) {
  var lon = p.x;
  var lat = p.y;
  var rh1;

  /* Forward equations
      -----------------*/
  if (this.sphere) {
    rh1 = this.a * (this.g - lat);
  }
  else {
    var ml = mlfn(this.e0, this.e1, this.e2, this.e3, lat);
    rh1 = this.a * (this.g - ml);
  }
  var theta = this.ns * adjust_lon(lon - this.long0);
  var x = this.x0 + rh1 * Math.sin(theta);
  var y = this.y0 + this.rh - rh1 * Math.cos(theta);
  p.x = x;
  p.y = y;
  return p;
};

/* Inverse equations
  -----------------*/
exports.inverse = function(p) {
  p.x -= this.x0;
  p.y = this.rh - p.y + this.y0;
  var con, rh1, lat, lon;
  if (this.ns >= 0) {
    rh1 = Math.sqrt(p.x * p.x + p.y * p.y);
    con = 1;
  }
  else {
    rh1 = -Math.sqrt(p.x * p.x + p.y * p.y);
    con = -1;
  }
  var theta = 0;
  if (rh1 !== 0) {
    theta = Math.atan2(con * p.x, con * p.y);
  }

  if (this.sphere) {
    lon = adjust_lon(this.long0 + theta / this.ns);
    lat = adjust_lat(this.g - rh1 / this.a);
    p.x = lon;
    p.y = lat;
    return p;
  }
  else {
    var ml = this.g - rh1 / this.a;
    lat = imlfn(ml, this.e0, this.e1, this.e2, this.e3);
    lon = adjust_lon(this.long0 + theta / this.ns);
    p.x = lon;
    p.y = lat;
    return p;
  }

};
exports.names = ["Equidistant_Conic", "eqdc"];

},{"../common/adjust_lat":"proj4/lib/common/adjust_lat","../common/adjust_lon":"proj4/lib/common/adjust_lon","../common/e0fn":"proj4/lib/common/e0fn","../common/e1fn":"proj4/lib/common/e1fn","../common/e2fn":"proj4/lib/common/e2fn","../common/e3fn":"proj4/lib/common/e3fn","../common/imlfn":"proj4/lib/common/imlfn","../common/mlfn":"proj4/lib/common/mlfn","../common/msfnz":"proj4/lib/common/msfnz"}],"proj4/lib/projections/gauss":[function(require,module,exports){
var FORTPI = Math.PI/4;
var srat = require('../common/srat');
var HALF_PI = Math.PI/2;
var MAX_ITER = 20;
exports.init = function() {
  var sphi = Math.sin(this.lat0);
  var cphi = Math.cos(this.lat0);
  cphi *= cphi;
  this.rc = Math.sqrt(1 - this.es) / (1 - this.es * sphi * sphi);
  this.C = Math.sqrt(1 + this.es * cphi * cphi / (1 - this.es));
  this.phic0 = Math.asin(sphi / this.C);
  this.ratexp = 0.5 * this.C * this.e;
  this.K = Math.tan(0.5 * this.phic0 + FORTPI) / (Math.pow(Math.tan(0.5 * this.lat0 + FORTPI), this.C) * srat(this.e * sphi, this.ratexp));
};

exports.forward = function(p) {
  var lon = p.x;
  var lat = p.y;

  p.y = 2 * Math.atan(this.K * Math.pow(Math.tan(0.5 * lat + FORTPI), this.C) * srat(this.e * Math.sin(lat), this.ratexp)) - HALF_PI;
  p.x = this.C * lon;
  return p;
};

exports.inverse = function(p) {
  var DEL_TOL = 1e-14;
  var lon = p.x / this.C;
  var lat = p.y;
  var num = Math.pow(Math.tan(0.5 * lat + FORTPI) / this.K, 1 / this.C);
  for (var i = MAX_ITER; i > 0; --i) {
    lat = 2 * Math.atan(num * srat(this.e * Math.sin(p.y), - 0.5 * this.e)) - HALF_PI;
    if (Math.abs(lat - p.y) < DEL_TOL) {
      break;
    }
    p.y = lat;
  }
  /* convergence failed */
  if (!i) {
    return null;
  }
  p.x = lon;
  p.y = lat;
  return p;
};
exports.names = ["gauss"];

},{"../common/srat":"proj4/lib/common/srat"}],"proj4/lib/projections/gnom":[function(require,module,exports){
var adjust_lon = require('../common/adjust_lon');
var EPSLN = 1.0e-10;
var asinz = require('../common/asinz');

/*
  reference:
    Wolfram Mathworld "Gnomonic Projection"
    http://mathworld.wolfram.com/GnomonicProjection.html
    Accessed: 12th November 2009
  */
exports.init = function() {

  /* Place parameters in static storage for common use
      -------------------------------------------------*/
  this.sin_p14 = Math.sin(this.lat0);
  this.cos_p14 = Math.cos(this.lat0);
  // Approximation for projecting points to the horizon (infinity)
  this.infinity_dist = 1000 * this.a;
  this.rc = 1;
};


/* Gnomonic forward equations--mapping lat,long to x,y
    ---------------------------------------------------*/
exports.forward = function(p) {
  var sinphi, cosphi; /* sin and cos value        */
  var dlon; /* delta longitude value      */
  var coslon; /* cos of longitude        */
  var ksp; /* scale factor          */
  var g;
  var x, y;
  var lon = p.x;
  var lat = p.y;
  /* Forward equations
      -----------------*/
  dlon = adjust_lon(lon - this.long0);

  sinphi = Math.sin(lat);
  cosphi = Math.cos(lat);

  coslon = Math.cos(dlon);
  g = this.sin_p14 * sinphi + this.cos_p14 * cosphi * coslon;
  ksp = 1;
  if ((g > 0) || (Math.abs(g) <= EPSLN)) {
    x = this.x0 + this.a * ksp * cosphi * Math.sin(dlon) / g;
    y = this.y0 + this.a * ksp * (this.cos_p14 * sinphi - this.sin_p14 * cosphi * coslon) / g;
  }
  else {

    // Point is in the opposing hemisphere and is unprojectable
    // We still need to return a reasonable point, so we project 
    // to infinity, on a bearing 
    // equivalent to the northern hemisphere equivalent
    // This is a reasonable approximation for short shapes and lines that 
    // straddle the horizon.

    x = this.x0 + this.infinity_dist * cosphi * Math.sin(dlon);
    y = this.y0 + this.infinity_dist * (this.cos_p14 * sinphi - this.sin_p14 * cosphi * coslon);

  }
  p.x = x;
  p.y = y;
  return p;
};


exports.inverse = function(p) {
  var rh; /* Rho */
  var sinc, cosc;
  var c;
  var lon, lat;

  /* Inverse equations
      -----------------*/
  p.x = (p.x - this.x0) / this.a;
  p.y = (p.y - this.y0) / this.a;

  p.x /= this.k0;
  p.y /= this.k0;

  if ((rh = Math.sqrt(p.x * p.x + p.y * p.y))) {
    c = Math.atan2(rh, this.rc);
    sinc = Math.sin(c);
    cosc = Math.cos(c);

    lat = asinz(cosc * this.sin_p14 + (p.y * sinc * this.cos_p14) / rh);
    lon = Math.atan2(p.x * sinc, rh * this.cos_p14 * cosc - p.y * this.sin_p14 * sinc);
    lon = adjust_lon(this.long0 + lon);
  }
  else {
    lat = this.phic0;
    lon = 0;
  }

  p.x = lon;
  p.y = lat;
  return p;
};
exports.names = ["gnom"];

},{"../common/adjust_lon":"proj4/lib/common/adjust_lon","../common/asinz":"proj4/lib/common/asinz"}],"proj4/lib/projections/krovak":[function(require,module,exports){
var adjust_lon = require('../common/adjust_lon');
exports.init = function() {
  this.a = 6377397.155;
  this.es = 0.006674372230614;
  this.e = Math.sqrt(this.es);
  if (!this.lat0) {
    this.lat0 = 0.863937979737193;
  }
  if (!this.long0) {
    this.long0 = 0.7417649320975901 - 0.308341501185665;
  }
  /* if scale not set default to 0.9999 */
  if (!this.k0) {
    this.k0 = 0.9999;
  }
  this.s45 = 0.785398163397448; /* 45 */
  this.s90 = 2 * this.s45;
  this.fi0 = this.lat0;
  this.e2 = this.es;
  this.e = Math.sqrt(this.e2);
  this.alfa = Math.sqrt(1 + (this.e2 * Math.pow(Math.cos(this.fi0), 4)) / (1 - this.e2));
  this.uq = 1.04216856380474;
  this.u0 = Math.asin(Math.sin(this.fi0) / this.alfa);
  this.g = Math.pow((1 + this.e * Math.sin(this.fi0)) / (1 - this.e * Math.sin(this.fi0)), this.alfa * this.e / 2);
  this.k = Math.tan(this.u0 / 2 + this.s45) / Math.pow(Math.tan(this.fi0 / 2 + this.s45), this.alfa) * this.g;
  this.k1 = this.k0;
  this.n0 = this.a * Math.sqrt(1 - this.e2) / (1 - this.e2 * Math.pow(Math.sin(this.fi0), 2));
  this.s0 = 1.37008346281555;
  this.n = Math.sin(this.s0);
  this.ro0 = this.k1 * this.n0 / Math.tan(this.s0);
  this.ad = this.s90 - this.uq;
};

/* ellipsoid */
/* calculate xy from lat/lon */
/* Constants, identical to inverse transform function */
exports.forward = function(p) {
  var gfi, u, deltav, s, d, eps, ro;
  var lon = p.x;
  var lat = p.y;
  var delta_lon = adjust_lon(lon - this.long0);
  /* Transformation */
  gfi = Math.pow(((1 + this.e * Math.sin(lat)) / (1 - this.e * Math.sin(lat))), (this.alfa * this.e / 2));
  u = 2 * (Math.atan(this.k * Math.pow(Math.tan(lat / 2 + this.s45), this.alfa) / gfi) - this.s45);
  deltav = -delta_lon * this.alfa;
  s = Math.asin(Math.cos(this.ad) * Math.sin(u) + Math.sin(this.ad) * Math.cos(u) * Math.cos(deltav));
  d = Math.asin(Math.cos(u) * Math.sin(deltav) / Math.cos(s));
  eps = this.n * d;
  ro = this.ro0 * Math.pow(Math.tan(this.s0 / 2 + this.s45), this.n) / Math.pow(Math.tan(s / 2 + this.s45), this.n);
  p.y = ro * Math.cos(eps) / 1;
  p.x = ro * Math.sin(eps) / 1;

  if (!this.czech) {
    p.y *= -1;
    p.x *= -1;
  }
  return (p);
};

/* calculate lat/lon from xy */
exports.inverse = function(p) {
  var u, deltav, s, d, eps, ro, fi1;
  var ok;

  /* Transformation */
  /* revert y, x*/
  var tmp = p.x;
  p.x = p.y;
  p.y = tmp;
  if (!this.czech) {
    p.y *= -1;
    p.x *= -1;
  }
  ro = Math.sqrt(p.x * p.x + p.y * p.y);
  eps = Math.atan2(p.y, p.x);
  d = eps / Math.sin(this.s0);
  s = 2 * (Math.atan(Math.pow(this.ro0 / ro, 1 / this.n) * Math.tan(this.s0 / 2 + this.s45)) - this.s45);
  u = Math.asin(Math.cos(this.ad) * Math.sin(s) - Math.sin(this.ad) * Math.cos(s) * Math.cos(d));
  deltav = Math.asin(Math.cos(s) * Math.sin(d) / Math.cos(u));
  p.x = this.long0 - deltav / this.alfa;
  fi1 = u;
  ok = 0;
  var iter = 0;
  do {
    p.y = 2 * (Math.atan(Math.pow(this.k, - 1 / this.alfa) * Math.pow(Math.tan(u / 2 + this.s45), 1 / this.alfa) * Math.pow((1 + this.e * Math.sin(fi1)) / (1 - this.e * Math.sin(fi1)), this.e / 2)) - this.s45);
    if (Math.abs(fi1 - p.y) < 0.0000000001) {
      ok = 1;
    }
    fi1 = p.y;
    iter += 1;
  } while (ok === 0 && iter < 15);
  if (iter >= 15) {
    return null;
  }

  return (p);
};
exports.names = ["Krovak", "krovak"];

},{"../common/adjust_lon":"proj4/lib/common/adjust_lon"}],"proj4/lib/projections/laea":[function(require,module,exports){
var HALF_PI = Math.PI/2;
var FORTPI = Math.PI/4;
var EPSLN = 1.0e-10;
var qsfnz = require('../common/qsfnz');
var adjust_lon = require('../common/adjust_lon');
/*
  reference
    "New Equal-Area Map Projections for Noncircular Regions", John P. Snyder,
    The American Cartographer, Vol 15, No. 4, October 1988, pp. 341-355.
  */

exports.S_POLE = 1;
exports.N_POLE = 2;
exports.EQUIT = 3;
exports.OBLIQ = 4;


/* Initialize the Lambert Azimuthal Equal Area projection
  ------------------------------------------------------*/
exports.init = function() {
  var t = Math.abs(this.lat0);
  if (Math.abs(t - HALF_PI) < EPSLN) {
    this.mode = this.lat0 < 0 ? this.S_POLE : this.N_POLE;
  }
  else if (Math.abs(t) < EPSLN) {
    this.mode = this.EQUIT;
  }
  else {
    this.mode = this.OBLIQ;
  }
  if (this.es > 0) {
    var sinphi;

    this.qp = qsfnz(this.e, 1);
    this.mmf = 0.5 / (1 - this.es);
    this.apa = this.authset(this.es);
    switch (this.mode) {
    case this.N_POLE:
      this.dd = 1;
      break;
    case this.S_POLE:
      this.dd = 1;
      break;
    case this.EQUIT:
      this.rq = Math.sqrt(0.5 * this.qp);
      this.dd = 1 / this.rq;
      this.xmf = 1;
      this.ymf = 0.5 * this.qp;
      break;
    case this.OBLIQ:
      this.rq = Math.sqrt(0.5 * this.qp);
      sinphi = Math.sin(this.lat0);
      this.sinb1 = qsfnz(this.e, sinphi) / this.qp;
      this.cosb1 = Math.sqrt(1 - this.sinb1 * this.sinb1);
      this.dd = Math.cos(this.lat0) / (Math.sqrt(1 - this.es * sinphi * sinphi) * this.rq * this.cosb1);
      this.ymf = (this.xmf = this.rq) / this.dd;
      this.xmf *= this.dd;
      break;
    }
  }
  else {
    if (this.mode === this.OBLIQ) {
      this.sinph0 = Math.sin(this.lat0);
      this.cosph0 = Math.cos(this.lat0);
    }
  }
};

/* Lambert Azimuthal Equal Area forward equations--mapping lat,long to x,y
  -----------------------------------------------------------------------*/
exports.forward = function(p) {

  /* Forward equations
      -----------------*/
  var x, y, coslam, sinlam, sinphi, q, sinb, cosb, b, cosphi;
  var lam = p.x;
  var phi = p.y;

  lam = adjust_lon(lam - this.long0);

  if (this.sphere) {
    sinphi = Math.sin(phi);
    cosphi = Math.cos(phi);
    coslam = Math.cos(lam);
    if (this.mode === this.OBLIQ || this.mode === this.EQUIT) {
      y = (this.mode === this.EQUIT) ? 1 + cosphi * coslam : 1 + this.sinph0 * sinphi + this.cosph0 * cosphi * coslam;
      if (y <= EPSLN) {
        return null;
      }
      y = Math.sqrt(2 / y);
      x = y * cosphi * Math.sin(lam);
      y *= (this.mode === this.EQUIT) ? sinphi : this.cosph0 * sinphi - this.sinph0 * cosphi * coslam;
    }
    else if (this.mode === this.N_POLE || this.mode === this.S_POLE) {
      if (this.mode === this.N_POLE) {
        coslam = -coslam;
      }
      if (Math.abs(phi + this.phi0) < EPSLN) {
        return null;
      }
      y = FORTPI - phi * 0.5;
      y = 2 * ((this.mode === this.S_POLE) ? Math.cos(y) : Math.sin(y));
      x = y * Math.sin(lam);
      y *= coslam;
    }
  }
  else {
    sinb = 0;
    cosb = 0;
    b = 0;
    coslam = Math.cos(lam);
    sinlam = Math.sin(lam);
    sinphi = Math.sin(phi);
    q = qsfnz(this.e, sinphi);
    if (this.mode === this.OBLIQ || this.mode === this.EQUIT) {
      sinb = q / this.qp;
      cosb = Math.sqrt(1 - sinb * sinb);
    }
    switch (this.mode) {
    case this.OBLIQ:
      b = 1 + this.sinb1 * sinb + this.cosb1 * cosb * coslam;
      break;
    case this.EQUIT:
      b = 1 + cosb * coslam;
      break;
    case this.N_POLE:
      b = HALF_PI + phi;
      q = this.qp - q;
      break;
    case this.S_POLE:
      b = phi - HALF_PI;
      q = this.qp + q;
      break;
    }
    if (Math.abs(b) < EPSLN) {
      return null;
    }
    switch (this.mode) {
    case this.OBLIQ:
    case this.EQUIT:
      b = Math.sqrt(2 / b);
      if (this.mode === this.OBLIQ) {
        y = this.ymf * b * (this.cosb1 * sinb - this.sinb1 * cosb * coslam);
      }
      else {
        y = (b = Math.sqrt(2 / (1 + cosb * coslam))) * sinb * this.ymf;
      }
      x = this.xmf * b * cosb * sinlam;
      break;
    case this.N_POLE:
    case this.S_POLE:
      if (q >= 0) {
        x = (b = Math.sqrt(q)) * sinlam;
        y = coslam * ((this.mode === this.S_POLE) ? b : -b);
      }
      else {
        x = y = 0;
      }
      break;
    }
  }

  p.x = this.a * x + this.x0;
  p.y = this.a * y + this.y0;
  return p;
};

/* Inverse equations
  -----------------*/
exports.inverse = function(p) {
  p.x -= this.x0;
  p.y -= this.y0;
  var x = p.x / this.a;
  var y = p.y / this.a;
  var lam, phi, cCe, sCe, q, rho, ab;

  if (this.sphere) {
    var cosz = 0,
      rh, sinz = 0;

    rh = Math.sqrt(x * x + y * y);
    phi = rh * 0.5;
    if (phi > 1) {
      return null;
    }
    phi = 2 * Math.asin(phi);
    if (this.mode === this.OBLIQ || this.mode === this.EQUIT) {
      sinz = Math.sin(phi);
      cosz = Math.cos(phi);
    }
    switch (this.mode) {
    case this.EQUIT:
      phi = (Math.abs(rh) <= EPSLN) ? 0 : Math.asin(y * sinz / rh);
      x *= sinz;
      y = cosz * rh;
      break;
    case this.OBLIQ:
      phi = (Math.abs(rh) <= EPSLN) ? this.phi0 : Math.asin(cosz * this.sinph0 + y * sinz * this.cosph0 / rh);
      x *= sinz * this.cosph0;
      y = (cosz - Math.sin(phi) * this.sinph0) * rh;
      break;
    case this.N_POLE:
      y = -y;
      phi = HALF_PI - phi;
      break;
    case this.S_POLE:
      phi -= HALF_PI;
      break;
    }
    lam = (y === 0 && (this.mode === this.EQUIT || this.mode === this.OBLIQ)) ? 0 : Math.atan2(x, y);
  }
  else {
    ab = 0;
    if (this.mode === this.OBLIQ || this.mode === this.EQUIT) {
      x /= this.dd;
      y *= this.dd;
      rho = Math.sqrt(x * x + y * y);
      if (rho < EPSLN) {
        p.x = 0;
        p.y = this.phi0;
        return p;
      }
      sCe = 2 * Math.asin(0.5 * rho / this.rq);
      cCe = Math.cos(sCe);
      x *= (sCe = Math.sin(sCe));
      if (this.mode === this.OBLIQ) {
        ab = cCe * this.sinb1 + y * sCe * this.cosb1 / rho;
        q = this.qp * ab;
        y = rho * this.cosb1 * cCe - y * this.sinb1 * sCe;
      }
      else {
        ab = y * sCe / rho;
        q = this.qp * ab;
        y = rho * cCe;
      }
    }
    else if (this.mode === this.N_POLE || this.mode === this.S_POLE) {
      if (this.mode === this.N_POLE) {
        y = -y;
      }
      q = (x * x + y * y);
      if (!q) {
        p.x = 0;
        p.y = this.phi0;
        return p;
      }
      ab = 1 - q / this.qp;
      if (this.mode === this.S_POLE) {
        ab = -ab;
      }
    }
    lam = Math.atan2(x, y);
    phi = this.authlat(Math.asin(ab), this.apa);
  }


  p.x = adjust_lon(this.long0 + lam);
  p.y = phi;
  return p;
};

/* determine latitude from authalic latitude */
exports.P00 = 0.33333333333333333333;
exports.P01 = 0.17222222222222222222;
exports.P02 = 0.10257936507936507936;
exports.P10 = 0.06388888888888888888;
exports.P11 = 0.06640211640211640211;
exports.P20 = 0.01641501294219154443;

exports.authset = function(es) {
  var t;
  var APA = [];
  APA[0] = es * this.P00;
  t = es * es;
  APA[0] += t * this.P01;
  APA[1] = t * this.P10;
  t *= es;
  APA[0] += t * this.P02;
  APA[1] += t * this.P11;
  APA[2] = t * this.P20;
  return APA;
};

exports.authlat = function(beta, APA) {
  var t = beta + beta;
  return (beta + APA[0] * Math.sin(t) + APA[1] * Math.sin(t + t) + APA[2] * Math.sin(t + t + t));
};
exports.names = ["Lambert Azimuthal Equal Area", "Lambert_Azimuthal_Equal_Area", "laea"];

},{"../common/adjust_lon":"proj4/lib/common/adjust_lon","../common/qsfnz":"proj4/lib/common/qsfnz"}],"proj4/lib/projections/lcc":[function(require,module,exports){
var EPSLN = 1.0e-10;
var msfnz = require('../common/msfnz');
var tsfnz = require('../common/tsfnz');
var HALF_PI = Math.PI/2;
var sign = require('../common/sign');
var adjust_lon = require('../common/adjust_lon');
var phi2z = require('../common/phi2z');
exports.init = function() {

  // array of:  r_maj,r_min,lat1,lat2,c_lon,c_lat,false_east,false_north
  //double c_lat;                   /* center latitude                      */
  //double c_lon;                   /* center longitude                     */
  //double lat1;                    /* first standard parallel              */
  //double lat2;                    /* second standard parallel             */
  //double r_maj;                   /* major axis                           */
  //double r_min;                   /* minor axis                           */
  //double false_east;              /* x offset in meters                   */
  //double false_north;             /* y offset in meters                   */

  if (!this.lat2) {
    this.lat2 = this.lat1;
  } //if lat2 is not defined
  if (!this.k0) {
    this.k0 = 1;
  }
  this.x0 = this.x0 || 0;
  this.y0 = this.y0 || 0;
  // Standard Parallels cannot be equal and on opposite sides of the equator
  if (Math.abs(this.lat1 + this.lat2) < EPSLN) {
    return;
  }

  var temp = this.b / this.a;
  this.e = Math.sqrt(1 - temp * temp);

  var sin1 = Math.sin(this.lat1);
  var cos1 = Math.cos(this.lat1);
  var ms1 = msfnz(this.e, sin1, cos1);
  var ts1 = tsfnz(this.e, this.lat1, sin1);

  var sin2 = Math.sin(this.lat2);
  var cos2 = Math.cos(this.lat2);
  var ms2 = msfnz(this.e, sin2, cos2);
  var ts2 = tsfnz(this.e, this.lat2, sin2);

  var ts0 = tsfnz(this.e, this.lat0, Math.sin(this.lat0));

  if (Math.abs(this.lat1 - this.lat2) > EPSLN) {
    this.ns = Math.log(ms1 / ms2) / Math.log(ts1 / ts2);
  }
  else {
    this.ns = sin1;
  }
  if (isNaN(this.ns)) {
    this.ns = sin1;
  }
  this.f0 = ms1 / (this.ns * Math.pow(ts1, this.ns));
  this.rh = this.a * this.f0 * Math.pow(ts0, this.ns);
  if (!this.title) {
    this.title = "Lambert Conformal Conic";
  }
};


// Lambert Conformal conic forward equations--mapping lat,long to x,y
// -----------------------------------------------------------------
exports.forward = function(p) {

  var lon = p.x;
  var lat = p.y;

  // singular cases :
  if (Math.abs(2 * Math.abs(lat) - Math.PI) <= EPSLN) {
    lat = sign(lat) * (HALF_PI - 2 * EPSLN);
  }

  var con = Math.abs(Math.abs(lat) - HALF_PI);
  var ts, rh1;
  if (con > EPSLN) {
    ts = tsfnz(this.e, lat, Math.sin(lat));
    rh1 = this.a * this.f0 * Math.pow(ts, this.ns);
  }
  else {
    con = lat * this.ns;
    if (con <= 0) {
      return null;
    }
    rh1 = 0;
  }
  var theta = this.ns * adjust_lon(lon - this.long0);
  p.x = this.k0 * (rh1 * Math.sin(theta)) + this.x0;
  p.y = this.k0 * (this.rh - rh1 * Math.cos(theta)) + this.y0;

  return p;
};

// Lambert Conformal Conic inverse equations--mapping x,y to lat/long
// -----------------------------------------------------------------
exports.inverse = function(p) {

  var rh1, con, ts;
  var lat, lon;
  var x = (p.x - this.x0) / this.k0;
  var y = (this.rh - (p.y - this.y0) / this.k0);
  if (this.ns > 0) {
    rh1 = Math.sqrt(x * x + y * y);
    con = 1;
  }
  else {
    rh1 = -Math.sqrt(x * x + y * y);
    con = -1;
  }
  var theta = 0;
  if (rh1 !== 0) {
    theta = Math.atan2((con * x), (con * y));
  }
  if ((rh1 !== 0) || (this.ns > 0)) {
    con = 1 / this.ns;
    ts = Math.pow((rh1 / (this.a * this.f0)), con);
    lat = phi2z(this.e, ts);
    if (lat === -9999) {
      return null;
    }
  }
  else {
    lat = -HALF_PI;
  }
  lon = adjust_lon(theta / this.ns + this.long0);

  p.x = lon;
  p.y = lat;
  return p;
};

exports.names = ["Lambert Tangential Conformal Conic Projection", "Lambert_Conformal_Conic", "Lambert_Conformal_Conic_2SP", "lcc"];

},{"../common/adjust_lon":"proj4/lib/common/adjust_lon","../common/msfnz":"proj4/lib/common/msfnz","../common/phi2z":"proj4/lib/common/phi2z","../common/sign":"proj4/lib/common/sign","../common/tsfnz":"proj4/lib/common/tsfnz"}],"proj4/lib/projections/longlat":[function(require,module,exports){
exports.init = function() {
  //no-op for longlat
};

function identity(pt) {
  return pt;
}
exports.forward = identity;
exports.inverse = identity;
exports.names = ["longlat", "identity"];

},{}],"proj4/lib/projections/merc":[function(require,module,exports){
var msfnz = require('../common/msfnz');
var HALF_PI = Math.PI/2;
var EPSLN = 1.0e-10;
var R2D = 57.29577951308232088;
var adjust_lon = require('../common/adjust_lon');
var FORTPI = Math.PI/4;
var tsfnz = require('../common/tsfnz');
var phi2z = require('../common/phi2z');
exports.init = function() {
  var con = this.b / this.a;
  this.es = 1 - con * con;
  if(!('x0' in this)){
    this.x0 = 0;
  }
  if(!('y0' in this)){
    this.y0 = 0;
  }
  this.e = Math.sqrt(this.es);
  if (this.lat_ts) {
    if (this.sphere) {
      this.k0 = Math.cos(this.lat_ts);
    }
    else {
      this.k0 = msfnz(this.e, Math.sin(this.lat_ts), Math.cos(this.lat_ts));
    }
  }
  else {
    if (!this.k0) {
      if (this.k) {
        this.k0 = this.k;
      }
      else {
        this.k0 = 1;
      }
    }
  }
};

/* Mercator forward equations--mapping lat,long to x,y
  --------------------------------------------------*/

exports.forward = function(p) {
  var lon = p.x;
  var lat = p.y;
  // convert to radians
  if (lat * R2D > 90 && lat * R2D < -90 && lon * R2D > 180 && lon * R2D < -180) {
    return null;
  }

  var x, y;
  if (Math.abs(Math.abs(lat) - HALF_PI) <= EPSLN) {
    return null;
  }
  else {
    if (this.sphere) {
      x = this.x0 + this.a * this.k0 * adjust_lon(lon - this.long0);
      y = this.y0 + this.a * this.k0 * Math.log(Math.tan(FORTPI + 0.5 * lat));
    }
    else {
      var sinphi = Math.sin(lat);
      var ts = tsfnz(this.e, lat, sinphi);
      x = this.x0 + this.a * this.k0 * adjust_lon(lon - this.long0);
      y = this.y0 - this.a * this.k0 * Math.log(ts);
    }
    p.x = x;
    p.y = y;
    return p;
  }
};


/* Mercator inverse equations--mapping x,y to lat/long
  --------------------------------------------------*/
exports.inverse = function(p) {

  var x = p.x - this.x0;
  var y = p.y - this.y0;
  var lon, lat;

  if (this.sphere) {
    lat = HALF_PI - 2 * Math.atan(Math.exp(-y / (this.a * this.k0)));
  }
  else {
    var ts = Math.exp(-y / (this.a * this.k0));
    lat = phi2z(this.e, ts);
    if (lat === -9999) {
      return null;
    }
  }
  lon = adjust_lon(this.long0 + x / (this.a * this.k0));

  p.x = lon;
  p.y = lat;
  return p;
};

exports.names = ["Mercator", "Popular Visualisation Pseudo Mercator", "Mercator_1SP", "Mercator_Auxiliary_Sphere", "merc"];

},{"../common/adjust_lon":"proj4/lib/common/adjust_lon","../common/msfnz":"proj4/lib/common/msfnz","../common/phi2z":"proj4/lib/common/phi2z","../common/tsfnz":"proj4/lib/common/tsfnz"}],"proj4/lib/projections/mill":[function(require,module,exports){
var adjust_lon = require('../common/adjust_lon');
/*
  reference
    "New Equal-Area Map Projections for Noncircular Regions", John P. Snyder,
    The American Cartographer, Vol 15, No. 4, October 1988, pp. 341-355.
  */


/* Initialize the Miller Cylindrical projection
  -------------------------------------------*/
exports.init = function() {
  //no-op
};


/* Miller Cylindrical forward equations--mapping lat,long to x,y
    ------------------------------------------------------------*/
exports.forward = function(p) {
  var lon = p.x;
  var lat = p.y;
  /* Forward equations
      -----------------*/
  var dlon = adjust_lon(lon - this.long0);
  var x = this.x0 + this.a * dlon;
  var y = this.y0 + this.a * Math.log(Math.tan((Math.PI / 4) + (lat / 2.5))) * 1.25;

  p.x = x;
  p.y = y;
  return p;
};

/* Miller Cylindrical inverse equations--mapping x,y to lat/long
    ------------------------------------------------------------*/
exports.inverse = function(p) {
  p.x -= this.x0;
  p.y -= this.y0;

  var lon = adjust_lon(this.long0 + p.x / this.a);
  var lat = 2.5 * (Math.atan(Math.exp(0.8 * p.y / this.a)) - Math.PI / 4);

  p.x = lon;
  p.y = lat;
  return p;
};
exports.names = ["Miller_Cylindrical", "mill"];

},{"../common/adjust_lon":"proj4/lib/common/adjust_lon"}],"proj4/lib/projections/moll":[function(require,module,exports){
var adjust_lon = require('../common/adjust_lon');
var EPSLN = 1.0e-10;
exports.init = function() {};

/* Mollweide forward equations--mapping lat,long to x,y
    ----------------------------------------------------*/
exports.forward = function(p) {

  /* Forward equations
      -----------------*/
  var lon = p.x;
  var lat = p.y;

  var delta_lon = adjust_lon(lon - this.long0);
  var theta = lat;
  var con = Math.PI * Math.sin(lat);

  /* Iterate using the Newton-Raphson method to find theta
      -----------------------------------------------------*/
  for (var i = 0; true; i++) {
    var delta_theta = -(theta + Math.sin(theta) - con) / (1 + Math.cos(theta));
    theta += delta_theta;
    if (Math.abs(delta_theta) < EPSLN) {
      break;
    }
  }
  theta /= 2;

  /* If the latitude is 90 deg, force the x coordinate to be "0 + false easting"
       this is done here because of precision problems with "cos(theta)"
       --------------------------------------------------------------------------*/
  if (Math.PI / 2 - Math.abs(lat) < EPSLN) {
    delta_lon = 0;
  }
  var x = 0.900316316158 * this.a * delta_lon * Math.cos(theta) + this.x0;
  var y = 1.4142135623731 * this.a * Math.sin(theta) + this.y0;

  p.x = x;
  p.y = y;
  return p;
};

exports.inverse = function(p) {
  var theta;
  var arg;

  /* Inverse equations
      -----------------*/
  p.x -= this.x0;
  p.y -= this.y0;
  arg = p.y / (1.4142135623731 * this.a);

  /* Because of division by zero problems, 'arg' can not be 1.  Therefore
       a number very close to one is used instead.
       -------------------------------------------------------------------*/
  if (Math.abs(arg) > 0.999999999999) {
    arg = 0.999999999999;
  }
  theta = Math.asin(arg);
  var lon = adjust_lon(this.long0 + (p.x / (0.900316316158 * this.a * Math.cos(theta))));
  if (lon < (-Math.PI)) {
    lon = -Math.PI;
  }
  if (lon > Math.PI) {
    lon = Math.PI;
  }
  arg = (2 * theta + Math.sin(2 * theta)) / Math.PI;
  if (Math.abs(arg) > 1) {
    arg = 1;
  }
  var lat = Math.asin(arg);

  p.x = lon;
  p.y = lat;
  return p;
};
exports.names = ["Mollweide", "moll"];

},{"../common/adjust_lon":"proj4/lib/common/adjust_lon"}],"proj4/lib/projections/nzmg":[function(require,module,exports){
var SEC_TO_RAD = 4.84813681109535993589914102357e-6;
/*
  reference
    Department of Land and Survey Technical Circular 1973/32
      http://www.linz.govt.nz/docs/miscellaneous/nz-map-definition.pdf
    OSG Technical Report 4.1
      http://www.linz.govt.nz/docs/miscellaneous/nzmg.pdf
  */

/**
 * iterations: Number of iterations to refine inverse transform.
 *     0 -> km accuracy
 *     1 -> m accuracy -- suitable for most mapping applications
 *     2 -> mm accuracy
 */
exports.iterations = 1;

exports.init = function() {
  this.A = [];
  this.A[1] = 0.6399175073;
  this.A[2] = -0.1358797613;
  this.A[3] = 0.063294409;
  this.A[4] = -0.02526853;
  this.A[5] = 0.0117879;
  this.A[6] = -0.0055161;
  this.A[7] = 0.0026906;
  this.A[8] = -0.001333;
  this.A[9] = 0.00067;
  this.A[10] = -0.00034;

  this.B_re = [];
  this.B_im = [];
  this.B_re[1] = 0.7557853228;
  this.B_im[1] = 0;
  this.B_re[2] = 0.249204646;
  this.B_im[2] = 0.003371507;
  this.B_re[3] = -0.001541739;
  this.B_im[3] = 0.041058560;
  this.B_re[4] = -0.10162907;
  this.B_im[4] = 0.01727609;
  this.B_re[5] = -0.26623489;
  this.B_im[5] = -0.36249218;
  this.B_re[6] = -0.6870983;
  this.B_im[6] = -1.1651967;

  this.C_re = [];
  this.C_im = [];
  this.C_re[1] = 1.3231270439;
  this.C_im[1] = 0;
  this.C_re[2] = -0.577245789;
  this.C_im[2] = -0.007809598;
  this.C_re[3] = 0.508307513;
  this.C_im[3] = -0.112208952;
  this.C_re[4] = -0.15094762;
  this.C_im[4] = 0.18200602;
  this.C_re[5] = 1.01418179;
  this.C_im[5] = 1.64497696;
  this.C_re[6] = 1.9660549;
  this.C_im[6] = 2.5127645;

  this.D = [];
  this.D[1] = 1.5627014243;
  this.D[2] = 0.5185406398;
  this.D[3] = -0.03333098;
  this.D[4] = -0.1052906;
  this.D[5] = -0.0368594;
  this.D[6] = 0.007317;
  this.D[7] = 0.01220;
  this.D[8] = 0.00394;
  this.D[9] = -0.0013;
};

/**
    New Zealand Map Grid Forward  - long/lat to x/y
    long/lat in radians
  */
exports.forward = function(p) {
  var n;
  var lon = p.x;
  var lat = p.y;

  var delta_lat = lat - this.lat0;
  var delta_lon = lon - this.long0;

  // 1. Calculate d_phi and d_psi    ...                          // and d_lambda
  // For this algorithm, delta_latitude is in seconds of arc x 10-5, so we need to scale to those units. Longitude is radians.
  var d_phi = delta_lat / SEC_TO_RAD * 1E-5;
  var d_lambda = delta_lon;
  var d_phi_n = 1; // d_phi^0

  var d_psi = 0;
  for (n = 1; n <= 10; n++) {
    d_phi_n = d_phi_n * d_phi;
    d_psi = d_psi + this.A[n] * d_phi_n;
  }

  // 2. Calculate theta
  var th_re = d_psi;
  var th_im = d_lambda;

  // 3. Calculate z
  var th_n_re = 1;
  var th_n_im = 0; // theta^0
  var th_n_re1;
  var th_n_im1;

  var z_re = 0;
  var z_im = 0;
  for (n = 1; n <= 6; n++) {
    th_n_re1 = th_n_re * th_re - th_n_im * th_im;
    th_n_im1 = th_n_im * th_re + th_n_re * th_im;
    th_n_re = th_n_re1;
    th_n_im = th_n_im1;
    z_re = z_re + this.B_re[n] * th_n_re - this.B_im[n] * th_n_im;
    z_im = z_im + this.B_im[n] * th_n_re + this.B_re[n] * th_n_im;
  }

  // 4. Calculate easting and northing
  p.x = (z_im * this.a) + this.x0;
  p.y = (z_re * this.a) + this.y0;

  return p;
};


/**
    New Zealand Map Grid Inverse  -  x/y to long/lat
  */
exports.inverse = function(p) {
  var n;
  var x = p.x;
  var y = p.y;

  var delta_x = x - this.x0;
  var delta_y = y - this.y0;

  // 1. Calculate z
  var z_re = delta_y / this.a;
  var z_im = delta_x / this.a;

  // 2a. Calculate theta - first approximation gives km accuracy
  var z_n_re = 1;
  var z_n_im = 0; // z^0
  var z_n_re1;
  var z_n_im1;

  var th_re = 0;
  var th_im = 0;
  for (n = 1; n <= 6; n++) {
    z_n_re1 = z_n_re * z_re - z_n_im * z_im;
    z_n_im1 = z_n_im * z_re + z_n_re * z_im;
    z_n_re = z_n_re1;
    z_n_im = z_n_im1;
    th_re = th_re + this.C_re[n] * z_n_re - this.C_im[n] * z_n_im;
    th_im = th_im + this.C_im[n] * z_n_re + this.C_re[n] * z_n_im;
  }

  // 2b. Iterate to refine the accuracy of the calculation
  //        0 iterations gives km accuracy
  //        1 iteration gives m accuracy -- good enough for most mapping applications
  //        2 iterations bives mm accuracy
  for (var i = 0; i < this.iterations; i++) {
    var th_n_re = th_re;
    var th_n_im = th_im;
    var th_n_re1;
    var th_n_im1;

    var num_re = z_re;
    var num_im = z_im;
    for (n = 2; n <= 6; n++) {
      th_n_re1 = th_n_re * th_re - th_n_im * th_im;
      th_n_im1 = th_n_im * th_re + th_n_re * th_im;
      th_n_re = th_n_re1;
      th_n_im = th_n_im1;
      num_re = num_re + (n - 1) * (this.B_re[n] * th_n_re - this.B_im[n] * th_n_im);
      num_im = num_im + (n - 1) * (this.B_im[n] * th_n_re + this.B_re[n] * th_n_im);
    }

    th_n_re = 1;
    th_n_im = 0;
    var den_re = this.B_re[1];
    var den_im = this.B_im[1];
    for (n = 2; n <= 6; n++) {
      th_n_re1 = th_n_re * th_re - th_n_im * th_im;
      th_n_im1 = th_n_im * th_re + th_n_re * th_im;
      th_n_re = th_n_re1;
      th_n_im = th_n_im1;
      den_re = den_re + n * (this.B_re[n] * th_n_re - this.B_im[n] * th_n_im);
      den_im = den_im + n * (this.B_im[n] * th_n_re + this.B_re[n] * th_n_im);
    }

    // Complex division
    var den2 = den_re * den_re + den_im * den_im;
    th_re = (num_re * den_re + num_im * den_im) / den2;
    th_im = (num_im * den_re - num_re * den_im) / den2;
  }

  // 3. Calculate d_phi              ...                                    // and d_lambda
  var d_psi = th_re;
  var d_lambda = th_im;
  var d_psi_n = 1; // d_psi^0

  var d_phi = 0;
  for (n = 1; n <= 9; n++) {
    d_psi_n = d_psi_n * d_psi;
    d_phi = d_phi + this.D[n] * d_psi_n;
  }

  // 4. Calculate latitude and longitude
  // d_phi is calcuated in second of arc * 10^-5, so we need to scale back to radians. d_lambda is in radians.
  var lat = this.lat0 + (d_phi * SEC_TO_RAD * 1E5);
  var lon = this.long0 + d_lambda;

  p.x = lon;
  p.y = lat;

  return p;
};
exports.names = ["New_Zealand_Map_Grid", "nzmg"];
},{}],"proj4/lib/projections/omerc":[function(require,module,exports){
var tsfnz = require('../common/tsfnz');
var adjust_lon = require('../common/adjust_lon');
var phi2z = require('../common/phi2z');
var HALF_PI = Math.PI/2;
var FORTPI = Math.PI/4;
var EPSLN = 1.0e-10;

/* Initialize the Oblique Mercator  projection
    ------------------------------------------*/
exports.init = function() {
  this.no_off = this.no_off || false;
  this.no_rot = this.no_rot || false;

  if (isNaN(this.k0)) {
    this.k0 = 1;
  }
  var sinlat = Math.sin(this.lat0);
  var coslat = Math.cos(this.lat0);
  var con = this.e * sinlat;

  this.bl = Math.sqrt(1 + this.es / (1 - this.es) * Math.pow(coslat, 4));
  this.al = this.a * this.bl * this.k0 * Math.sqrt(1 - this.es) / (1 - con * con);
  var t0 = tsfnz(this.e, this.lat0, sinlat);
  var dl = this.bl / coslat * Math.sqrt((1 - this.es) / (1 - con * con));
  if (dl * dl < 1) {
    dl = 1;
  }
  var fl;
  var gl;
  if (!isNaN(this.longc)) {
    //Central point and azimuth method

    if (this.lat0 >= 0) {
      fl = dl + Math.sqrt(dl * dl - 1);
    }
    else {
      fl = dl - Math.sqrt(dl * dl - 1);
    }
    this.el = fl * Math.pow(t0, this.bl);
    gl = 0.5 * (fl - 1 / fl);
    this.gamma0 = Math.asin(Math.sin(this.alpha) / dl);
    this.long0 = this.longc - Math.asin(gl * Math.tan(this.gamma0)) / this.bl;

  }
  else {
    //2 points method
    var t1 = tsfnz(this.e, this.lat1, Math.sin(this.lat1));
    var t2 = tsfnz(this.e, this.lat2, Math.sin(this.lat2));
    if (this.lat0 >= 0) {
      this.el = (dl + Math.sqrt(dl * dl - 1)) * Math.pow(t0, this.bl);
    }
    else {
      this.el = (dl - Math.sqrt(dl * dl - 1)) * Math.pow(t0, this.bl);
    }
    var hl = Math.pow(t1, this.bl);
    var ll = Math.pow(t2, this.bl);
    fl = this.el / hl;
    gl = 0.5 * (fl - 1 / fl);
    var jl = (this.el * this.el - ll * hl) / (this.el * this.el + ll * hl);
    var pl = (ll - hl) / (ll + hl);
    var dlon12 = adjust_lon(this.long1 - this.long2);
    this.long0 = 0.5 * (this.long1 + this.long2) - Math.atan(jl * Math.tan(0.5 * this.bl * (dlon12)) / pl) / this.bl;
    this.long0 = adjust_lon(this.long0);
    var dlon10 = adjust_lon(this.long1 - this.long0);
    this.gamma0 = Math.atan(Math.sin(this.bl * (dlon10)) / gl);
    this.alpha = Math.asin(dl * Math.sin(this.gamma0));
  }

  if (this.no_off) {
    this.uc = 0;
  }
  else {
    if (this.lat0 >= 0) {
      this.uc = this.al / this.bl * Math.atan2(Math.sqrt(dl * dl - 1), Math.cos(this.alpha));
    }
    else {
      this.uc = -1 * this.al / this.bl * Math.atan2(Math.sqrt(dl * dl - 1), Math.cos(this.alpha));
    }
  }

};


/* Oblique Mercator forward equations--mapping lat,long to x,y
    ----------------------------------------------------------*/
exports.forward = function(p) {
  var lon = p.x;
  var lat = p.y;
  var dlon = adjust_lon(lon - this.long0);
  var us, vs;
  var con;
  if (Math.abs(Math.abs(lat) - HALF_PI) <= EPSLN) {
    if (lat > 0) {
      con = -1;
    }
    else {
      con = 1;
    }
    vs = this.al / this.bl * Math.log(Math.tan(FORTPI + con * this.gamma0 * 0.5));
    us = -1 * con * HALF_PI * this.al / this.bl;
  }
  else {
    var t = tsfnz(this.e, lat, Math.sin(lat));
    var ql = this.el / Math.pow(t, this.bl);
    var sl = 0.5 * (ql - 1 / ql);
    var tl = 0.5 * (ql + 1 / ql);
    var vl = Math.sin(this.bl * (dlon));
    var ul = (sl * Math.sin(this.gamma0) - vl * Math.cos(this.gamma0)) / tl;
    if (Math.abs(Math.abs(ul) - 1) <= EPSLN) {
      vs = Number.POSITIVE_INFINITY;
    }
    else {
      vs = 0.5 * this.al * Math.log((1 - ul) / (1 + ul)) / this.bl;
    }
    if (Math.abs(Math.cos(this.bl * (dlon))) <= EPSLN) {
      us = this.al * this.bl * (dlon);
    }
    else {
      us = this.al * Math.atan2(sl * Math.cos(this.gamma0) + vl * Math.sin(this.gamma0), Math.cos(this.bl * dlon)) / this.bl;
    }
  }

  if (this.no_rot) {
    p.x = this.x0 + us;
    p.y = this.y0 + vs;
  }
  else {

    us -= this.uc;
    p.x = this.x0 + vs * Math.cos(this.alpha) + us * Math.sin(this.alpha);
    p.y = this.y0 + us * Math.cos(this.alpha) - vs * Math.sin(this.alpha);
  }
  return p;
};

exports.inverse = function(p) {
  var us, vs;
  if (this.no_rot) {
    vs = p.y - this.y0;
    us = p.x - this.x0;
  }
  else {
    vs = (p.x - this.x0) * Math.cos(this.alpha) - (p.y - this.y0) * Math.sin(this.alpha);
    us = (p.y - this.y0) * Math.cos(this.alpha) + (p.x - this.x0) * Math.sin(this.alpha);
    us += this.uc;
  }
  var qp = Math.exp(-1 * this.bl * vs / this.al);
  var sp = 0.5 * (qp - 1 / qp);
  var tp = 0.5 * (qp + 1 / qp);
  var vp = Math.sin(this.bl * us / this.al);
  var up = (vp * Math.cos(this.gamma0) + sp * Math.sin(this.gamma0)) / tp;
  var ts = Math.pow(this.el / Math.sqrt((1 + up) / (1 - up)), 1 / this.bl);
  if (Math.abs(up - 1) < EPSLN) {
    p.x = this.long0;
    p.y = HALF_PI;
  }
  else if (Math.abs(up + 1) < EPSLN) {
    p.x = this.long0;
    p.y = -1 * HALF_PI;
  }
  else {
    p.y = phi2z(this.e, ts);
    p.x = adjust_lon(this.long0 - Math.atan2(sp * Math.cos(this.gamma0) - vp * Math.sin(this.gamma0), Math.cos(this.bl * us / this.al)) / this.bl);
  }
  return p;
};

exports.names = ["Hotine_Oblique_Mercator", "Hotine Oblique Mercator", "Hotine_Oblique_Mercator_Azimuth_Natural_Origin", "Hotine_Oblique_Mercator_Azimuth_Center", "omerc"];
},{"../common/adjust_lon":"proj4/lib/common/adjust_lon","../common/phi2z":"proj4/lib/common/phi2z","../common/tsfnz":"proj4/lib/common/tsfnz"}],"proj4/lib/projections/poly":[function(require,module,exports){
var e0fn = require('../common/e0fn');
var e1fn = require('../common/e1fn');
var e2fn = require('../common/e2fn');
var e3fn = require('../common/e3fn');
var adjust_lon = require('../common/adjust_lon');
var adjust_lat = require('../common/adjust_lat');
var mlfn = require('../common/mlfn');
var EPSLN = 1.0e-10;
var gN = require('../common/gN');
var MAX_ITER = 20;
exports.init = function() {
  /* Place parameters in static storage for common use
      -------------------------------------------------*/
  this.temp = this.b / this.a;
  this.es = 1 - Math.pow(this.temp, 2); // devait etre dans tmerc.js mais n y est pas donc je commente sinon retour de valeurs nulles
  this.e = Math.sqrt(this.es);
  this.e0 = e0fn(this.es);
  this.e1 = e1fn(this.es);
  this.e2 = e2fn(this.es);
  this.e3 = e3fn(this.es);
  this.ml0 = this.a * mlfn(this.e0, this.e1, this.e2, this.e3, this.lat0); //si que des zeros le calcul ne se fait pas
};


/* Polyconic forward equations--mapping lat,long to x,y
    ---------------------------------------------------*/
exports.forward = function(p) {
  var lon = p.x;
  var lat = p.y;
  var x, y, el;
  var dlon = adjust_lon(lon - this.long0);
  el = dlon * Math.sin(lat);
  if (this.sphere) {
    if (Math.abs(lat) <= EPSLN) {
      x = this.a * dlon;
      y = -1 * this.a * this.lat0;
    }
    else {
      x = this.a * Math.sin(el) / Math.tan(lat);
      y = this.a * (adjust_lat(lat - this.lat0) + (1 - Math.cos(el)) / Math.tan(lat));
    }
  }
  else {
    if (Math.abs(lat) <= EPSLN) {
      x = this.a * dlon;
      y = -1 * this.ml0;
    }
    else {
      var nl = gN(this.a, this.e, Math.sin(lat)) / Math.tan(lat);
      x = nl * Math.sin(el);
      y = this.a * mlfn(this.e0, this.e1, this.e2, this.e3, lat) - this.ml0 + nl * (1 - Math.cos(el));
    }

  }
  p.x = x + this.x0;
  p.y = y + this.y0;
  return p;
};


/* Inverse equations
  -----------------*/
exports.inverse = function(p) {
  var lon, lat, x, y, i;
  var al, bl;
  var phi, dphi;
  x = p.x - this.x0;
  y = p.y - this.y0;

  if (this.sphere) {
    if (Math.abs(y + this.a * this.lat0) <= EPSLN) {
      lon = adjust_lon(x / this.a + this.long0);
      lat = 0;
    }
    else {
      al = this.lat0 + y / this.a;
      bl = x * x / this.a / this.a + al * al;
      phi = al;
      var tanphi;
      for (i = MAX_ITER; i; --i) {
        tanphi = Math.tan(phi);
        dphi = -1 * (al * (phi * tanphi + 1) - phi - 0.5 * (phi * phi + bl) * tanphi) / ((phi - al) / tanphi - 1);
        phi += dphi;
        if (Math.abs(dphi) <= EPSLN) {
          lat = phi;
          break;
        }
      }
      lon = adjust_lon(this.long0 + (Math.asin(x * Math.tan(phi) / this.a)) / Math.sin(lat));
    }
  }
  else {
    if (Math.abs(y + this.ml0) <= EPSLN) {
      lat = 0;
      lon = adjust_lon(this.long0 + x / this.a);
    }
    else {

      al = (this.ml0 + y) / this.a;
      bl = x * x / this.a / this.a + al * al;
      phi = al;
      var cl, mln, mlnp, ma;
      var con;
      for (i = MAX_ITER; i; --i) {
        con = this.e * Math.sin(phi);
        cl = Math.sqrt(1 - con * con) * Math.tan(phi);
        mln = this.a * mlfn(this.e0, this.e1, this.e2, this.e3, phi);
        mlnp = this.e0 - 2 * this.e1 * Math.cos(2 * phi) + 4 * this.e2 * Math.cos(4 * phi) - 6 * this.e3 * Math.cos(6 * phi);
        ma = mln / this.a;
        dphi = (al * (cl * ma + 1) - ma - 0.5 * cl * (ma * ma + bl)) / (this.es * Math.sin(2 * phi) * (ma * ma + bl - 2 * al * ma) / (4 * cl) + (al - ma) * (cl * mlnp - 2 / Math.sin(2 * phi)) - mlnp);
        phi -= dphi;
        if (Math.abs(dphi) <= EPSLN) {
          lat = phi;
          break;
        }
      }

      //lat=phi4z(this.e,this.e0,this.e1,this.e2,this.e3,al,bl,0,0);
      cl = Math.sqrt(1 - this.es * Math.pow(Math.sin(lat), 2)) * Math.tan(lat);
      lon = adjust_lon(this.long0 + Math.asin(x * cl / this.a) / Math.sin(lat));
    }
  }

  p.x = lon;
  p.y = lat;
  return p;
};
exports.names = ["Polyconic", "poly"];
},{"../common/adjust_lat":"proj4/lib/common/adjust_lat","../common/adjust_lon":"proj4/lib/common/adjust_lon","../common/e0fn":"proj4/lib/common/e0fn","../common/e1fn":"proj4/lib/common/e1fn","../common/e2fn":"proj4/lib/common/e2fn","../common/e3fn":"proj4/lib/common/e3fn","../common/gN":"proj4/lib/common/gN","../common/mlfn":"proj4/lib/common/mlfn"}],"proj4/lib/projections/sinu":[function(require,module,exports){
var adjust_lon = require('../common/adjust_lon');
var adjust_lat = require('../common/adjust_lat');
var pj_enfn = require('../common/pj_enfn');
var MAX_ITER = 20;
var pj_mlfn = require('../common/pj_mlfn');
var pj_inv_mlfn = require('../common/pj_inv_mlfn');
var HALF_PI = Math.PI/2;
var EPSLN = 1.0e-10;
var asinz = require('../common/asinz');
exports.init = function() {
  /* Place parameters in static storage for common use
    -------------------------------------------------*/


  if (!this.sphere) {
    this.en = pj_enfn(this.es);
  }
  else {
    this.n = 1;
    this.m = 0;
    this.es = 0;
    this.C_y = Math.sqrt((this.m + 1) / this.n);
    this.C_x = this.C_y / (this.m + 1);
  }

};

/* Sinusoidal forward equations--mapping lat,long to x,y
  -----------------------------------------------------*/
exports.forward = function(p) {
  var x, y;
  var lon = p.x;
  var lat = p.y;
  /* Forward equations
    -----------------*/
  lon = adjust_lon(lon - this.long0);

  if (this.sphere) {
    if (!this.m) {
      lat = this.n !== 1 ? Math.asin(this.n * Math.sin(lat)) : lat;
    }
    else {
      var k = this.n * Math.sin(lat);
      for (var i = MAX_ITER; i; --i) {
        var V = (this.m * lat + Math.sin(lat) - k) / (this.m + Math.cos(lat));
        lat -= V;
        if (Math.abs(V) < EPSLN) {
          break;
        }
      }
    }
    x = this.a * this.C_x * lon * (this.m + Math.cos(lat));
    y = this.a * this.C_y * lat;

  }
  else {

    var s = Math.sin(lat);
    var c = Math.cos(lat);
    y = this.a * pj_mlfn(lat, s, c, this.en);
    x = this.a * lon * c / Math.sqrt(1 - this.es * s * s);
  }

  p.x = x;
  p.y = y;
  return p;
};

exports.inverse = function(p) {
  var lat, temp, lon, s;

  p.x -= this.x0;
  lon = p.x / this.a;
  p.y -= this.y0;
  lat = p.y / this.a;

  if (this.sphere) {
    lat /= this.C_y;
    lon = lon / (this.C_x * (this.m + Math.cos(lat)));
    if (this.m) {
      lat = asinz((this.m * lat + Math.sin(lat)) / this.n);
    }
    else if (this.n !== 1) {
      lat = asinz(Math.sin(lat) / this.n);
    }
    lon = adjust_lon(lon + this.long0);
    lat = adjust_lat(lat);
  }
  else {
    lat = pj_inv_mlfn(p.y / this.a, this.es, this.en);
    s = Math.abs(lat);
    if (s < HALF_PI) {
      s = Math.sin(lat);
      temp = this.long0 + p.x * Math.sqrt(1 - this.es * s * s) / (this.a * Math.cos(lat));
      //temp = this.long0 + p.x / (this.a * Math.cos(lat));
      lon = adjust_lon(temp);
    }
    else if ((s - EPSLN) < HALF_PI) {
      lon = this.long0;
    }
  }
  p.x = lon;
  p.y = lat;
  return p;
};
exports.names = ["Sinusoidal", "sinu"];
},{"../common/adjust_lat":"proj4/lib/common/adjust_lat","../common/adjust_lon":"proj4/lib/common/adjust_lon","../common/asinz":"proj4/lib/common/asinz","../common/pj_enfn":"proj4/lib/common/pj_enfn","../common/pj_inv_mlfn":"proj4/lib/common/pj_inv_mlfn","../common/pj_mlfn":"proj4/lib/common/pj_mlfn"}],"proj4/lib/projections/somerc":[function(require,module,exports){
/*
  references:
    Formules et constantes pour le Calcul pour la
    projection cylindrique conforme à axe oblique et pour la transformation entre
    des systèmes de référence.
    http://www.swisstopo.admin.ch/internet/swisstopo/fr/home/topics/survey/sys/refsys/switzerland.parsysrelated1.31216.downloadList.77004.DownloadFile.tmp/swissprojectionfr.pdf
  */
exports.init = function() {
  var phy0 = this.lat0;
  this.lambda0 = this.long0;
  var sinPhy0 = Math.sin(phy0);
  var semiMajorAxis = this.a;
  var invF = this.rf;
  var flattening = 1 / invF;
  var e2 = 2 * flattening - Math.pow(flattening, 2);
  var e = this.e = Math.sqrt(e2);
  this.R = this.k0 * semiMajorAxis * Math.sqrt(1 - e2) / (1 - e2 * Math.pow(sinPhy0, 2));
  this.alpha = Math.sqrt(1 + e2 / (1 - e2) * Math.pow(Math.cos(phy0), 4));
  this.b0 = Math.asin(sinPhy0 / this.alpha);
  var k1 = Math.log(Math.tan(Math.PI / 4 + this.b0 / 2));
  var k2 = Math.log(Math.tan(Math.PI / 4 + phy0 / 2));
  var k3 = Math.log((1 + e * sinPhy0) / (1 - e * sinPhy0));
  this.K = k1 - this.alpha * k2 + this.alpha * e / 2 * k3;
};


exports.forward = function(p) {
  var Sa1 = Math.log(Math.tan(Math.PI / 4 - p.y / 2));
  var Sa2 = this.e / 2 * Math.log((1 + this.e * Math.sin(p.y)) / (1 - this.e * Math.sin(p.y)));
  var S = -this.alpha * (Sa1 + Sa2) + this.K;

  // spheric latitude
  var b = 2 * (Math.atan(Math.exp(S)) - Math.PI / 4);

  // spheric longitude
  var I = this.alpha * (p.x - this.lambda0);

  // psoeudo equatorial rotation
  var rotI = Math.atan(Math.sin(I) / (Math.sin(this.b0) * Math.tan(b) + Math.cos(this.b0) * Math.cos(I)));

  var rotB = Math.asin(Math.cos(this.b0) * Math.sin(b) - Math.sin(this.b0) * Math.cos(b) * Math.cos(I));

  p.y = this.R / 2 * Math.log((1 + Math.sin(rotB)) / (1 - Math.sin(rotB))) + this.y0;
  p.x = this.R * rotI + this.x0;
  return p;
};

exports.inverse = function(p) {
  var Y = p.x - this.x0;
  var X = p.y - this.y0;

  var rotI = Y / this.R;
  var rotB = 2 * (Math.atan(Math.exp(X / this.R)) - Math.PI / 4);

  var b = Math.asin(Math.cos(this.b0) * Math.sin(rotB) + Math.sin(this.b0) * Math.cos(rotB) * Math.cos(rotI));
  var I = Math.atan(Math.sin(rotI) / (Math.cos(this.b0) * Math.cos(rotI) - Math.sin(this.b0) * Math.tan(rotB)));

  var lambda = this.lambda0 + I / this.alpha;

  var S = 0;
  var phy = b;
  var prevPhy = -1000;
  var iteration = 0;
  while (Math.abs(phy - prevPhy) > 0.0000001) {
    if (++iteration > 20) {
      //...reportError("omercFwdInfinity");
      return;
    }
    //S = Math.log(Math.tan(Math.PI / 4 + phy / 2));
    S = 1 / this.alpha * (Math.log(Math.tan(Math.PI / 4 + b / 2)) - this.K) + this.e * Math.log(Math.tan(Math.PI / 4 + Math.asin(this.e * Math.sin(phy)) / 2));
    prevPhy = phy;
    phy = 2 * Math.atan(Math.exp(S)) - Math.PI / 2;
  }

  p.x = lambda;
  p.y = phy;
  return p;
};

exports.names = ["somerc"];

},{}],"proj4/lib/projections/stere":[function(require,module,exports){
var HALF_PI = Math.PI/2;
var EPSLN = 1.0e-10;
var sign = require('../common/sign');
var msfnz = require('../common/msfnz');
var tsfnz = require('../common/tsfnz');
var phi2z = require('../common/phi2z');
var adjust_lon = require('../common/adjust_lon');
exports.ssfn_ = function(phit, sinphi, eccen) {
  sinphi *= eccen;
  return (Math.tan(0.5 * (HALF_PI + phit)) * Math.pow((1 - sinphi) / (1 + sinphi), 0.5 * eccen));
};

exports.init = function() {
  this.coslat0 = Math.cos(this.lat0);
  this.sinlat0 = Math.sin(this.lat0);
  if (this.sphere) {
    if (this.k0 === 1 && !isNaN(this.lat_ts) && Math.abs(this.coslat0) <= EPSLN) {
      this.k0 = 0.5 * (1 + sign(this.lat0) * Math.sin(this.lat_ts));
    }
  }
  else {
    if (Math.abs(this.coslat0) <= EPSLN) {
      if (this.lat0 > 0) {
        //North pole
        //trace('stere:north pole');
        this.con = 1;
      }
      else {
        //South pole
        //trace('stere:south pole');
        this.con = -1;
      }
    }
    this.cons = Math.sqrt(Math.pow(1 + this.e, 1 + this.e) * Math.pow(1 - this.e, 1 - this.e));
    if (this.k0 === 1 && !isNaN(this.lat_ts) && Math.abs(this.coslat0) <= EPSLN) {
      this.k0 = 0.5 * this.cons * msfnz(this.e, Math.sin(this.lat_ts), Math.cos(this.lat_ts)) / tsfnz(this.e, this.con * this.lat_ts, this.con * Math.sin(this.lat_ts));
    }
    this.ms1 = msfnz(this.e, this.sinlat0, this.coslat0);
    this.X0 = 2 * Math.atan(this.ssfn_(this.lat0, this.sinlat0, this.e)) - HALF_PI;
    this.cosX0 = Math.cos(this.X0);
    this.sinX0 = Math.sin(this.X0);
  }
};

// Stereographic forward equations--mapping lat,long to x,y
exports.forward = function(p) {
  var lon = p.x;
  var lat = p.y;
  var sinlat = Math.sin(lat);
  var coslat = Math.cos(lat);
  var A, X, sinX, cosX, ts, rh;
  var dlon = adjust_lon(lon - this.long0);

  if (Math.abs(Math.abs(lon - this.long0) - Math.PI) <= EPSLN && Math.abs(lat + this.lat0) <= EPSLN) {
    //case of the origine point
    //trace('stere:this is the origin point');
    p.x = NaN;
    p.y = NaN;
    return p;
  }
  if (this.sphere) {
    //trace('stere:sphere case');
    A = 2 * this.k0 / (1 + this.sinlat0 * sinlat + this.coslat0 * coslat * Math.cos(dlon));
    p.x = this.a * A * coslat * Math.sin(dlon) + this.x0;
    p.y = this.a * A * (this.coslat0 * sinlat - this.sinlat0 * coslat * Math.cos(dlon)) + this.y0;
    return p;
  }
  else {
    X = 2 * Math.atan(this.ssfn_(lat, sinlat, this.e)) - HALF_PI;
    cosX = Math.cos(X);
    sinX = Math.sin(X);
    if (Math.abs(this.coslat0) <= EPSLN) {
      ts = tsfnz(this.e, lat * this.con, this.con * sinlat);
      rh = 2 * this.a * this.k0 * ts / this.cons;
      p.x = this.x0 + rh * Math.sin(lon - this.long0);
      p.y = this.y0 - this.con * rh * Math.cos(lon - this.long0);
      //trace(p.toString());
      return p;
    }
    else if (Math.abs(this.sinlat0) < EPSLN) {
      //Eq
      //trace('stere:equateur');
      A = 2 * this.a * this.k0 / (1 + cosX * Math.cos(dlon));
      p.y = A * sinX;
    }
    else {
      //other case
      //trace('stere:normal case');
      A = 2 * this.a * this.k0 * this.ms1 / (this.cosX0 * (1 + this.sinX0 * sinX + this.cosX0 * cosX * Math.cos(dlon)));
      p.y = A * (this.cosX0 * sinX - this.sinX0 * cosX * Math.cos(dlon)) + this.y0;
    }
    p.x = A * cosX * Math.sin(dlon) + this.x0;
  }
  //trace(p.toString());
  return p;
};


//* Stereographic inverse equations--mapping x,y to lat/long
exports.inverse = function(p) {
  p.x -= this.x0;
  p.y -= this.y0;
  var lon, lat, ts, ce, Chi;
  var rh = Math.sqrt(p.x * p.x + p.y * p.y);
  if (this.sphere) {
    var c = 2 * Math.atan(rh / (0.5 * this.a * this.k0));
    lon = this.long0;
    lat = this.lat0;
    if (rh <= EPSLN) {
      p.x = lon;
      p.y = lat;
      return p;
    }
    lat = Math.asin(Math.cos(c) * this.sinlat0 + p.y * Math.sin(c) * this.coslat0 / rh);
    if (Math.abs(this.coslat0) < EPSLN) {
      if (this.lat0 > 0) {
        lon = adjust_lon(this.long0 + Math.atan2(p.x, - 1 * p.y));
      }
      else {
        lon = adjust_lon(this.long0 + Math.atan2(p.x, p.y));
      }
    }
    else {
      lon = adjust_lon(this.long0 + Math.atan2(p.x * Math.sin(c), rh * this.coslat0 * Math.cos(c) - p.y * this.sinlat0 * Math.sin(c)));
    }
    p.x = lon;
    p.y = lat;
    return p;
  }
  else {
    if (Math.abs(this.coslat0) <= EPSLN) {
      if (rh <= EPSLN) {
        lat = this.lat0;
        lon = this.long0;
        p.x = lon;
        p.y = lat;
        //trace(p.toString());
        return p;
      }
      p.x *= this.con;
      p.y *= this.con;
      ts = rh * this.cons / (2 * this.a * this.k0);
      lat = this.con * phi2z(this.e, ts);
      lon = this.con * adjust_lon(this.con * this.long0 + Math.atan2(p.x, - 1 * p.y));
    }
    else {
      ce = 2 * Math.atan(rh * this.cosX0 / (2 * this.a * this.k0 * this.ms1));
      lon = this.long0;
      if (rh <= EPSLN) {
        Chi = this.X0;
      }
      else {
        Chi = Math.asin(Math.cos(ce) * this.sinX0 + p.y * Math.sin(ce) * this.cosX0 / rh);
        lon = adjust_lon(this.long0 + Math.atan2(p.x * Math.sin(ce), rh * this.cosX0 * Math.cos(ce) - p.y * this.sinX0 * Math.sin(ce)));
      }
      lat = -1 * phi2z(this.e, Math.tan(0.5 * (HALF_PI + Chi)));
    }
  }
  p.x = lon;
  p.y = lat;

  //trace(p.toString());
  return p;

};
exports.names = ["stere", "Stereographic_South_Pole", "Polar Stereographic (variant B)"];

},{"../common/adjust_lon":"proj4/lib/common/adjust_lon","../common/msfnz":"proj4/lib/common/msfnz","../common/phi2z":"proj4/lib/common/phi2z","../common/sign":"proj4/lib/common/sign","../common/tsfnz":"proj4/lib/common/tsfnz"}],"proj4/lib/projections/sterea":[function(require,module,exports){
var gauss = require('./gauss');
var adjust_lon = require('../common/adjust_lon');
exports.init = function() {
  gauss.init.apply(this);
  if (!this.rc) {
    return;
  }
  this.sinc0 = Math.sin(this.phic0);
  this.cosc0 = Math.cos(this.phic0);
  this.R2 = 2 * this.rc;
  if (!this.title) {
    this.title = "Oblique Stereographic Alternative";
  }
};

exports.forward = function(p) {
  var sinc, cosc, cosl, k;
  p.x = adjust_lon(p.x - this.long0);
  gauss.forward.apply(this, [p]);
  sinc = Math.sin(p.y);
  cosc = Math.cos(p.y);
  cosl = Math.cos(p.x);
  k = this.k0 * this.R2 / (1 + this.sinc0 * sinc + this.cosc0 * cosc * cosl);
  p.x = k * cosc * Math.sin(p.x);
  p.y = k * (this.cosc0 * sinc - this.sinc0 * cosc * cosl);
  p.x = this.a * p.x + this.x0;
  p.y = this.a * p.y + this.y0;
  return p;
};

exports.inverse = function(p) {
  var sinc, cosc, lon, lat, rho;
  p.x = (p.x - this.x0) / this.a;
  p.y = (p.y - this.y0) / this.a;

  p.x /= this.k0;
  p.y /= this.k0;
  if ((rho = Math.sqrt(p.x * p.x + p.y * p.y))) {
    var c = 2 * Math.atan2(rho, this.R2);
    sinc = Math.sin(c);
    cosc = Math.cos(c);
    lat = Math.asin(cosc * this.sinc0 + p.y * sinc * this.cosc0 / rho);
    lon = Math.atan2(p.x * sinc, rho * this.cosc0 * cosc - p.y * this.sinc0 * sinc);
  }
  else {
    lat = this.phic0;
    lon = 0;
  }

  p.x = lon;
  p.y = lat;
  gauss.inverse.apply(this, [p]);
  p.x = adjust_lon(p.x + this.long0);
  return p;
};

exports.names = ["Stereographic_North_Pole", "Oblique_Stereographic", "Polar_Stereographic", "sterea","Oblique Stereographic Alternative"];

},{"../common/adjust_lon":"proj4/lib/common/adjust_lon","./gauss":"proj4/lib/projections/gauss"}],"proj4/lib/projections/tmerc":[function(require,module,exports){
var e0fn = require('../common/e0fn');
var e1fn = require('../common/e1fn');
var e2fn = require('../common/e2fn');
var e3fn = require('../common/e3fn');
var mlfn = require('../common/mlfn');
var adjust_lon = require('../common/adjust_lon');
var HALF_PI = Math.PI/2;
var EPSLN = 1.0e-10;
var sign = require('../common/sign');
var asinz = require('../common/asinz');

exports.init = function() {
  this.e0 = e0fn(this.es);
  this.e1 = e1fn(this.es);
  this.e2 = e2fn(this.es);
  this.e3 = e3fn(this.es);
  this.ml0 = this.a * mlfn(this.e0, this.e1, this.e2, this.e3, this.lat0);
};

/**
    Transverse Mercator Forward  - long/lat to x/y
    long/lat in radians
  */
exports.forward = function(p) {
  var lon = p.x;
  var lat = p.y;

  var delta_lon = adjust_lon(lon - this.long0);
  var con;
  var x, y;
  var sin_phi = Math.sin(lat);
  var cos_phi = Math.cos(lat);

  if (this.sphere) {
    var b = cos_phi * Math.sin(delta_lon);
    if ((Math.abs(Math.abs(b) - 1)) < 0.0000000001) {
      return (93);
    }
    else {
      x = 0.5 * this.a * this.k0 * Math.log((1 + b) / (1 - b));
      con = Math.acos(cos_phi * Math.cos(delta_lon) / Math.sqrt(1 - b * b));
      if (lat < 0) {
        con = -con;
      }
      y = this.a * this.k0 * (con - this.lat0);
    }
  }
  else {
    var al = cos_phi * delta_lon;
    var als = Math.pow(al, 2);
    var c = this.ep2 * Math.pow(cos_phi, 2);
    var tq = Math.tan(lat);
    var t = Math.pow(tq, 2);
    con = 1 - this.es * Math.pow(sin_phi, 2);
    var n = this.a / Math.sqrt(con);
    var ml = this.a * mlfn(this.e0, this.e1, this.e2, this.e3, lat);

    x = this.k0 * n * al * (1 + als / 6 * (1 - t + c + als / 20 * (5 - 18 * t + Math.pow(t, 2) + 72 * c - 58 * this.ep2))) + this.x0;
    y = this.k0 * (ml - this.ml0 + n * tq * (als * (0.5 + als / 24 * (5 - t + 9 * c + 4 * Math.pow(c, 2) + als / 30 * (61 - 58 * t + Math.pow(t, 2) + 600 * c - 330 * this.ep2))))) + this.y0;

  }
  p.x = x;
  p.y = y;
  return p;
};

/**
    Transverse Mercator Inverse  -  x/y to long/lat
  */
exports.inverse = function(p) {
  var con, phi;
  var delta_phi;
  var i;
  var max_iter = 6;
  var lat, lon;

  if (this.sphere) {
    var f = Math.exp(p.x / (this.a * this.k0));
    var g = 0.5 * (f - 1 / f);
    var temp = this.lat0 + p.y / (this.a * this.k0);
    var h = Math.cos(temp);
    con = Math.sqrt((1 - h * h) / (1 + g * g));
    lat = asinz(con);
    if (temp < 0) {
      lat = -lat;
    }
    if ((g === 0) && (h === 0)) {
      lon = this.long0;
    }
    else {
      lon = adjust_lon(Math.atan2(g, h) + this.long0);
    }
  }
  else { // ellipsoidal form
    var x = p.x - this.x0;
    var y = p.y - this.y0;

    con = (this.ml0 + y / this.k0) / this.a;
    phi = con;
    for (i = 0; true; i++) {
      delta_phi = ((con + this.e1 * Math.sin(2 * phi) - this.e2 * Math.sin(4 * phi) + this.e3 * Math.sin(6 * phi)) / this.e0) - phi;
      phi += delta_phi;
      if (Math.abs(delta_phi) <= EPSLN) {
        break;
      }
      if (i >= max_iter) {
        return (95);
      }
    } // for()
    if (Math.abs(phi) < HALF_PI) {
      var sin_phi = Math.sin(phi);
      var cos_phi = Math.cos(phi);
      var tan_phi = Math.tan(phi);
      var c = this.ep2 * Math.pow(cos_phi, 2);
      var cs = Math.pow(c, 2);
      var t = Math.pow(tan_phi, 2);
      var ts = Math.pow(t, 2);
      con = 1 - this.es * Math.pow(sin_phi, 2);
      var n = this.a / Math.sqrt(con);
      var r = n * (1 - this.es) / con;
      var d = x / (n * this.k0);
      var ds = Math.pow(d, 2);
      lat = phi - (n * tan_phi * ds / r) * (0.5 - ds / 24 * (5 + 3 * t + 10 * c - 4 * cs - 9 * this.ep2 - ds / 30 * (61 + 90 * t + 298 * c + 45 * ts - 252 * this.ep2 - 3 * cs)));
      lon = adjust_lon(this.long0 + (d * (1 - ds / 6 * (1 + 2 * t + c - ds / 20 * (5 - 2 * c + 28 * t - 3 * cs + 8 * this.ep2 + 24 * ts))) / cos_phi));
    }
    else {
      lat = HALF_PI * sign(y);
      lon = this.long0;
    }
  }
  p.x = lon;
  p.y = lat;
  return p;
};
exports.names = ["Transverse_Mercator", "Transverse Mercator", "tmerc"];

},{"../common/adjust_lon":"proj4/lib/common/adjust_lon","../common/asinz":"proj4/lib/common/asinz","../common/e0fn":"proj4/lib/common/e0fn","../common/e1fn":"proj4/lib/common/e1fn","../common/e2fn":"proj4/lib/common/e2fn","../common/e3fn":"proj4/lib/common/e3fn","../common/mlfn":"proj4/lib/common/mlfn","../common/sign":"proj4/lib/common/sign"}],"proj4/lib/projections/utm":[function(require,module,exports){
var D2R = 0.01745329251994329577;
var tmerc = require('./tmerc');
exports.dependsOn = 'tmerc';
exports.init = function() {
  if (!this.zone) {
    return;
  }
  this.lat0 = 0;
  this.long0 = ((6 * Math.abs(this.zone)) - 183) * D2R;
  this.x0 = 500000;
  this.y0 = this.utmSouth ? 10000000 : 0;
  this.k0 = 0.9996;

  tmerc.init.apply(this);
  this.forward = tmerc.forward;
  this.inverse = tmerc.inverse;
};
exports.names = ["Universal Transverse Mercator System", "utm"];

},{"./tmerc":"proj4/lib/projections/tmerc"}],"proj4/lib/projections/vandg":[function(require,module,exports){
var adjust_lon = require('../common/adjust_lon');
var HALF_PI = Math.PI/2;
var EPSLN = 1.0e-10;
var asinz = require('../common/asinz');
/* Initialize the Van Der Grinten projection
  ----------------------------------------*/
exports.init = function() {
  //this.R = 6370997; //Radius of earth
  this.R = this.a;
};

exports.forward = function(p) {

  var lon = p.x;
  var lat = p.y;

  /* Forward equations
    -----------------*/
  var dlon = adjust_lon(lon - this.long0);
  var x, y;

  if (Math.abs(lat) <= EPSLN) {
    x = this.x0 + this.R * dlon;
    y = this.y0;
  }
  var theta = asinz(2 * Math.abs(lat / Math.PI));
  if ((Math.abs(dlon) <= EPSLN) || (Math.abs(Math.abs(lat) - HALF_PI) <= EPSLN)) {
    x = this.x0;
    if (lat >= 0) {
      y = this.y0 + Math.PI * this.R * Math.tan(0.5 * theta);
    }
    else {
      y = this.y0 + Math.PI * this.R * -Math.tan(0.5 * theta);
    }
    //  return(OK);
  }
  var al = 0.5 * Math.abs((Math.PI / dlon) - (dlon / Math.PI));
  var asq = al * al;
  var sinth = Math.sin(theta);
  var costh = Math.cos(theta);

  var g = costh / (sinth + costh - 1);
  var gsq = g * g;
  var m = g * (2 / sinth - 1);
  var msq = m * m;
  var con = Math.PI * this.R * (al * (g - msq) + Math.sqrt(asq * (g - msq) * (g - msq) - (msq + asq) * (gsq - msq))) / (msq + asq);
  if (dlon < 0) {
    con = -con;
  }
  x = this.x0 + con;
  //con = Math.abs(con / (Math.PI * this.R));
  var q = asq + g;
  con = Math.PI * this.R * (m * q - al * Math.sqrt((msq + asq) * (asq + 1) - q * q)) / (msq + asq);
  if (lat >= 0) {
    //y = this.y0 + Math.PI * this.R * Math.sqrt(1 - con * con - 2 * al * con);
    y = this.y0 + con;
  }
  else {
    //y = this.y0 - Math.PI * this.R * Math.sqrt(1 - con * con - 2 * al * con);
    y = this.y0 - con;
  }
  p.x = x;
  p.y = y;
  return p;
};

/* Van Der Grinten inverse equations--mapping x,y to lat/long
  ---------------------------------------------------------*/
exports.inverse = function(p) {
  var lon, lat;
  var xx, yy, xys, c1, c2, c3;
  var a1;
  var m1;
  var con;
  var th1;
  var d;

  /* inverse equations
    -----------------*/
  p.x -= this.x0;
  p.y -= this.y0;
  con = Math.PI * this.R;
  xx = p.x / con;
  yy = p.y / con;
  xys = xx * xx + yy * yy;
  c1 = -Math.abs(yy) * (1 + xys);
  c2 = c1 - 2 * yy * yy + xx * xx;
  c3 = -2 * c1 + 1 + 2 * yy * yy + xys * xys;
  d = yy * yy / c3 + (2 * c2 * c2 * c2 / c3 / c3 / c3 - 9 * c1 * c2 / c3 / c3) / 27;
  a1 = (c1 - c2 * c2 / 3 / c3) / c3;
  m1 = 2 * Math.sqrt(-a1 / 3);
  con = ((3 * d) / a1) / m1;
  if (Math.abs(con) > 1) {
    if (con >= 0) {
      con = 1;
    }
    else {
      con = -1;
    }
  }
  th1 = Math.acos(con) / 3;
  if (p.y >= 0) {
    lat = (-m1 * Math.cos(th1 + Math.PI / 3) - c2 / 3 / c3) * Math.PI;
  }
  else {
    lat = -(-m1 * Math.cos(th1 + Math.PI / 3) - c2 / 3 / c3) * Math.PI;
  }

  if (Math.abs(xx) < EPSLN) {
    lon = this.long0;
  }
  else {
    lon = adjust_lon(this.long0 + Math.PI * (xys - 1 + Math.sqrt(1 + 2 * (xx * xx - yy * yy) + xys * xys)) / 2 / xx);
  }

  p.x = lon;
  p.y = lat;
  return p;
};
exports.names = ["Van_der_Grinten_I", "VanDerGrinten", "vandg"];
},{"../common/adjust_lon":"proj4/lib/common/adjust_lon","../common/asinz":"proj4/lib/common/asinz"}],"proj4/lib/transform":[function(require,module,exports){
var D2R = 0.01745329251994329577;
var R2D = 57.29577951308232088;
var PJD_3PARAM = 1;
var PJD_7PARAM = 2;
var datum_transform = require('./datum_transform');
var adjust_axis = require('./adjust_axis');
var proj = require('./Proj');
var toPoint = require('./common/toPoint');
module.exports = function transform(source, dest, point) {
  var wgs84;
  if (Array.isArray(point)) {
    point = toPoint(point);
  }
  function checkNotWGS(source, dest) {
    return ((source.datum.datum_type === PJD_3PARAM || source.datum.datum_type === PJD_7PARAM) && dest.datumCode !== "WGS84");
  }

  // Workaround for datum shifts towgs84, if either source or destination projection is not wgs84
  if (source.datum && dest.datum && (checkNotWGS(source, dest) || checkNotWGS(dest, source))) {
    wgs84 = new proj('WGS84');
    transform(source, wgs84, point);
    source = wgs84;
  }
  // DGR, 2010/11/12
  if (source.axis !== "enu") {
    adjust_axis(source, false, point);
  }
  // Transform source points to long/lat, if they aren't already.
  if (source.projName === "longlat") {
    point.x *= D2R; // convert degrees to radians
    point.y *= D2R;
  }
  else {
    if (source.to_meter) {
      point.x *= source.to_meter;
      point.y *= source.to_meter;
    }
    source.inverse(point); // Convert Cartesian to longlat
  }
  // Adjust for the prime meridian if necessary
  if (source.from_greenwich) {
    point.x += source.from_greenwich;
  }

  // Convert datums if needed, and if possible.
  point = datum_transform(source.datum, dest.datum, point);

  // Adjust for the prime meridian if necessary
  if (dest.from_greenwich) {
    point.x -= dest.from_greenwich;
  }

  if (dest.projName === "longlat") {
    // convert radians to decimal degrees
    point.x *= R2D;
    point.y *= R2D;
  }
  else { // else project
    dest.forward(point);
    if (dest.to_meter) {
      point.x /= dest.to_meter;
      point.y /= dest.to_meter;
    }
  }

  // DGR, 2010/11/12
  if (dest.axis !== "enu") {
    adjust_axis(dest, true, point);
  }

  return point;
};
},{"./Proj":"proj4/lib/Proj","./adjust_axis":"proj4/lib/adjust_axis","./common/toPoint":"proj4/lib/common/toPoint","./datum_transform":"proj4/lib/datum_transform"}],"proj4/lib/wkt":[function(require,module,exports){
var D2R = 0.01745329251994329577;
var extend = require('./extend');

function mapit(obj, key, v) {
  obj[key] = v.map(function(aa) {
    var o = {};
    sExpr(aa, o);
    return o;
  }).reduce(function(a, b) {
    return extend(a, b);
  }, {});
}

function sExpr(v, obj) {
  var key;
  if (!Array.isArray(v)) {
    obj[v] = true;
    return;
  }
  else {
    key = v.shift();
    if (key === 'PARAMETER') {
      key = v.shift();
    }
    if (v.length === 1) {
      if (Array.isArray(v[0])) {
        obj[key] = {};
        sExpr(v[0], obj[key]);
      }
      else {
        obj[key] = v[0];
      }
    }
    else if (!v.length) {
      obj[key] = true;
    }
    else if (key === 'TOWGS84') {
      obj[key] = v;
    }
    else {
      obj[key] = {};
      if (['UNIT', 'PRIMEM', 'VERT_DATUM'].indexOf(key) > -1) {
        obj[key] = {
          name: v[0].toLowerCase(),
          convert: v[1]
        };
        if (v.length === 3) {
          obj[key].auth = v[2];
        }
      }
      else if (key === 'SPHEROID') {
        obj[key] = {
          name: v[0],
          a: v[1],
          rf: v[2]
        };
        if (v.length === 4) {
          obj[key].auth = v[3];
        }
      }
      else if (['GEOGCS', 'GEOCCS', 'DATUM', 'VERT_CS', 'COMPD_CS', 'LOCAL_CS', 'FITTED_CS', 'LOCAL_DATUM'].indexOf(key) > -1) {
        v[0] = ['name', v[0]];
        mapit(obj, key, v);
      }
      else if (v.every(function(aa) {
        return Array.isArray(aa);
      })) {
        mapit(obj, key, v);
      }
      else {
        sExpr(v, obj[key]);
      }
    }
  }
}

function rename(obj, params) {
  var outName = params[0];
  var inName = params[1];
  if (!(outName in obj) && (inName in obj)) {
    obj[outName] = obj[inName];
    if (params.length === 3) {
      obj[outName] = params[2](obj[outName]);
    }
  }
}

function d2r(input) {
  return input * D2R;
}

function cleanWKT(wkt) {
  if (wkt.type === 'GEOGCS') {
    wkt.projName = 'longlat';
  }
  else if (wkt.type === 'LOCAL_CS') {
    wkt.projName = 'identity';
    wkt.local = true;
  }
  else {
    if (typeof wkt.PROJECTION === "object") {
      wkt.projName = Object.keys(wkt.PROJECTION)[0];
    }
    else {
      wkt.projName = wkt.PROJECTION;
    }
  }
  if (wkt.UNIT) {
    wkt.units = wkt.UNIT.name.toLowerCase();
    if (wkt.units === 'metre') {
      wkt.units = 'meter';
    }
    if (wkt.UNIT.convert) {
      if (wkt.type === 'GEOGCS') {
        if (wkt.DATUM && wkt.DATUM.SPHEROID) {
          wkt.to_meter = parseFloat(wkt.UNIT.convert, 10)*wkt.DATUM.SPHEROID.a;
        }
      } else {
        wkt.to_meter = parseFloat(wkt.UNIT.convert, 10);
      }
    }
  }

  if (wkt.GEOGCS) {
    //if(wkt.GEOGCS.PRIMEM&&wkt.GEOGCS.PRIMEM.convert){
    //  wkt.from_greenwich=wkt.GEOGCS.PRIMEM.convert*D2R;
    //}
    if (wkt.GEOGCS.DATUM) {
      wkt.datumCode = wkt.GEOGCS.DATUM.name.toLowerCase();
    }
    else {
      wkt.datumCode = wkt.GEOGCS.name.toLowerCase();
    }
    if (wkt.datumCode.slice(0, 2) === 'd_') {
      wkt.datumCode = wkt.datumCode.slice(2);
    }
    if (wkt.datumCode === 'new_zealand_geodetic_datum_1949' || wkt.datumCode === 'new_zealand_1949') {
      wkt.datumCode = 'nzgd49';
    }
    if (wkt.datumCode === "wgs_1984") {
      if (wkt.PROJECTION === 'Mercator_Auxiliary_Sphere') {
        wkt.sphere = true;
      }
      wkt.datumCode = 'wgs84';
    }
    if (wkt.datumCode.slice(-6) === '_ferro') {
      wkt.datumCode = wkt.datumCode.slice(0, - 6);
    }
    if (wkt.datumCode.slice(-8) === '_jakarta') {
      wkt.datumCode = wkt.datumCode.slice(0, - 8);
    }
    if (~wkt.datumCode.indexOf('belge')) {
      wkt.datumCode = "rnb72";
    }
    if (wkt.GEOGCS.DATUM && wkt.GEOGCS.DATUM.SPHEROID) {
      wkt.ellps = wkt.GEOGCS.DATUM.SPHEROID.name.replace('_19', '').replace(/[Cc]larke\_18/, 'clrk');
      if (wkt.ellps.toLowerCase().slice(0, 13) === "international") {
        wkt.ellps = 'intl';
      }

      wkt.a = wkt.GEOGCS.DATUM.SPHEROID.a;
      wkt.rf = parseFloat(wkt.GEOGCS.DATUM.SPHEROID.rf, 10);
    }
    if (~wkt.datumCode.indexOf('osgb_1936')) {
      wkt.datumCode = "osgb36";
    }
  }
  if (wkt.b && !isFinite(wkt.b)) {
    wkt.b = wkt.a;
  }

  function toMeter(input) {
    var ratio = wkt.to_meter || 1;
    return parseFloat(input, 10) * ratio;
  }
  var renamer = function(a) {
    return rename(wkt, a);
  };
  var list = [
    ['standard_parallel_1', 'Standard_Parallel_1'],
    ['standard_parallel_2', 'Standard_Parallel_2'],
    ['false_easting', 'False_Easting'],
    ['false_northing', 'False_Northing'],
    ['central_meridian', 'Central_Meridian'],
    ['latitude_of_origin', 'Latitude_Of_Origin'],
    ['latitude_of_origin', 'Central_Parallel'],
    ['scale_factor', 'Scale_Factor'],
    ['k0', 'scale_factor'],
    ['latitude_of_center', 'Latitude_of_center'],
    ['lat0', 'latitude_of_center', d2r],
    ['longitude_of_center', 'Longitude_Of_Center'],
    ['longc', 'longitude_of_center', d2r],
    ['x0', 'false_easting', toMeter],
    ['y0', 'false_northing', toMeter],
    ['long0', 'central_meridian', d2r],
    ['lat0', 'latitude_of_origin', d2r],
    ['lat0', 'standard_parallel_1', d2r],
    ['lat1', 'standard_parallel_1', d2r],
    ['lat2', 'standard_parallel_2', d2r],
    ['alpha', 'azimuth', d2r],
    ['srsCode', 'name']
  ];
  list.forEach(renamer);
  if (!wkt.long0 && wkt.longc && (wkt.projName === 'Albers_Conic_Equal_Area' || wkt.projName === "Lambert_Azimuthal_Equal_Area")) {
    wkt.long0 = wkt.longc;
  }
  if (!wkt.lat_ts && wkt.lat1 && (wkt.projName === 'Stereographic_South_Pole' || wkt.projName === 'Polar Stereographic (variant B)')) {
    wkt.lat0 = d2r(wkt.lat1 > 0 ? 90 : -90);
    wkt.lat_ts = wkt.lat1;
  }
}
module.exports = function(wkt, self) {
  var lisp = JSON.parse(("," + wkt).replace(/\s*\,\s*([A-Z_0-9]+?)(\[)/g, ',["$1",').slice(1).replace(/\s*\,\s*([A-Z_0-9]+?)\]/g, ',"$1"]').replace(/,\["VERTCS".+/,''));
  var type = lisp.shift();
  var name = lisp.shift();
  lisp.unshift(['name', name]);
  lisp.unshift(['type', type]);
  lisp.unshift('output');
  var obj = {};
  sExpr(lisp, obj);
  cleanWKT(obj.output);
  return extend(self, obj.output);
};

},{"./extend":"proj4/lib/extend"}],"proj4/node_modules/mgrs/mgrs":[function(require,module,exports){



/**
 * UTM zones are grouped, and assigned to one of a group of 6
 * sets.
 *
 * {int} @private
 */
var NUM_100K_SETS = 6;

/**
 * The column letters (for easting) of the lower left value, per
 * set.
 *
 * {string} @private
 */
var SET_ORIGIN_COLUMN_LETTERS = 'AJSAJS';

/**
 * The row letters (for northing) of the lower left value, per
 * set.
 *
 * {string} @private
 */
var SET_ORIGIN_ROW_LETTERS = 'AFAFAF';

var A = 65; // A
var I = 73; // I
var O = 79; // O
var V = 86; // V
var Z = 90; // Z

/**
 * Conversion of lat/lon to MGRS.
 *
 * @param {object} ll Object literal with lat and lon properties on a
 *     WGS84 ellipsoid.
 * @param {int} accuracy Accuracy in digits (5 for 1 m, 4 for 10 m, 3 for
 *      100 m, 2 for 1000 m or 1 for 10000 m). Optional, default is 5.
 * @return {string} the MGRS string for the given location and accuracy.
 */
exports.forward = function(ll, accuracy) {
  accuracy = accuracy || 5; // default accuracy 1m
  return encode(LLtoUTM({
    lat: ll[1],
    lon: ll[0]
  }), accuracy);
};

/**
 * Conversion of MGRS to lat/lon.
 *
 * @param {string} mgrs MGRS string.
 * @return {array} An array with left (longitude), bottom (latitude), right
 *     (longitude) and top (latitude) values in WGS84, representing the
 *     bounding box for the provided MGRS reference.
 */
exports.inverse = function(mgrs) {
  var bbox = UTMtoLL(decode(mgrs.toUpperCase()));
  if (bbox.lat && bbox.lon) {
    return [bbox.lon, bbox.lat, bbox.lon, bbox.lat];
  }
  return [bbox.left, bbox.bottom, bbox.right, bbox.top];
};

exports.toPoint = function(mgrs) {
  var bbox = UTMtoLL(decode(mgrs.toUpperCase()));
  if (bbox.lat && bbox.lon) {
    return [bbox.lon, bbox.lat];
  }
  return [(bbox.left + bbox.right) / 2, (bbox.top + bbox.bottom) / 2];
};
/**
 * Conversion from degrees to radians.
 *
 * @private
 * @param {number} deg the angle in degrees.
 * @return {number} the angle in radians.
 */
function degToRad(deg) {
  return (deg * (Math.PI / 180.0));
}

/**
 * Conversion from radians to degrees.
 *
 * @private
 * @param {number} rad the angle in radians.
 * @return {number} the angle in degrees.
 */
function radToDeg(rad) {
  return (180.0 * (rad / Math.PI));
}

/**
 * Converts a set of Longitude and Latitude co-ordinates to UTM
 * using the WGS84 ellipsoid.
 *
 * @private
 * @param {object} ll Object literal with lat and lon properties
 *     representing the WGS84 coordinate to be converted.
 * @return {object} Object literal containing the UTM value with easting,
 *     northing, zoneNumber and zoneLetter properties, and an optional
 *     accuracy property in digits. Returns null if the conversion failed.
 */
function LLtoUTM(ll) {
  var Lat = ll.lat;
  var Long = ll.lon;
  var a = 6378137.0; //ellip.radius;
  var eccSquared = 0.00669438; //ellip.eccsq;
  var k0 = 0.9996;
  var LongOrigin;
  var eccPrimeSquared;
  var N, T, C, A, M;
  var LatRad = degToRad(Lat);
  var LongRad = degToRad(Long);
  var LongOriginRad;
  var ZoneNumber;
  // (int)
  ZoneNumber = Math.floor((Long + 180) / 6) + 1;

  //Make sure the longitude 180.00 is in Zone 60
  if (Long === 180) {
    ZoneNumber = 60;
  }

  // Special zone for Norway
  if (Lat >= 56.0 && Lat < 64.0 && Long >= 3.0 && Long < 12.0) {
    ZoneNumber = 32;
  }

  // Special zones for Svalbard
  if (Lat >= 72.0 && Lat < 84.0) {
    if (Long >= 0.0 && Long < 9.0) {
      ZoneNumber = 31;
    }
    else if (Long >= 9.0 && Long < 21.0) {
      ZoneNumber = 33;
    }
    else if (Long >= 21.0 && Long < 33.0) {
      ZoneNumber = 35;
    }
    else if (Long >= 33.0 && Long < 42.0) {
      ZoneNumber = 37;
    }
  }

  LongOrigin = (ZoneNumber - 1) * 6 - 180 + 3; //+3 puts origin
  // in middle of
  // zone
  LongOriginRad = degToRad(LongOrigin);

  eccPrimeSquared = (eccSquared) / (1 - eccSquared);

  N = a / Math.sqrt(1 - eccSquared * Math.sin(LatRad) * Math.sin(LatRad));
  T = Math.tan(LatRad) * Math.tan(LatRad);
  C = eccPrimeSquared * Math.cos(LatRad) * Math.cos(LatRad);
  A = Math.cos(LatRad) * (LongRad - LongOriginRad);

  M = a * ((1 - eccSquared / 4 - 3 * eccSquared * eccSquared / 64 - 5 * eccSquared * eccSquared * eccSquared / 256) * LatRad - (3 * eccSquared / 8 + 3 * eccSquared * eccSquared / 32 + 45 * eccSquared * eccSquared * eccSquared / 1024) * Math.sin(2 * LatRad) + (15 * eccSquared * eccSquared / 256 + 45 * eccSquared * eccSquared * eccSquared / 1024) * Math.sin(4 * LatRad) - (35 * eccSquared * eccSquared * eccSquared / 3072) * Math.sin(6 * LatRad));

  var UTMEasting = (k0 * N * (A + (1 - T + C) * A * A * A / 6.0 + (5 - 18 * T + T * T + 72 * C - 58 * eccPrimeSquared) * A * A * A * A * A / 120.0) + 500000.0);

  var UTMNorthing = (k0 * (M + N * Math.tan(LatRad) * (A * A / 2 + (5 - T + 9 * C + 4 * C * C) * A * A * A * A / 24.0 + (61 - 58 * T + T * T + 600 * C - 330 * eccPrimeSquared) * A * A * A * A * A * A / 720.0)));
  if (Lat < 0.0) {
    UTMNorthing += 10000000.0; //10000000 meter offset for
    // southern hemisphere
  }

  return {
    northing: Math.round(UTMNorthing),
    easting: Math.round(UTMEasting),
    zoneNumber: ZoneNumber,
    zoneLetter: getLetterDesignator(Lat)
  };
}

/**
 * Converts UTM coords to lat/long, using the WGS84 ellipsoid. This is a convenience
 * class where the Zone can be specified as a single string eg."60N" which
 * is then broken down into the ZoneNumber and ZoneLetter.
 *
 * @private
 * @param {object} utm An object literal with northing, easting, zoneNumber
 *     and zoneLetter properties. If an optional accuracy property is
 *     provided (in meters), a bounding box will be returned instead of
 *     latitude and longitude.
 * @return {object} An object literal containing either lat and lon values
 *     (if no accuracy was provided), or top, right, bottom and left values
 *     for the bounding box calculated according to the provided accuracy.
 *     Returns null if the conversion failed.
 */
function UTMtoLL(utm) {

  var UTMNorthing = utm.northing;
  var UTMEasting = utm.easting;
  var zoneLetter = utm.zoneLetter;
  var zoneNumber = utm.zoneNumber;
  // check the ZoneNummber is valid
  if (zoneNumber < 0 || zoneNumber > 60) {
    return null;
  }

  var k0 = 0.9996;
  var a = 6378137.0; //ellip.radius;
  var eccSquared = 0.00669438; //ellip.eccsq;
  var eccPrimeSquared;
  var e1 = (1 - Math.sqrt(1 - eccSquared)) / (1 + Math.sqrt(1 - eccSquared));
  var N1, T1, C1, R1, D, M;
  var LongOrigin;
  var mu, phi1Rad;

  // remove 500,000 meter offset for longitude
  var x = UTMEasting - 500000.0;
  var y = UTMNorthing;

  // We must know somehow if we are in the Northern or Southern
  // hemisphere, this is the only time we use the letter So even
  // if the Zone letter isn't exactly correct it should indicate
  // the hemisphere correctly
  if (zoneLetter < 'N') {
    y -= 10000000.0; // remove 10,000,000 meter offset used
    // for southern hemisphere
  }

  // There are 60 zones with zone 1 being at West -180 to -174
  LongOrigin = (zoneNumber - 1) * 6 - 180 + 3; // +3 puts origin
  // in middle of
  // zone

  eccPrimeSquared = (eccSquared) / (1 - eccSquared);

  M = y / k0;
  mu = M / (a * (1 - eccSquared / 4 - 3 * eccSquared * eccSquared / 64 - 5 * eccSquared * eccSquared * eccSquared / 256));

  phi1Rad = mu + (3 * e1 / 2 - 27 * e1 * e1 * e1 / 32) * Math.sin(2 * mu) + (21 * e1 * e1 / 16 - 55 * e1 * e1 * e1 * e1 / 32) * Math.sin(4 * mu) + (151 * e1 * e1 * e1 / 96) * Math.sin(6 * mu);
  // double phi1 = ProjMath.radToDeg(phi1Rad);

  N1 = a / Math.sqrt(1 - eccSquared * Math.sin(phi1Rad) * Math.sin(phi1Rad));
  T1 = Math.tan(phi1Rad) * Math.tan(phi1Rad);
  C1 = eccPrimeSquared * Math.cos(phi1Rad) * Math.cos(phi1Rad);
  R1 = a * (1 - eccSquared) / Math.pow(1 - eccSquared * Math.sin(phi1Rad) * Math.sin(phi1Rad), 1.5);
  D = x / (N1 * k0);

  var lat = phi1Rad - (N1 * Math.tan(phi1Rad) / R1) * (D * D / 2 - (5 + 3 * T1 + 10 * C1 - 4 * C1 * C1 - 9 * eccPrimeSquared) * D * D * D * D / 24 + (61 + 90 * T1 + 298 * C1 + 45 * T1 * T1 - 252 * eccPrimeSquared - 3 * C1 * C1) * D * D * D * D * D * D / 720);
  lat = radToDeg(lat);

  var lon = (D - (1 + 2 * T1 + C1) * D * D * D / 6 + (5 - 2 * C1 + 28 * T1 - 3 * C1 * C1 + 8 * eccPrimeSquared + 24 * T1 * T1) * D * D * D * D * D / 120) / Math.cos(phi1Rad);
  lon = LongOrigin + radToDeg(lon);

  var result;
  if (utm.accuracy) {
    var topRight = UTMtoLL({
      northing: utm.northing + utm.accuracy,
      easting: utm.easting + utm.accuracy,
      zoneLetter: utm.zoneLetter,
      zoneNumber: utm.zoneNumber
    });
    result = {
      top: topRight.lat,
      right: topRight.lon,
      bottom: lat,
      left: lon
    };
  }
  else {
    result = {
      lat: lat,
      lon: lon
    };
  }
  return result;
}

/**
 * Calculates the MGRS letter designator for the given latitude.
 *
 * @private
 * @param {number} lat The latitude in WGS84 to get the letter designator
 *     for.
 * @return {char} The letter designator.
 */
function getLetterDesignator(lat) {
  //This is here as an error flag to show that the Latitude is
  //outside MGRS limits
  var LetterDesignator = 'Z';

  if ((84 >= lat) && (lat >= 72)) {
    LetterDesignator = 'X';
  }
  else if ((72 > lat) && (lat >= 64)) {
    LetterDesignator = 'W';
  }
  else if ((64 > lat) && (lat >= 56)) {
    LetterDesignator = 'V';
  }
  else if ((56 > lat) && (lat >= 48)) {
    LetterDesignator = 'U';
  }
  else if ((48 > lat) && (lat >= 40)) {
    LetterDesignator = 'T';
  }
  else if ((40 > lat) && (lat >= 32)) {
    LetterDesignator = 'S';
  }
  else if ((32 > lat) && (lat >= 24)) {
    LetterDesignator = 'R';
  }
  else if ((24 > lat) && (lat >= 16)) {
    LetterDesignator = 'Q';
  }
  else if ((16 > lat) && (lat >= 8)) {
    LetterDesignator = 'P';
  }
  else if ((8 > lat) && (lat >= 0)) {
    LetterDesignator = 'N';
  }
  else if ((0 > lat) && (lat >= -8)) {
    LetterDesignator = 'M';
  }
  else if ((-8 > lat) && (lat >= -16)) {
    LetterDesignator = 'L';
  }
  else if ((-16 > lat) && (lat >= -24)) {
    LetterDesignator = 'K';
  }
  else if ((-24 > lat) && (lat >= -32)) {
    LetterDesignator = 'J';
  }
  else if ((-32 > lat) && (lat >= -40)) {
    LetterDesignator = 'H';
  }
  else if ((-40 > lat) && (lat >= -48)) {
    LetterDesignator = 'G';
  }
  else if ((-48 > lat) && (lat >= -56)) {
    LetterDesignator = 'F';
  }
  else if ((-56 > lat) && (lat >= -64)) {
    LetterDesignator = 'E';
  }
  else if ((-64 > lat) && (lat >= -72)) {
    LetterDesignator = 'D';
  }
  else if ((-72 > lat) && (lat >= -80)) {
    LetterDesignator = 'C';
  }
  return LetterDesignator;
}

/**
 * Encodes a UTM location as MGRS string.
 *
 * @private
 * @param {object} utm An object literal with easting, northing,
 *     zoneLetter, zoneNumber
 * @param {number} accuracy Accuracy in digits (1-5).
 * @return {string} MGRS string for the given UTM location.
 */
function encode(utm, accuracy) {
  // prepend with leading zeroes
  var seasting = "00000" + utm.easting,
    snorthing = "00000" + utm.northing;

  return utm.zoneNumber + utm.zoneLetter + get100kID(utm.easting, utm.northing, utm.zoneNumber) + seasting.substr(seasting.length - 5, accuracy) + snorthing.substr(snorthing.length - 5, accuracy);
}

/**
 * Get the two letter 100k designator for a given UTM easting,
 * northing and zone number value.
 *
 * @private
 * @param {number} easting
 * @param {number} northing
 * @param {number} zoneNumber
 * @return the two letter 100k designator for the given UTM location.
 */
function get100kID(easting, northing, zoneNumber) {
  var setParm = get100kSetForZone(zoneNumber);
  var setColumn = Math.floor(easting / 100000);
  var setRow = Math.floor(northing / 100000) % 20;
  return getLetter100kID(setColumn, setRow, setParm);
}

/**
 * Given a UTM zone number, figure out the MGRS 100K set it is in.
 *
 * @private
 * @param {number} i An UTM zone number.
 * @return {number} the 100k set the UTM zone is in.
 */
function get100kSetForZone(i) {
  var setParm = i % NUM_100K_SETS;
  if (setParm === 0) {
    setParm = NUM_100K_SETS;
  }

  return setParm;
}

/**
 * Get the two-letter MGRS 100k designator given information
 * translated from the UTM northing, easting and zone number.
 *
 * @private
 * @param {number} column the column index as it relates to the MGRS
 *        100k set spreadsheet, created from the UTM easting.
 *        Values are 1-8.
 * @param {number} row the row index as it relates to the MGRS 100k set
 *        spreadsheet, created from the UTM northing value. Values
 *        are from 0-19.
 * @param {number} parm the set block, as it relates to the MGRS 100k set
 *        spreadsheet, created from the UTM zone. Values are from
 *        1-60.
 * @return two letter MGRS 100k code.
 */
function getLetter100kID(column, row, parm) {
  // colOrigin and rowOrigin are the letters at the origin of the set
  var index = parm - 1;
  var colOrigin = SET_ORIGIN_COLUMN_LETTERS.charCodeAt(index);
  var rowOrigin = SET_ORIGIN_ROW_LETTERS.charCodeAt(index);

  // colInt and rowInt are the letters to build to return
  var colInt = colOrigin + column - 1;
  var rowInt = rowOrigin + row;
  var rollover = false;

  if (colInt > Z) {
    colInt = colInt - Z + A - 1;
    rollover = true;
  }

  if (colInt === I || (colOrigin < I && colInt > I) || ((colInt > I || colOrigin < I) && rollover)) {
    colInt++;
  }

  if (colInt === O || (colOrigin < O && colInt > O) || ((colInt > O || colOrigin < O) && rollover)) {
    colInt++;

    if (colInt === I) {
      colInt++;
    }
  }

  if (colInt > Z) {
    colInt = colInt - Z + A - 1;
  }

  if (rowInt > V) {
    rowInt = rowInt - V + A - 1;
    rollover = true;
  }
  else {
    rollover = false;
  }

  if (((rowInt === I) || ((rowOrigin < I) && (rowInt > I))) || (((rowInt > I) || (rowOrigin < I)) && rollover)) {
    rowInt++;
  }

  if (((rowInt === O) || ((rowOrigin < O) && (rowInt > O))) || (((rowInt > O) || (rowOrigin < O)) && rollover)) {
    rowInt++;

    if (rowInt === I) {
      rowInt++;
    }
  }

  if (rowInt > V) {
    rowInt = rowInt - V + A - 1;
  }

  var twoLetter = String.fromCharCode(colInt) + String.fromCharCode(rowInt);
  return twoLetter;
}

/**
 * Decode the UTM parameters from a MGRS string.
 *
 * @private
 * @param {string} mgrsString an UPPERCASE coordinate string is expected.
 * @return {object} An object literal with easting, northing, zoneLetter,
 *     zoneNumber and accuracy (in meters) properties.
 */
function decode(mgrsString) {

  if (mgrsString && mgrsString.length === 0) {
    throw ("MGRSPoint coverting from nothing");
  }

  var length = mgrsString.length;

  var hunK = null;
  var sb = "";
  var testChar;
  var i = 0;

  // get Zone number
  while (!(/[A-Z]/).test(testChar = mgrsString.charAt(i))) {
    if (i >= 2) {
      throw ("MGRSPoint bad conversion from: " + mgrsString);
    }
    sb += testChar;
    i++;
  }

  var zoneNumber = parseInt(sb, 10);

  if (i === 0 || i + 3 > length) {
    // A good MGRS string has to be 4-5 digits long,
    // ##AAA/#AAA at least.
    throw ("MGRSPoint bad conversion from: " + mgrsString);
  }

  var zoneLetter = mgrsString.charAt(i++);

  // Should we check the zone letter here? Why not.
  if (zoneLetter <= 'A' || zoneLetter === 'B' || zoneLetter === 'Y' || zoneLetter >= 'Z' || zoneLetter === 'I' || zoneLetter === 'O') {
    throw ("MGRSPoint zone letter " + zoneLetter + " not handled: " + mgrsString);
  }

  hunK = mgrsString.substring(i, i += 2);

  var set = get100kSetForZone(zoneNumber);

  var east100k = getEastingFromChar(hunK.charAt(0), set);
  var north100k = getNorthingFromChar(hunK.charAt(1), set);

  // We have a bug where the northing may be 2000000 too low.
  // How
  // do we know when to roll over?

  while (north100k < getMinNorthing(zoneLetter)) {
    north100k += 2000000;
  }

  // calculate the char index for easting/northing separator
  var remainder = length - i;

  if (remainder % 2 !== 0) {
    throw ("MGRSPoint has to have an even number \nof digits after the zone letter and two 100km letters - front \nhalf for easting meters, second half for \nnorthing meters" + mgrsString);
  }

  var sep = remainder / 2;

  var sepEasting = 0.0;
  var sepNorthing = 0.0;
  var accuracyBonus, sepEastingString, sepNorthingString, easting, northing;
  if (sep > 0) {
    accuracyBonus = 100000.0 / Math.pow(10, sep);
    sepEastingString = mgrsString.substring(i, i + sep);
    sepEasting = parseFloat(sepEastingString) * accuracyBonus;
    sepNorthingString = mgrsString.substring(i + sep);
    sepNorthing = parseFloat(sepNorthingString) * accuracyBonus;
  }

  easting = sepEasting + east100k;
  northing = sepNorthing + north100k;

  return {
    easting: easting,
    northing: northing,
    zoneLetter: zoneLetter,
    zoneNumber: zoneNumber,
    accuracy: accuracyBonus
  };
}

/**
 * Given the first letter from a two-letter MGRS 100k zone, and given the
 * MGRS table set for the zone number, figure out the easting value that
 * should be added to the other, secondary easting value.
 *
 * @private
 * @param {char} e The first letter from a two-letter MGRS 100´k zone.
 * @param {number} set The MGRS table set for the zone number.
 * @return {number} The easting value for the given letter and set.
 */
function getEastingFromChar(e, set) {
  // colOrigin is the letter at the origin of the set for the
  // column
  var curCol = SET_ORIGIN_COLUMN_LETTERS.charCodeAt(set - 1);
  var eastingValue = 100000.0;
  var rewindMarker = false;

  while (curCol !== e.charCodeAt(0)) {
    curCol++;
    if (curCol === I) {
      curCol++;
    }
    if (curCol === O) {
      curCol++;
    }
    if (curCol > Z) {
      if (rewindMarker) {
        throw ("Bad character: " + e);
      }
      curCol = A;
      rewindMarker = true;
    }
    eastingValue += 100000.0;
  }

  return eastingValue;
}

/**
 * Given the second letter from a two-letter MGRS 100k zone, and given the
 * MGRS table set for the zone number, figure out the northing value that
 * should be added to the other, secondary northing value. You have to
 * remember that Northings are determined from the equator, and the vertical
 * cycle of letters mean a 2000000 additional northing meters. This happens
 * approx. every 18 degrees of latitude. This method does *NOT* count any
 * additional northings. You have to figure out how many 2000000 meters need
 * to be added for the zone letter of the MGRS coordinate.
 *
 * @private
 * @param {char} n Second letter of the MGRS 100k zone
 * @param {number} set The MGRS table set number, which is dependent on the
 *     UTM zone number.
 * @return {number} The northing value for the given letter and set.
 */
function getNorthingFromChar(n, set) {

  if (n > 'V') {
    throw ("MGRSPoint given invalid Northing " + n);
  }

  // rowOrigin is the letter at the origin of the set for the
  // column
  var curRow = SET_ORIGIN_ROW_LETTERS.charCodeAt(set - 1);
  var northingValue = 0.0;
  var rewindMarker = false;

  while (curRow !== n.charCodeAt(0)) {
    curRow++;
    if (curRow === I) {
      curRow++;
    }
    if (curRow === O) {
      curRow++;
    }
    // fixing a bug making whole application hang in this loop
    // when 'n' is a wrong character
    if (curRow > V) {
      if (rewindMarker) { // making sure that this loop ends
        throw ("Bad character: " + n);
      }
      curRow = A;
      rewindMarker = true;
    }
    northingValue += 100000.0;
  }

  return northingValue;
}

/**
 * The function getMinNorthing returns the minimum northing value of a MGRS
 * zone.
 *
 * Ported from Geotrans' c Lattitude_Band_Value structure table.
 *
 * @private
 * @param {char} zoneLetter The MGRS zone to get the min northing for.
 * @return {number}
 */
function getMinNorthing(zoneLetter) {
  var northing;
  switch (zoneLetter) {
  case 'C':
    northing = 1100000.0;
    break;
  case 'D':
    northing = 2000000.0;
    break;
  case 'E':
    northing = 2800000.0;
    break;
  case 'F':
    northing = 3700000.0;
    break;
  case 'G':
    northing = 4600000.0;
    break;
  case 'H':
    northing = 5500000.0;
    break;
  case 'J':
    northing = 6400000.0;
    break;
  case 'K':
    northing = 7300000.0;
    break;
  case 'L':
    northing = 8200000.0;
    break;
  case 'M':
    northing = 9100000.0;
    break;
  case 'N':
    northing = 0.0;
    break;
  case 'P':
    northing = 800000.0;
    break;
  case 'Q':
    northing = 1700000.0;
    break;
  case 'R':
    northing = 2600000.0;
    break;
  case 'S':
    northing = 3500000.0;
    break;
  case 'T':
    northing = 4400000.0;
    break;
  case 'U':
    northing = 5300000.0;
    break;
  case 'V':
    northing = 6200000.0;
    break;
  case 'W':
    northing = 7000000.0;
    break;
  case 'X':
    northing = 7900000.0;
    break;
  default:
    northing = -1.0;
  }
  if (northing >= 0.0) {
    return northing;
  }
  else {
    throw ("Invalid zone letter: " + zoneLetter);
  }

}

},{}],"proj4/package.json":[function(require,module,exports){
module.exports={
  "name": "proj4",
  "version": "2.3.12",
  "description": "Proj4js is a JavaScript library to transform point coordinates from one coordinate system to another, including datum transformations.",
  "main": "lib/index.js",
  "directories": {
    "test": "test",
    "doc": "docs"
  },
  "scripts": {
    "test": "./node_modules/istanbul/lib/cli.js test ./node_modules/mocha/bin/_mocha test/test.js"
  },
  "repository": {
    "type": "git",
    "url": "git://github.com/proj4js/proj4js.git"
  },
  "author": "",
  "license": "MIT",
  "jam": {
    "main": "dist/proj4.js",
    "include": [
      "dist/proj4.js",
      "README.md",
      "AUTHORS",
      "LICENSE.md"
    ]
  },
  "devDependencies": {
    "grunt-cli": "~0.1.13",
    "grunt": "~0.4.2",
    "grunt-contrib-connect": "~0.6.0",
    "grunt-contrib-jshint": "~0.8.0",
    "chai": "~1.8.1",
    "mocha": "~1.17.1",
    "grunt-mocha-phantomjs": "~0.4.0",
    "browserify": "~3.24.5",
    "grunt-browserify": "~1.3.0",
    "grunt-contrib-uglify": "~0.3.2",
    "curl": "git://github.com/cujojs/curl.git",
    "istanbul": "~0.2.4",
    "tin": "~0.4.0"
  },
  "dependencies": {
    "mgrs": "~0.0.2"
  },
  "contributors": [
    {
      "name": "Mike Adair",
      "email": "madair@dmsolutions.ca"
    },
    {
      "name": "Richard Greenwood",
      "email": "rich@greenwoodmap.com"
    },
    {
      "name": "Calvin Metcalf",
      "email": "calvin.metcalf@gmail.com"
    },
    {
      "name": "Richard Marsden",
      "url": "http://www.winwaed.com"
    },
    {
      "name": "T. Mittan"
    },
    {
      "name": "D. Steinwand"
    },
    {
      "name": "S. Nelson"
    }
  ],
  "gitHead": "cd07cad5c6a5b6ed82b59a21356848979eafe22c",
  "bugs": {
    "url": "https://github.com/proj4js/proj4js/issues"
  },
  "homepage": "https://github.com/proj4js/proj4js#readme",
  "_id": "proj4@2.3.12",
  "_shasum": "96b9ed2a810dad6e62f1e32b4dad37c276b427a2",
  "_from": "proj4@>=2.3.10 <3.0.0",
  "_npmVersion": "2.11.3",
  "_nodeVersion": "0.12.7",
  "_npmUser": {
    "name": "ahocevar",
    "email": "andreas.hocevar@gmail.com"
  },
  "dist": {
    "shasum": "96b9ed2a810dad6e62f1e32b4dad37c276b427a2",
    "tarball": "http://registry.npmjs.org/proj4/-/proj4-2.3.12.tgz"
  },
  "maintainers": [
    {
      "name": "cwmma",
      "email": "calvin.metcalf@gmail.com"
    },
    {
      "name": "ahocevar",
      "email": "andreas.hocevar@gmail.com"
    }
  ],
  "_resolved": "https://registry.npmjs.org/proj4/-/proj4-2.3.12.tgz"
}

},{}],"rbush":[function(require,module,exports){
/*
 (c) 2015, Vladimir Agafonkin
 RBush, a JavaScript library for high-performance 2D spatial indexing of points and rectangles.
 https://github.com/mourner/rbush
*/

(function () { 'use strict';

function rbush(maxEntries, format) {

    // jshint newcap: false, validthis: true
    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.bbox)) 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.bbox;

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

                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 = {
            children: [],
            height: 1,
            bbox: empty(),
            leaf: true
        };
        return this;
    },

    remove: function (item) {
        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 = node.children.indexOf(item);

                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, 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: function (a, b) { return a[0] - b[0]; },
    compareMinY: function (a, b) { return a[1] - b[1]; },

    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 = {
                children: items.slice(left, right + 1),
                height: 1,
                bbox: null,
                leaf: true
            };
            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));
        }

        // TODO eliminate recursion?

        node = {
            children: [],
            height: height,
            bbox: null
        };

        // 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.bbox);
                enlargement = enlargedArea(bbox, child.bbox) - 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;
        }

        return node;
    },

    _insert: function (item, level, isNode) {

        var toBBox = this.toBBox,
            bbox = isNode ? item.bbox : 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, 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 = {
            children: node.children.splice(splitIndex, node.children.length - splitIndex),
            height: node.height
        };

        if (node.leaf) newNode.leaf = true;

        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 = {
            children: [node, newNode],
            height: node.height + 1
        };
        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.bbox);
            margin += bboxMargin(leftBBox);
        }

        for (i = M - m - 1; i >= m; i--) {
            child = node.children[i];
            extend(rightBBox, node.leaf ? toBBox(child) : child.bbox);
            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, 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

        // jshint evil: true

        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 [a' + format.join(', a') + '];');
    }
};


// calculate node's bbox from bboxes of its children
function calcBBox(node, toBBox) {
    node.bbox = distBBox(node, 0, node.children.length, toBBox);
}

// min bounding rectangle of node children from k to p-1
function distBBox(node, k, p, toBBox) {
    var bbox = empty();

    for (var i = k, child; i < p; i++) {
        child = node.children[i];
        extend(bbox, node.leaf ? toBBox(child) : child.bbox);
    }

    return bbox;
}

function empty() { return [Infinity, Infinity, -Infinity, -Infinity]; }

function extend(a, b) {
    a[0] = Math.min(a[0], b[0]);
    a[1] = Math.min(a[1], b[1]);
    a[2] = Math.max(a[2], b[2]);
    a[3] = Math.max(a[3], b[3]);
    return a;
}

function compareNodeMinX(a, b) { return a.bbox[0] - b.bbox[0]; }
function compareNodeMinY(a, b) { return a.bbox[1] - b.bbox[1]; }

function bboxArea(a)   { return (a[2] - a[0]) * (a[3] - a[1]); }
function bboxMargin(a) { return (a[2] - a[0]) + (a[3] - a[1]); }

function enlargedArea(a, b) {
    return (Math.max(b[2], a[2]) - Math.min(b[0], a[0])) *
           (Math.max(b[3], a[3]) - Math.min(b[1], a[1]));
}

function intersectionArea(a, b) {
    var minX = Math.max(a[0], b[0]),
        minY = Math.max(a[1], b[1]),
        maxX = Math.min(a[2], b[2]),
        maxY = Math.min(a[3], b[3]);

    return Math.max(0, maxX - minX) *
           Math.max(0, maxY - minY);
}

function contains(a, b) {
    return a[0] <= b[0] &&
           a[1] <= b[1] &&
           b[2] <= a[2] &&
           b[3] <= a[3];
}

function intersects(a, b) {
    return b[0] <= a[2] &&
           b[1] <= a[3] &&
           b[2] >= a[0] &&
           b[3] >= a[1];
}

// 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;
        select(arr, left, right, mid, compare);

        stack.push(left, mid, mid, right);
    }
}

// Floyd-Rivest selection algorithm:
// sort an array between left and right (inclusive) so that the smallest k elements come first (unordered)
function select(arr, left, right, k, compare) {
    var n, i, z, s, sd, newLeft, newRight, t, j;

    while (right > left) {
        if (right - left > 600) {
            n = right - left + 1;
            i = k - left + 1;
            z = Math.log(n);
            s = 0.5 * Math.exp(2 * z / 3);
            sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (i - n / 2 < 0 ? -1 : 1);
            newLeft = Math.max(left, Math.floor(k - i * s / n + sd));
            newRight = Math.min(right, Math.floor(k + (n - i) * s / n + sd));
            select(arr, newLeft, newRight, k, compare);
        }

        t = arr[k];
        i = left;
        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;
}


// export as AMD/CommonJS module or global variable
if (typeof define === 'function' && define.amd) define('rbush', function() { return rbush; });
else if (typeof module !== 'undefined') module.exports = rbush;
else if (typeof self !== 'undefined') self.rbush = rbush;
else window.rbush = rbush;

})();

},{}],"sprintf":[function(require,module,exports){
/**
sprintf() for JavaScript 0.7-beta1
http://www.diveintojavascript.com/projects/javascript-sprintf

Copyright (c) Alexandru Marasteanu <alexaholic [at) gmail (dot] com>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of sprintf() for JavaScript nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Alexandru Marasteanu BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


Changelog:
2010.11.07 - 0.7-beta1-node
  - converted it to a node.js compatible module

2010.09.06 - 0.7-beta1
  - features: vsprintf, support for named placeholders
  - enhancements: format cache, reduced global namespace pollution

2010.05.22 - 0.6:
 - reverted to 0.4 and fixed the bug regarding the sign of the number 0
 Note:
 Thanks to Raphael Pigulla <raph (at] n3rd [dot) org> (http://www.n3rd.org/)
 who warned me about a bug in 0.5, I discovered that the last update was
 a regress. I appologize for that.

2010.05.09 - 0.5:
 - bug fix: 0 is now preceeded with a + sign
 - bug fix: the sign was not at the right position on padded results (Kamal Abdali)
 - switched from GPL to BSD license

2007.10.21 - 0.4:
 - unit test and patch (David Baird)

2007.09.17 - 0.3:
 - bug fix: no longer throws exception on empty paramenters (Hans Pufal)

2007.09.11 - 0.2:
 - feature: added argument swapping

2007.04.03 - 0.1:
 - initial release
**/

var sprintf = (function() {
	function get_type(variable) {
		return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
	}
	function str_repeat(input, multiplier) {
		for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
		return output.join('');
	}

	var str_format = function() {
		if (!str_format.cache.hasOwnProperty(arguments[0])) {
			str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
		}
		return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
	};

	// convert object to simple one line string without indentation or
	// newlines. Note that this implementation does not print array
	// values to their actual place for sparse arrays. 
	//
	// For example sparse array like this
	//    l = []
	//    l[4] = 1
	// Would be printed as "[1]" instead of "[, , , , 1]"
	// 
	// If argument 'seen' is not null and array the function will check for 
	// circular object references from argument.
	str_format.object_stringify = function(obj, depth, maxdepth, seen) {
		var str = '';
		if (obj != null) {
			switch( typeof(obj) ) {
			case 'function': 
				return '[Function' + (obj.name ? ': '+obj.name : '') + ']';
			    break;
			case 'object':
				if ( obj instanceof Error) { return '[' + obj.toString() + ']' };
				if (depth >= maxdepth) return '[Object]'
				if (seen) {
					// add object to seen list
					seen = seen.slice(0)
					seen.push(obj);
				}
				if (obj.length != null) { //array
					str += '[';
					var arr = []
					for (var i in obj) {
						if (seen && seen.indexOf(obj[i]) >= 0) arr.push('[Circular]');
						else arr.push(str_format.object_stringify(obj[i], depth+1, maxdepth, seen));
					}
					str += arr.join(', ') + ']';
				} else if ('getMonth' in obj) { // date
					return 'Date(' + obj + ')';
				} else { // object
					str += '{';
					var arr = []
					for (var k in obj) { 
						if(obj.hasOwnProperty(k)) {
							if (seen && seen.indexOf(obj[k]) >= 0) arr.push(k + ': [Circular]');
							else arr.push(k +': ' +str_format.object_stringify(obj[k], depth+1, maxdepth, seen)); 
						}
					}
					str += arr.join(', ') + '}';
				}
				return str;
				break;
			case 'string':				
				return '"' + obj + '"';
				break
			}
		}
		return '' + obj;
	}

	str_format.format = function(parse_tree, argv) {
		var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
		for (i = 0; i < tree_length; i++) {
			node_type = get_type(parse_tree[i]);
			if (node_type === 'string') {
				output.push(parse_tree[i]);
			}
			else if (node_type === 'array') {
				match = parse_tree[i]; // convenience purposes only
				if (match[2]) { // keyword argument
					arg = argv[cursor];
					for (k = 0; k < match[2].length; k++) {
						if (!arg.hasOwnProperty(match[2][k])) {
							throw new Error(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
						}
						arg = arg[match[2][k]];
					}
				}
				else if (match[1]) { // positional argument (explicit)
					arg = argv[match[1]];
				}
				else { // positional argument (implicit)
					arg = argv[cursor++];
				}

				if (/[^sO]/.test(match[8]) && (get_type(arg) != 'number')) {
					throw new Error(sprintf('[sprintf] expecting number but found %s "' + arg + '"', get_type(arg)));
				}
				switch (match[8]) {
					case 'b': arg = arg.toString(2); break;
					case 'c': arg = String.fromCharCode(arg); break;
					case 'd': arg = parseInt(arg, 10); break;
					case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
					case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
				    case 'O': arg = str_format.object_stringify(arg, 0, parseInt(match[7]) || 5); break;
					case 'o': arg = arg.toString(8); break;
					case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
					case 'u': arg = Math.abs(arg); break;
					case 'x': arg = arg.toString(16); break;
					case 'X': arg = arg.toString(16).toUpperCase(); break;
				}
				arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
				pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
				pad_length = match[6] - String(arg).length;
				pad = match[6] ? str_repeat(pad_character, pad_length) : '';
				output.push(match[5] ? arg + pad : pad + arg);
			}
		}
		return output.join('');
	};

	str_format.cache = {};

	str_format.parse = function(fmt) {
		var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
		while (_fmt) {
			if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
				parse_tree.push(match[0]);
			}
			else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
				parse_tree.push('%');
			}
			else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosOuxX])/.exec(_fmt)) !== null) {
				if (match[2]) {
					arg_names |= 1;
					var field_list = [], replacement_field = match[2], field_match = [];
					if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
						field_list.push(field_match[1]);
						while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
							if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
								field_list.push(field_match[1]);
							}
							else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
								field_list.push(field_match[1]);
							}
							else {
								throw new Error('[sprintf] ' + replacement_field);
							}
						}
					}
					else {
                        throw new Error('[sprintf] ' + replacement_field);
					}
					match[2] = field_list;
				}
				else {
					arg_names |= 2;
				}
				if (arg_names === 3) {
					throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported');
				}
				parse_tree.push(match);
			}
			else {
				throw new Error('[sprintf] ' + _fmt);
			}
			_fmt = _fmt.substring(match[0].length);
		}
		return parse_tree;
	};

	return str_format;
})();

var vsprintf = function(fmt, argv) {
	var argvClone = argv.slice();
	argvClone.unshift(fmt);
	return sprintf.apply(null, argvClone);
};

module.exports = sprintf;
sprintf.sprintf = sprintf;
sprintf.vsprintf = vsprintf;

},{}],"timezone/index":[function(require,module,exports){
!function (definition) {
  if (typeof module == "object" && module.exports) module.exports = definition();
  else if (typeof define == "function") define(definition);
  else this.tz = definition();
} (function () {
/*
  function die () {
    console.log.apply(console, __slice.call(arguments, 0));
    return process.exit(1);
  }

  function say () { return console.log.apply(console, __slice.call(arguments, 0)) }
*/
  function actualize (entry, rule, year) {
    var actualized, date = rule.day[1];

    do {
      actualized = new Date(Date.UTC(year, rule.month, Math.abs(date++)));
    } while (rule.day[0] < 7 && actualized.getUTCDay() != rule.day[0])

    actualized = {
      clock: rule.clock,
      sort: actualized.getTime(),
      rule: rule,
      save: rule.save * 6e4,
      offset: entry.offset
    };

    actualized[actualized.clock] = actualized.sort + rule.time * 6e4;

    if (actualized.posix) {
      actualized.wallclock = actualized[actualized.clock] + (entry.offset + rule.saved);
    } else {
      actualized.posix = actualized[actualized.clock] - (entry.offset + rule.saved);
    }

    return actualized;
  }

  function find (request, clock, time) {
    var i, I, entry, found, zone = request[request.zone], actualized = [], abbrev, rules
      , j, year = new Date(time).getUTCFullYear(), off = 1;
    for (i = 1, I = zone.length; i < I; i++) if (zone[i][clock] <= time) break;
    entry = zone[i];
    if (entry.rules) {
      rules = request[entry.rules];
      for (j = year + 1; j >= year - off; --j)
        for (i = 0, I = rules.length; i < I; i++)
          if (rules[i].from <= j && j <= rules[i].to) actualized.push(actualize(entry, rules[i], j));
          else if (rules[i].to < j && off == 1) off = j - rules[i].to;
      actualized.sort(function (a, b) { return a.sort - b.sort });
      for (i = 0, I = actualized.length; i < I; i++) {
        if (time >= actualized[i][clock] && actualized[i][actualized[i].clock] > entry[actualized[i].clock]) found = actualized[i];
      }
    }
    if (found) {
      if (abbrev = /^(.*)\/(.*)$/.exec(entry.format)) {
        found.abbrev = abbrev[found.save ? 2 : 1];
      } else {
        found.abbrev = entry.format.replace(/%s/, found.rule.letter);
      }
    }
    return found || entry;
  }

  function convertToWallclock (request, posix) {
    if (request.zone == "UTC") return posix;
    request.entry = find(request, "posix", posix);
    return posix + request.entry.offset + request.entry.save;
  }

  function convertToPOSIX (request, wallclock) {
    if (request.zone == "UTC") return wallclock;

    var entry, diff;
    request.entry = entry = find(request, "wallclock", wallclock);
    diff = wallclock - entry.wallclock;

    return 0 < diff && diff < entry.save ? null : wallclock - entry.offset - entry.save;
  }

  function adjust (request, posix, match) {
    var increment = +(match[1] + 1) // conversion necessary for week day addition
      , offset = match[2] * increment
      , index = UNITS.indexOf(match[3].toLowerCase())
      , date
      ;
    if (index > 9) {
      posix += offset * TIME[index - 10];
    } else {
      date = new Date(convertToWallclock(request, posix));
      if (index < 7) {
        while (offset) {
          date.setUTCDate(date.getUTCDate() + increment);
          if (date.getUTCDay() == index) offset -= increment;
        }
      } else if (index == 7) {
        date.setUTCFullYear(date.getUTCFullYear() + offset);
      } else if (index == 8) {
        date.setUTCMonth(date.getUTCMonth() + offset);
      } else {
        date.setUTCDate(date.getUTCDate() + offset);
      }
      if ((posix = convertToPOSIX(request, date.getTime())) == null) {
        posix = convertToPOSIX(request, date.getTime() + 864e5 * increment) - 864e5 * increment;
      }
    }
    return posix;
  }

  function convert (vargs) {
    if (!vargs.length) return "0.0.38";

    var request = Object.create(this)
      , adjustments = []
      , i, I, $, argument, date
      ;

    for (i = 0; i < vargs.length; i++) { // leave the for loop alone, it works.
      argument = vargs[i];
      // https://twitter.com/bigeasy/status/215112186572439552
      if (Array.isArray(argument)) {
        if (!i && !isNaN(argument[1])) {
          date = argument;
        } else {
          argument.splice.apply(vargs, [ i--, 1 ].concat(argument));
        }
      } else if (isNaN(argument)) {
        $ = typeof argument;
        if ($ == "string") {
          if (~argument.indexOf("%")) {
            request.format = argument;
          } else if (!i && argument == "*") {
            date = argument;
          } else if (!i && ($ = /^(\d{4})-(\d{2})-(\d{2})(?:[T\s](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(Z|(([+-])(\d{2}(:\d{2}){0,2})))?)?$/.exec(argument))) {
            date = [];
            date.push.apply(date, $.slice(1, 8));
            if ($[9]) {
              date.push($[10] + 1);
              date.push.apply(date, $[11].split(/:/));
            } else if ($[8]) {
              date.push(1);
            }
          } else if (/^\w{2,3}_\w{2}$/.test(argument)) {
            request.locale = argument;
          } else if ($ = UNIT_RE.exec(argument)) {
            adjustments.push($);
          } else {
            request.zone = argument;
          }
        } else if ($ == "function") {
          if ($ = argument.call(request)) return $;
        } else if (/^\w{2,3}_\w{2}$/.test(argument.name)) {
          request[argument.name] = argument;
        } else if (argument.zones) {
          for ($ in argument.zones) request[$] = argument.zones[$];
          for ($ in argument.rules) request[$] = argument.rules[$];
        }
      } else if (!i) {
        date = argument;
      }
    }

    if (!request[request.locale]) delete request.locale;
    if (!request[request.zone]) delete request.zone;

    if (date != null) {
      if (date == "*") {
        date = request.clock();
      } else if (Array.isArray(date)) {
        I = !date[7];
        for (i = 0; i < 11; i++) date[i] = +(date[i] || 0); // conversion necessary for decrement
        --date[1]; // Grr..
        date = Date.UTC.apply(Date.UTC, date.slice(0, 8)) +
          -date[7] * (date[8] * 36e5 + date[9] * 6e4 + date[10] * 1e3);
      } else {
        date = Math.floor(date);
      }
      if (!isNaN(date)) {
        if (I) date = convertToPOSIX(request, date);

        if (date == null) return date;

        for (i = 0, I = adjustments.length; i < I; i++) {
          date = adjust(request, date, adjustments[i]);
        }

        if (!request.format) return date;

        $ = new Date(convertToWallclock(request, date));
        return request.format.replace(/%([-0_^]?)(:{0,3})(\d*)(.)/g,
        function (value, flag, colons, padding, specifier) {
          var f, fill = "0", pad;
          if (f = request[specifier]) {
            value = String(f.call(request, $, date, flag, colons.length));
            if ((flag || f.style) == "_") fill = " ";
            pad = flag == "-" ? 0 : f.pad || 0;
            while (value.length < pad) value = fill + value;
            pad = flag == "-" ? 0 : padding || f.pad;
            while (value.length < pad) value = fill + value;
            if (specifier == "N" && pad < value.length) value = value.slice(0, pad);
            if (flag == "^") value = value.toUpperCase();
          }
          return value;
        });
      }
    }

    return function () { return request.convert(arguments) };
  }

  var context =
    { clock: function () { return +(new Date()) }
    , zone: "UTC"
    , entry: { abbrev: "UTC", offset: 0, save: 0 }
    , UTC: 1
    , z: function(date, posix, flag, delimiters) {
        var offset = this.entry.offset + this.entry.save
          , seconds = Math.abs(offset / 1000), parts = [], part = 3600, i, z;
        for (i = 0; i < 3; i++) {
          parts.push(("0" + Math.floor(seconds / part)).slice(-2));
          seconds %= part;
          part /= 60;
        }
        if (flag == "^" && !offset) return "Z";
        if (flag == "^") delimiters = 3;
        if (delimiters == 3) {
          z = parts.join(":");
          z = z.replace(/:00$/, "");
          if (flag != "^") z = z.replace(/:00$/, "");
        } else if (delimiters) {
          z = parts.slice(0, delimiters + 1).join(":");
          if (flag == "^") z = z.replace(/:00$/, "");
        } else {
          z = parts.slice(0, 2).join("");
        }
        z = (offset < 0 ? "-" : "+") + z;
        z = z.replace(/([-+])(0)/, { "_": " $1", "-": "$1" }[flag] || "$1$2");
        return z;
      }
    , "%": function(date) { return "%" }
    , n: function (date) { return "\n" }
    , t: function (date) { return "\t" }
    , U: function (date) { return weekOfYear(date, 0) }
    , W: function (date) { return weekOfYear(date, 1) }
    , V: function (date) { return isoWeek(date)[0] }
    , G: function (date) { return isoWeek(date)[1] }
    , g: function (date) { return isoWeek(date)[1] % 100 }
    , j: function (date) { return Math.floor((date.getTime() - Date.UTC(date.getUTCFullYear(), 0)) / 864e5) + 1 }
    , s: function (date) { return Math.floor(date.getTime() / 1000) }
    , C: function (date) { return Math.floor(date.getUTCFullYear() / 100) }
    , N: function (date) { return date.getTime() % 1000 * 1000000 }
    , m: function (date) { return date.getUTCMonth() + 1 }
    , Y: function (date) { return date.getUTCFullYear() }
    , y: function (date) { return date.getUTCFullYear() % 100 }
    , H: function (date) { return date.getUTCHours() }
    , M: function (date) { return date.getUTCMinutes() }
    , S: function (date) { return date.getUTCSeconds() }
    , e: function (date) { return date.getUTCDate() }
    , d: function (date) { return date.getUTCDate() }
    , u: function (date) { return date.getUTCDay() || 7 }
    , w: function (date) { return date.getUTCDay() }
    , l: function (date) { return date.getUTCHours() % 12 || 12 }
    , I: function (date) { return date.getUTCHours() % 12 || 12 }
    , k: function (date) { return date.getUTCHours() }
    , Z: function (date) { return this.entry.abbrev }
    , a: function (date) { return this[this.locale].day.abbrev[date.getUTCDay()] }
    , A: function (date) { return this[this.locale].day.full[date.getUTCDay()] }
    , h: function (date) { return this[this.locale].month.abbrev[date.getUTCMonth()] }
    , b: function (date) { return this[this.locale].month.abbrev[date.getUTCMonth()] }
    , B: function (date) { return this[this.locale].month.full[date.getUTCMonth()] }
    , P: function (date) { return this[this.locale].meridiem[Math.floor(date.getUTCHours() / 12)].toLowerCase() }
    , p: function (date) { return this[this.locale].meridiem[Math.floor(date.getUTCHours() / 12)] }
    , R: function (date, posix) { return this.convert([ posix, "%H:%M" ]) }
    , T: function (date, posix) { return this.convert([ posix, "%H:%M:%S" ]) }
    , D: function (date, posix) { return this.convert([ posix, "%m/%d/%y" ]) }
    , F: function (date, posix) { return this.convert([ posix, "%Y-%m-%d" ]) }
    , x: function (date, posix) { return this.convert([ posix, this[this.locale].date ]) }
    , r: function (date, posix) { return this.convert([ posix, this[this.locale].time12 || '%I:%M:%S' ]) }
    , X: function (date, posix) { return this.convert([ posix, this[this.locale].time24 ]) }
    , c: function (date, posix) { return this.convert([ posix, this[this.locale].dateTime ]) }
    , convert: convert
    , locale: "en_US"
    , en_US: {
        date: "%m/%d/%Y",
        time24: "%I:%M:%S %p",
        time12: "%I:%M:%S %p",
        dateTime: "%a %d %b %Y %I:%M:%S %p %Z",
        meridiem: [ "AM", "PM" ],
        month: {
          abbrev: "Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec".split("|"),
          full: "January|February|March|April|May|June|July|August|September|October|November|December".split("|")
        },
        day: {
          abbrev: "Sun|Mon|Tue|Wed|Thu|Fri|Sat".split("|"),
          full: "Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday".split("|")
        }
      }
    };
  var UNITS = "Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|year|month|day|hour|minute|second|millisecond"
    , UNIT_RE = new RegExp("^\\s*([+-])(\\d+)\\s+(" + UNITS + ")s?\\s*$", "i")
    , TIME = [ 36e5, 6e4, 1e3, 1 ]
    ;
  UNITS = UNITS.toLowerCase().split("|");

  "delmHMSUWVgCIky".replace(/./g, function (e) { context[e].pad = 2 });

  context.N.pad = 9;
  context.j.pad = 3;

  context.k.style = "_";
  context.l.style = "_";
  context.e.style = "_";

  function weekOfYear (date, startOfWeek) {
    var diff, nyd, weekStart;
    nyd = new Date(Date.UTC(date.getUTCFullYear(), 0));
    diff = Math.floor((date.getTime() - nyd.getTime()) / 864e5);
    if (nyd.getUTCDay() == startOfWeek) {
      weekStart = 0;
    } else {
      weekStart = 7 - nyd.getUTCDay() + startOfWeek;
      if (weekStart == 8) {
        weekStart = 1;
      }
    }
    return diff >= weekStart ? Math.floor((diff - weekStart) / 7) + 1 : 0;
  }

  function isoWeek (date) {
    var nyd, nyy, week;
    nyy = date.getUTCFullYear();
    nyd = new Date(Date.UTC(nyy, 0)).getUTCDay();
    week = weekOfYear(date, 1) + (nyd > 1 && nyd <= 4 ? 1 : 0);
    if (!week) {
      nyy = date.getUTCFullYear() - 1;
      nyd = new Date(Date.UTC(nyy, 0)).getUTCDay();
      week = nyd == 4 || (nyd == 3 && new Date(nyy, 1, 29).getDate() == 29) ? 53 : 52;
      return [week, date.getUTCFullYear() - 1];
    } else if (week == 53 && !(nyd == 4 || (nyd == 3 && new Date(nyy, 1, 29).getDate() == 29))) {
      return [1, date.getUTCFullYear() + 1];
    } else {
      return [week, date.getUTCFullYear()];
    }
  }

  return function () { return context.convert(arguments) };
});

},{}],"underscore":[function(require,module,exports){
//     Underscore.js 1.8.3
//     http://underscorejs.org
//     (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
//     Underscore may be freely distributed under the MIT license.

(function() {

  // Baseline setup
  // --------------

  // Establish the root object, `window` in the browser, or `exports` on the server.
  var root = this;

  // Save the previous value of the `_` variable.
  var previousUnderscore = root._;

  // Save bytes in the minified (but not gzipped) version:
  var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;

  // Create quick reference variables for speed access to core prototypes.
  var
    push             = ArrayProto.push,
    slice            = ArrayProto.slice,
    toString         = ObjProto.toString,
    hasOwnProperty   = ObjProto.hasOwnProperty;

  // All **ECMAScript 5** native function implementations that we hope to use
  // are declared here.
  var
    nativeIsArray      = Array.isArray,
    nativeKeys         = Object.keys,
    nativeBind         = FuncProto.bind,
    nativeCreate       = Object.create;

  // Naked function reference for surrogate-prototype-swapping.
  var Ctor = function(){};

  // Create a safe reference to the Underscore object for use below.
  var _ = function(obj) {
    if (obj instanceof _) return obj;
    if (!(this instanceof _)) return new _(obj);
    this._wrapped = obj;
  };

  // Export the Underscore object for **Node.js**, with
  // backwards-compatibility for the old `require()` API. If we're in
  // the browser, add `_` as a global object.
  if (typeof exports !== 'undefined') {
    if (typeof module !== 'undefined' && module.exports) {
      exports = module.exports = _;
    }
    exports._ = _;
  } else {
    root._ = _;
  }

  // Current version.
  _.VERSION = '1.8.3';

  // Internal function that returns an efficient (for current engines) version
  // of the passed-in callback, to be repeatedly applied in other Underscore
  // functions.
  var optimizeCb = function(func, context, argCount) {
    if (context === void 0) return func;
    switch (argCount == null ? 3 : argCount) {
      case 1: return function(value) {
        return func.call(context, value);
      };
      case 2: return function(value, other) {
        return func.call(context, value, other);
      };
      case 3: return function(value, index, collection) {
        return func.call(context, value, index, collection);
      };
      case 4: return function(accumulator, value, index, collection) {
        return func.call(context, accumulator, value, index, collection);
      };
    }
    return function() {
      return func.apply(context, arguments);
    };
  };

  // A mostly-internal function to generate callbacks that can be applied
  // to each element in a collection, returning the desired result — either
  // identity, an arbitrary callback, a property matcher, or a property accessor.
  var cb = function(value, context, argCount) {
    if (value == null) return _.identity;
    if (_.isFunction(value)) return optimizeCb(value, context, argCount);
    if (_.isObject(value)) return _.matcher(value);
    return _.property(value);
  };
  _.iteratee = function(value, context) {
    return cb(value, context, Infinity);
  };

  // An internal function for creating assigner functions.
  var createAssigner = function(keysFunc, undefinedOnly) {
    return function(obj) {
      var length = arguments.length;
      if (length < 2 || obj == null) return obj;
      for (var index = 1; index < length; index++) {
        var source = arguments[index],
            keys = keysFunc(source),
            l = keys.length;
        for (var i = 0; i < l; i++) {
          var key = keys[i];
          if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];
        }
      }
      return obj;
    };
  };

  // An internal function for creating a new object that inherits from another.
  var baseCreate = function(prototype) {
    if (!_.isObject(prototype)) return {};
    if (nativeCreate) return nativeCreate(prototype);
    Ctor.prototype = prototype;
    var result = new Ctor;
    Ctor.prototype = null;
    return result;
  };

  var property = function(key) {
    return function(obj) {
      return obj == null ? void 0 : obj[key];
    };
  };

  // Helper for collection methods to determine whether a collection
  // should be iterated as an array or as an object
  // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
  // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
  var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
  var getLength = property('length');
  var isArrayLike = function(collection) {
    var length = getLength(collection);
    return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
  };

  // Collection Functions
  // --------------------

  // The cornerstone, an `each` implementation, aka `forEach`.
  // Handles raw objects in addition to array-likes. Treats all
  // sparse array-likes as if they were dense.
  _.each = _.forEach = function(obj, iteratee, context) {
    iteratee = optimizeCb(iteratee, context);
    var i, length;
    if (isArrayLike(obj)) {
      for (i = 0, length = obj.length; i < length; i++) {
        iteratee(obj[i], i, obj);
      }
    } else {
      var keys = _.keys(obj);
      for (i = 0, length = keys.length; i < length; i++) {
        iteratee(obj[keys[i]], keys[i], obj);
      }
    }
    return obj;
  };

  // Return the results of applying the iteratee to each element.
  _.map = _.collect = function(obj, iteratee, context) {
    iteratee = cb(iteratee, context);
    var keys = !isArrayLike(obj) && _.keys(obj),
        length = (keys || obj).length,
        results = Array(length);
    for (var index = 0; index < length; index++) {
      var currentKey = keys ? keys[index] : index;
      results[index] = iteratee(obj[currentKey], currentKey, obj);
    }
    return results;
  };

  // Create a reducing function iterating left or right.
  function createReduce(dir) {
    // Optimized iterator function as using arguments.length
    // in the main function will deoptimize the, see #1991.
    function iterator(obj, iteratee, memo, keys, index, length) {
      for (; index >= 0 && index < length; index += dir) {
        var currentKey = keys ? keys[index] : index;
        memo = iteratee(memo, obj[currentKey], currentKey, obj);
      }
      return memo;
    }

    return function(obj, iteratee, memo, context) {
      iteratee = optimizeCb(iteratee, context, 4);
      var keys = !isArrayLike(obj) && _.keys(obj),
          length = (keys || obj).length,
          index = dir > 0 ? 0 : length - 1;
      // Determine the initial value if none is provided.
      if (arguments.length < 3) {
        memo = obj[keys ? keys[index] : index];
        index += dir;
      }
      return iterator(obj, iteratee, memo, keys, index, length);
    };
  }

  // **Reduce** builds up a single result from a list of values, aka `inject`,
  // or `foldl`.
  _.reduce = _.foldl = _.inject = createReduce(1);

  // The right-associative version of reduce, also known as `foldr`.
  _.reduceRight = _.foldr = createReduce(-1);

  // Return the first value which passes a truth test. Aliased as `detect`.
  _.find = _.detect = function(obj, predicate, context) {
    var key;
    if (isArrayLike(obj)) {
      key = _.findIndex(obj, predicate, context);
    } else {
      key = _.findKey(obj, predicate, context);
    }
    if (key !== void 0 && key !== -1) return obj[key];
  };

  // Return all the elements that pass a truth test.
  // Aliased as `select`.
  _.filter = _.select = function(obj, predicate, context) {
    var results = [];
    predicate = cb(predicate, context);
    _.each(obj, function(value, index, list) {
      if (predicate(value, index, list)) results.push(value);
    });
    return results;
  };

  // Return all the elements for which a truth test fails.
  _.reject = function(obj, predicate, context) {
    return _.filter(obj, _.negate(cb(predicate)), context);
  };

  // Determine whether all of the elements match a truth test.
  // Aliased as `all`.
  _.every = _.all = function(obj, predicate, context) {
    predicate = cb(predicate, context);
    var keys = !isArrayLike(obj) && _.keys(obj),
        length = (keys || obj).length;
    for (var index = 0; index < length; index++) {
      var currentKey = keys ? keys[index] : index;
      if (!predicate(obj[currentKey], currentKey, obj)) return false;
    }
    return true;
  };

  // Determine if at least one element in the object matches a truth test.
  // Aliased as `any`.
  _.some = _.any = function(obj, predicate, context) {
    predicate = cb(predicate, context);
    var keys = !isArrayLike(obj) && _.keys(obj),
        length = (keys || obj).length;
    for (var index = 0; index < length; index++) {
      var currentKey = keys ? keys[index] : index;
      if (predicate(obj[currentKey], currentKey, obj)) return true;
    }
    return false;
  };

  // Determine if the array or object contains a given item (using `===`).
  // Aliased as `includes` and `include`.
  _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {
    if (!isArrayLike(obj)) obj = _.values(obj);
    if (typeof fromIndex != 'number' || guard) fromIndex = 0;
    return _.indexOf(obj, item, fromIndex) >= 0;
  };

  // Invoke a method (with arguments) on every item in a collection.
  _.invoke = function(obj, method) {
    var args = slice.call(arguments, 2);
    var isFunc = _.isFunction(method);
    return _.map(obj, function(value) {
      var func = isFunc ? method : value[method];
      return func == null ? func : func.apply(value, args);
    });
  };

  // Convenience version of a common use case of `map`: fetching a property.
  _.pluck = function(obj, key) {
    return _.map(obj, _.property(key));
  };

  // Convenience version of a common use case of `filter`: selecting only objects
  // containing specific `key:value` pairs.
  _.where = function(obj, attrs) {
    return _.filter(obj, _.matcher(attrs));
  };

  // Convenience version of a common use case of `find`: getting the first object
  // containing specific `key:value` pairs.
  _.findWhere = function(obj, attrs) {
    return _.find(obj, _.matcher(attrs));
  };

  // Return the maximum element (or element-based computation).
  _.max = function(obj, iteratee, context) {
    var result = -Infinity, lastComputed = -Infinity,
        value, computed;
    if (iteratee == null && obj != null) {
      obj = isArrayLike(obj) ? obj : _.values(obj);
      for (var i = 0, length = obj.length; i < length; i++) {
        value = obj[i];
        if (value > result) {
          result = value;
        }
      }
    } else {
      iteratee = cb(iteratee, context);
      _.each(obj, function(value, index, list) {
        computed = iteratee(value, index, list);
        if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
          result = value;
          lastComputed = computed;
        }
      });
    }
    return result;
  };

  // Return the minimum element (or element-based computation).
  _.min = function(obj, iteratee, context) {
    var result = Infinity, lastComputed = Infinity,
        value, computed;
    if (iteratee == null && obj != null) {
      obj = isArrayLike(obj) ? obj : _.values(obj);
      for (var i = 0, length = obj.length; i < length; i++) {
        value = obj[i];
        if (value < result) {
          result = value;
        }
      }
    } else {
      iteratee = cb(iteratee, context);
      _.each(obj, function(value, index, list) {
        computed = iteratee(value, index, list);
        if (computed < lastComputed || computed === Infinity && result === Infinity) {
          result = value;
          lastComputed = computed;
        }
      });
    }
    return result;
  };

  // Shuffle a collection, using the modern version of the
  // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
  _.shuffle = function(obj) {
    var set = isArrayLike(obj) ? obj : _.values(obj);
    var length = set.length;
    var shuffled = Array(length);
    for (var index = 0, rand; index < length; index++) {
      rand = _.random(0, index);
      if (rand !== index) shuffled[index] = shuffled[rand];
      shuffled[rand] = set[index];
    }
    return shuffled;
  };

  // Sample **n** random values from a collection.
  // If **n** is not specified, returns a single random element.
  // The internal `guard` argument allows it to work with `map`.
  _.sample = function(obj, n, guard) {
    if (n == null || guard) {
      if (!isArrayLike(obj)) obj = _.values(obj);
      return obj[_.random(obj.length - 1)];
    }
    return _.shuffle(obj).slice(0, Math.max(0, n));
  };

  // Sort the object's values by a criterion produced by an iteratee.
  _.sortBy = function(obj, iteratee, context) {
    iteratee = cb(iteratee, context);
    return _.pluck(_.map(obj, function(value, index, list) {
      return {
        value: value,
        index: index,
        criteria: iteratee(value, index, list)
      };
    }).sort(function(left, right) {
      var a = left.criteria;
      var b = right.criteria;
      if (a !== b) {
        if (a > b || a === void 0) return 1;
        if (a < b || b === void 0) return -1;
      }
      return left.index - right.index;
    }), 'value');
  };

  // An internal function used for aggregate "group by" operations.
  var group = function(behavior) {
    return function(obj, iteratee, context) {
      var result = {};
      iteratee = cb(iteratee, context);
      _.each(obj, function(value, index) {
        var key = iteratee(value, index, obj);
        behavior(result, value, key);
      });
      return result;
    };
  };

  // Groups the object's values by a criterion. Pass either a string attribute
  // to group by, or a function that returns the criterion.
  _.groupBy = group(function(result, value, key) {
    if (_.has(result, key)) result[key].push(value); else result[key] = [value];
  });

  // Indexes the object's values by a criterion, similar to `groupBy`, but for
  // when you know that your index values will be unique.
  _.indexBy = group(function(result, value, key) {
    result[key] = value;
  });

  // Counts instances of an object that group by a certain criterion. Pass
  // either a string attribute to count by, or a function that returns the
  // criterion.
  _.countBy = group(function(result, value, key) {
    if (_.has(result, key)) result[key]++; else result[key] = 1;
  });

  // Safely create a real, live array from anything iterable.
  _.toArray = function(obj) {
    if (!obj) return [];
    if (_.isArray(obj)) return slice.call(obj);
    if (isArrayLike(obj)) return _.map(obj, _.identity);
    return _.values(obj);
  };

  // Return the number of elements in an object.
  _.size = function(obj) {
    if (obj == null) return 0;
    return isArrayLike(obj) ? obj.length : _.keys(obj).length;
  };

  // Split a collection into two arrays: one whose elements all satisfy the given
  // predicate, and one whose elements all do not satisfy the predicate.
  _.partition = function(obj, predicate, context) {
    predicate = cb(predicate, context);
    var pass = [], fail = [];
    _.each(obj, function(value, key, obj) {
      (predicate(value, key, obj) ? pass : fail).push(value);
    });
    return [pass, fail];
  };

  // Array Functions
  // ---------------

  // Get the first element of an array. Passing **n** will return the first N
  // values in the array. Aliased as `head` and `take`. The **guard** check
  // allows it to work with `_.map`.
  _.first = _.head = _.take = function(array, n, guard) {
    if (array == null) return void 0;
    if (n == null || guard) return array[0];
    return _.initial(array, array.length - n);
  };

  // Returns everything but the last entry of the array. Especially useful on
  // the arguments object. Passing **n** will return all the values in
  // the array, excluding the last N.
  _.initial = function(array, n, guard) {
    return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
  };

  // Get the last element of an array. Passing **n** will return the last N
  // values in the array.
  _.last = function(array, n, guard) {
    if (array == null) return void 0;
    if (n == null || guard) return array[array.length - 1];
    return _.rest(array, Math.max(0, array.length - n));
  };

  // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
  // Especially useful on the arguments object. Passing an **n** will return
  // the rest N values in the array.
  _.rest = _.tail = _.drop = function(array, n, guard) {
    return slice.call(array, n == null || guard ? 1 : n);
  };

  // Trim out all falsy values from an array.
  _.compact = function(array) {
    return _.filter(array, _.identity);
  };

  // Internal implementation of a recursive `flatten` function.
  var flatten = function(input, shallow, strict, startIndex) {
    var output = [], idx = 0;
    for (var i = startIndex || 0, length = getLength(input); i < length; i++) {
      var value = input[i];
      if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
        //flatten current level of array or arguments object
        if (!shallow) value = flatten(value, shallow, strict);
        var j = 0, len = value.length;
        output.length += len;
        while (j < len) {
          output[idx++] = value[j++];
        }
      } else if (!strict) {
        output[idx++] = value;
      }
    }
    return output;
  };

  // Flatten out an array, either recursively (by default), or just one level.
  _.flatten = function(array, shallow) {
    return flatten(array, shallow, false);
  };

  // Return a version of the array that does not contain the specified value(s).
  _.without = function(array) {
    return _.difference(array, slice.call(arguments, 1));
  };

  // Produce a duplicate-free version of the array. If the array has already
  // been sorted, you have the option of using a faster algorithm.
  // Aliased as `unique`.
  _.uniq = _.unique = function(array, isSorted, iteratee, context) {
    if (!_.isBoolean(isSorted)) {
      context = iteratee;
      iteratee = isSorted;
      isSorted = false;
    }
    if (iteratee != null) iteratee = cb(iteratee, context);
    var result = [];
    var seen = [];
    for (var i = 0, length = getLength(array); i < length; i++) {
      var value = array[i],
          computed = iteratee ? iteratee(value, i, array) : value;
      if (isSorted) {
        if (!i || seen !== computed) result.push(value);
        seen = computed;
      } else if (iteratee) {
        if (!_.contains(seen, computed)) {
          seen.push(computed);
          result.push(value);
        }
      } else if (!_.contains(result, value)) {
        result.push(value);
      }
    }
    return result;
  };

  // Produce an array that contains the union: each distinct element from all of
  // the passed-in arrays.
  _.union = function() {
    return _.uniq(flatten(arguments, true, true));
  };

  // Produce an array that contains every item shared between all the
  // passed-in arrays.
  _.intersection = function(array) {
    var result = [];
    var argsLength = arguments.length;
    for (var i = 0, length = getLength(array); i < length; i++) {
      var item = array[i];
      if (_.contains(result, item)) continue;
      for (var j = 1; j < argsLength; j++) {
        if (!_.contains(arguments[j], item)) break;
      }
      if (j === argsLength) result.push(item);
    }
    return result;
  };

  // Take the difference between one array and a number of other arrays.
  // Only the elements present in just the first array will remain.
  _.difference = function(array) {
    var rest = flatten(arguments, true, true, 1);
    return _.filter(array, function(value){
      return !_.contains(rest, value);
    });
  };

  // Zip together multiple lists into a single array -- elements that share
  // an index go together.
  _.zip = function() {
    return _.unzip(arguments);
  };

  // Complement of _.zip. Unzip accepts an array of arrays and groups
  // each array's elements on shared indices
  _.unzip = function(array) {
    var length = array && _.max(array, getLength).length || 0;
    var result = Array(length);

    for (var index = 0; index < length; index++) {
      result[index] = _.pluck(array, index);
    }
    return result;
  };

  // Converts lists into objects. Pass either a single array of `[key, value]`
  // pairs, or two parallel arrays of the same length -- one of keys, and one of
  // the corresponding values.
  _.object = function(list, values) {
    var result = {};
    for (var i = 0, length = getLength(list); i < length; i++) {
      if (values) {
        result[list[i]] = values[i];
      } else {
        result[list[i][0]] = list[i][1];
      }
    }
    return result;
  };

  // Generator function to create the findIndex and findLastIndex functions
  function createPredicateIndexFinder(dir) {
    return function(array, predicate, context) {
      predicate = cb(predicate, context);
      var length = getLength(array);
      var index = dir > 0 ? 0 : length - 1;
      for (; index >= 0 && index < length; index += dir) {
        if (predicate(array[index], index, array)) return index;
      }
      return -1;
    };
  }

  // Returns the first index on an array-like that passes a predicate test
  _.findIndex = createPredicateIndexFinder(1);
  _.findLastIndex = createPredicateIndexFinder(-1);

  // Use a comparator function to figure out the smallest index at which
  // an object should be inserted so as to maintain order. Uses binary search.
  _.sortedIndex = function(array, obj, iteratee, context) {
    iteratee = cb(iteratee, context, 1);
    var value = iteratee(obj);
    var low = 0, high = getLength(array);
    while (low < high) {
      var mid = Math.floor((low + high) / 2);
      if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
    }
    return low;
  };

  // Generator function to create the indexOf and lastIndexOf functions
  function createIndexFinder(dir, predicateFind, sortedIndex) {
    return function(array, item, idx) {
      var i = 0, length = getLength(array);
      if (typeof idx == 'number') {
        if (dir > 0) {
            i = idx >= 0 ? idx : Math.max(idx + length, i);
        } else {
            length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
        }
      } else if (sortedIndex && idx && length) {
        idx = sortedIndex(array, item);
        return array[idx] === item ? idx : -1;
      }
      if (item !== item) {
        idx = predicateFind(slice.call(array, i, length), _.isNaN);
        return idx >= 0 ? idx + i : -1;
      }
      for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
        if (array[idx] === item) return idx;
      }
      return -1;
    };
  }

  // Return the position of the first occurrence of an item in an array,
  // or -1 if the item is not included in the array.
  // If the array is large and already in sort order, pass `true`
  // for **isSorted** to use binary search.
  _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
  _.lastIndexOf = createIndexFinder(-1, _.findLastIndex);

  // Generate an integer Array containing an arithmetic progression. A port of
  // the native Python `range()` function. See
  // [the Python documentation](http://docs.python.org/library/functions.html#range).
  _.range = function(start, stop, step) {
    if (stop == null) {
      stop = start || 0;
      start = 0;
    }
    step = step || 1;

    var length = Math.max(Math.ceil((stop - start) / step), 0);
    var range = Array(length);

    for (var idx = 0; idx < length; idx++, start += step) {
      range[idx] = start;
    }

    return range;
  };

  // Function (ahem) Functions
  // ------------------

  // Determines whether to execute a function as a constructor
  // or a normal function with the provided arguments
  var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {
    if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
    var self = baseCreate(sourceFunc.prototype);
    var result = sourceFunc.apply(self, args);
    if (_.isObject(result)) return result;
    return self;
  };

  // Create a function bound to a given object (assigning `this`, and arguments,
  // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
  // available.
  _.bind = function(func, context) {
    if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
    if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
    var args = slice.call(arguments, 2);
    var bound = function() {
      return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));
    };
    return bound;
  };

  // Partially apply a function by creating a version that has had some of its
  // arguments pre-filled, without changing its dynamic `this` context. _ acts
  // as a placeholder, allowing any combination of arguments to be pre-filled.
  _.partial = function(func) {
    var boundArgs = slice.call(arguments, 1);
    var bound = function() {
      var position = 0, length = boundArgs.length;
      var args = Array(length);
      for (var i = 0; i < length; i++) {
        args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];
      }
      while (position < arguments.length) args.push(arguments[position++]);
      return executeBound(func, bound, this, this, args);
    };
    return bound;
  };

  // Bind a number of an object's methods to that object. Remaining arguments
  // are the method names to be bound. Useful for ensuring that all callbacks
  // defined on an object belong to it.
  _.bindAll = function(obj) {
    var i, length = arguments.length, key;
    if (length <= 1) throw new Error('bindAll must be passed function names');
    for (i = 1; i < length; i++) {
      key = arguments[i];
      obj[key] = _.bind(obj[key], obj);
    }
    return obj;
  };

  // Memoize an expensive function by storing its results.
  _.memoize = function(func, hasher) {
    var memoize = function(key) {
      var cache = memoize.cache;
      var address = '' + (hasher ? hasher.apply(this, arguments) : key);
      if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
      return cache[address];
    };
    memoize.cache = {};
    return memoize;
  };

  // Delays a function for the given number of milliseconds, and then calls
  // it with the arguments supplied.
  _.delay = function(func, wait) {
    var args = slice.call(arguments, 2);
    return setTimeout(function(){
      return func.apply(null, args);
    }, wait);
  };

  // Defers a function, scheduling it to run after the current call stack has
  // cleared.
  _.defer = _.partial(_.delay, _, 1);

  // Returns a function, that, when invoked, will only be triggered at most once
  // during a given window of time. Normally, the throttled function will run
  // as much as it can, without ever going more than once per `wait` duration;
  // but if you'd like to disable the execution on the leading edge, pass
  // `{leading: false}`. To disable execution on the trailing edge, ditto.
  _.throttle = function(func, wait, options) {
    var context, args, result;
    var timeout = null;
    var previous = 0;
    if (!options) options = {};
    var later = function() {
      previous = options.leading === false ? 0 : _.now();
      timeout = null;
      result = func.apply(context, args);
      if (!timeout) context = args = null;
    };
    return function() {
      var now = _.now();
      if (!previous && options.leading === false) previous = now;
      var remaining = wait - (now - previous);
      context = this;
      args = arguments;
      if (remaining <= 0 || remaining > wait) {
        if (timeout) {
          clearTimeout(timeout);
          timeout = null;
        }
        previous = now;
        result = func.apply(context, args);
        if (!timeout) context = args = null;
      } else if (!timeout && options.trailing !== false) {
        timeout = setTimeout(later, remaining);
      }
      return result;
    };
  };

  // Returns a function, that, as long as it continues to be invoked, will not
  // be triggered. The function will be called after it stops being called for
  // N milliseconds. If `immediate` is passed, trigger the function on the
  // leading edge, instead of the trailing.
  _.debounce = function(func, wait, immediate) {
    var timeout, args, context, timestamp, result;

    var later = function() {
      var last = _.now() - timestamp;

      if (last < wait && last >= 0) {
        timeout = setTimeout(later, wait - last);
      } else {
        timeout = null;
        if (!immediate) {
          result = func.apply(context, args);
          if (!timeout) context = args = null;
        }
      }
    };

    return function() {
      context = this;
      args = arguments;
      timestamp = _.now();
      var callNow = immediate && !timeout;
      if (!timeout) timeout = setTimeout(later, wait);
      if (callNow) {
        result = func.apply(context, args);
        context = args = null;
      }

      return result;
    };
  };

  // Returns the first function passed as an argument to the second,
  // allowing you to adjust arguments, run code before and after, and
  // conditionally execute the original function.
  _.wrap = function(func, wrapper) {
    return _.partial(wrapper, func);
  };

  // Returns a negated version of the passed-in predicate.
  _.negate = function(predicate) {
    return function() {
      return !predicate.apply(this, arguments);
    };
  };

  // Returns a function that is the composition of a list of functions, each
  // consuming the return value of the function that follows.
  _.compose = function() {
    var args = arguments;
    var start = args.length - 1;
    return function() {
      var i = start;
      var result = args[start].apply(this, arguments);
      while (i--) result = args[i].call(this, result);
      return result;
    };
  };

  // Returns a function that will only be executed on and after the Nth call.
  _.after = function(times, func) {
    return function() {
      if (--times < 1) {
        return func.apply(this, arguments);
      }
    };
  };

  // Returns a function that will only be executed up to (but not including) the Nth call.
  _.before = function(times, func) {
    var memo;
    return function() {
      if (--times > 0) {
        memo = func.apply(this, arguments);
      }
      if (times <= 1) func = null;
      return memo;
    };
  };

  // Returns a function that will be executed at most one time, no matter how
  // often you call it. Useful for lazy initialization.
  _.once = _.partial(_.before, 2);

  // Object Functions
  // ----------------

  // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
  var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
  var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
                      'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];

  function collectNonEnumProps(obj, keys) {
    var nonEnumIdx = nonEnumerableProps.length;
    var constructor = obj.constructor;
    var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto;

    // Constructor is a special case.
    var prop = 'constructor';
    if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);

    while (nonEnumIdx--) {
      prop = nonEnumerableProps[nonEnumIdx];
      if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
        keys.push(prop);
      }
    }
  }

  // Retrieve the names of an object's own properties.
  // Delegates to **ECMAScript 5**'s native `Object.keys`
  _.keys = function(obj) {
    if (!_.isObject(obj)) return [];
    if (nativeKeys) return nativeKeys(obj);
    var keys = [];
    for (var key in obj) if (_.has(obj, key)) keys.push(key);
    // Ahem, IE < 9.
    if (hasEnumBug) collectNonEnumProps(obj, keys);
    return keys;
  };

  // Retrieve all the property names of an object.
  _.allKeys = function(obj) {
    if (!_.isObject(obj)) return [];
    var keys = [];
    for (var key in obj) keys.push(key);
    // Ahem, IE < 9.
    if (hasEnumBug) collectNonEnumProps(obj, keys);
    return keys;
  };

  // Retrieve the values of an object's properties.
  _.values = function(obj) {
    var keys = _.keys(obj);
    var length = keys.length;
    var values = Array(length);
    for (var i = 0; i < length; i++) {
      values[i] = obj[keys[i]];
    }
    return values;
  };

  // Returns the results of applying the iteratee to each element of the object
  // In contrast to _.map it returns an object
  _.mapObject = function(obj, iteratee, context) {
    iteratee = cb(iteratee, context);
    var keys =  _.keys(obj),
          length = keys.length,
          results = {},
          currentKey;
      for (var index = 0; index < length; index++) {
        currentKey = keys[index];
        results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
      }
      return results;
  };

  // Convert an object into a list of `[key, value]` pairs.
  _.pairs = function(obj) {
    var keys = _.keys(obj);
    var length = keys.length;
    var pairs = Array(length);
    for (var i = 0; i < length; i++) {
      pairs[i] = [keys[i], obj[keys[i]]];
    }
    return pairs;
  };

  // Invert the keys and values of an object. The values must be serializable.
  _.invert = function(obj) {
    var result = {};
    var keys = _.keys(obj);
    for (var i = 0, length = keys.length; i < length; i++) {
      result[obj[keys[i]]] = keys[i];
    }
    return result;
  };

  // Return a sorted list of the function names available on the object.
  // Aliased as `methods`
  _.functions = _.methods = function(obj) {
    var names = [];
    for (var key in obj) {
      if (_.isFunction(obj[key])) names.push(key);
    }
    return names.sort();
  };

  // Extend a given object with all the properties in passed-in object(s).
  _.extend = createAssigner(_.allKeys);

  // Assigns a given object with all the own properties in the passed-in object(s)
  // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
  _.extendOwn = _.assign = createAssigner(_.keys);

  // Returns the first key on an object that passes a predicate test
  _.findKey = function(obj, predicate, context) {
    predicate = cb(predicate, context);
    var keys = _.keys(obj), key;
    for (var i = 0, length = keys.length; i < length; i++) {
      key = keys[i];
      if (predicate(obj[key], key, obj)) return key;
    }
  };

  // Return a copy of the object only containing the whitelisted properties.
  _.pick = function(object, oiteratee, context) {
    var result = {}, obj = object, iteratee, keys;
    if (obj == null) return result;
    if (_.isFunction(oiteratee)) {
      keys = _.allKeys(obj);
      iteratee = optimizeCb(oiteratee, context);
    } else {
      keys = flatten(arguments, false, false, 1);
      iteratee = function(value, key, obj) { return key in obj; };
      obj = Object(obj);
    }
    for (var i = 0, length = keys.length; i < length; i++) {
      var key = keys[i];
      var value = obj[key];
      if (iteratee(value, key, obj)) result[key] = value;
    }
    return result;
  };

   // Return a copy of the object without the blacklisted properties.
  _.omit = function(obj, iteratee, context) {
    if (_.isFunction(iteratee)) {
      iteratee = _.negate(iteratee);
    } else {
      var keys = _.map(flatten(arguments, false, false, 1), String);
      iteratee = function(value, key) {
        return !_.contains(keys, key);
      };
    }
    return _.pick(obj, iteratee, context);
  };

  // Fill in a given object with default properties.
  _.defaults = createAssigner(_.allKeys, true);

  // Creates an object that inherits from the given prototype object.
  // If additional properties are provided then they will be added to the
  // created object.
  _.create = function(prototype, props) {
    var result = baseCreate(prototype);
    if (props) _.extendOwn(result, props);
    return result;
  };

  // Create a (shallow-cloned) duplicate of an object.
  _.clone = function(obj) {
    if (!_.isObject(obj)) return obj;
    return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
  };

  // Invokes interceptor with the obj, and then returns obj.
  // The primary purpose of this method is to "tap into" a method chain, in
  // order to perform operations on intermediate results within the chain.
  _.tap = function(obj, interceptor) {
    interceptor(obj);
    return obj;
  };

  // Returns whether an object has a given set of `key:value` pairs.
  _.isMatch = function(object, attrs) {
    var keys = _.keys(attrs), length = keys.length;
    if (object == null) return !length;
    var obj = Object(object);
    for (var i = 0; i < length; i++) {
      var key = keys[i];
      if (attrs[key] !== obj[key] || !(key in obj)) return false;
    }
    return true;
  };


  // Internal recursive comparison function for `isEqual`.
  var eq = function(a, b, aStack, bStack) {
    // Identical objects are equal. `0 === -0`, but they aren't identical.
    // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
    if (a === b) return a !== 0 || 1 / a === 1 / b;
    // A strict comparison is necessary because `null == undefined`.
    if (a == null || b == null) return a === b;
    // Unwrap any wrapped objects.
    if (a instanceof _) a = a._wrapped;
    if (b instanceof _) b = b._wrapped;
    // Compare `[[Class]]` names.
    var className = toString.call(a);
    if (className !== toString.call(b)) return false;
    switch (className) {
      // Strings, numbers, regular expressions, dates, and booleans are compared by value.
      case '[object RegExp]':
      // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
      case '[object String]':
        // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
        // equivalent to `new String("5")`.
        return '' + a === '' + b;
      case '[object Number]':
        // `NaN`s are equivalent, but non-reflexive.
        // Object(NaN) is equivalent to NaN
        if (+a !== +a) return +b !== +b;
        // An `egal` comparison is performed for other numeric values.
        return +a === 0 ? 1 / +a === 1 / b : +a === +b;
      case '[object Date]':
      case '[object Boolean]':
        // Coerce dates and booleans to numeric primitive values. Dates are compared by their
        // millisecond representations. Note that invalid dates with millisecond representations
        // of `NaN` are not equivalent.
        return +a === +b;
    }

    var areArrays = className === '[object Array]';
    if (!areArrays) {
      if (typeof a != 'object' || typeof b != 'object') return false;

      // Objects with different constructors are not equivalent, but `Object`s or `Array`s
      // from different frames are.
      var aCtor = a.constructor, bCtor = b.constructor;
      if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
                               _.isFunction(bCtor) && bCtor instanceof bCtor)
                          && ('constructor' in a && 'constructor' in b)) {
        return false;
      }
    }
    // Assume equality for cyclic structures. The algorithm for detecting cyclic
    // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.

    // Initializing stack of traversed objects.
    // It's done here since we only need them for objects and arrays comparison.
    aStack = aStack || [];
    bStack = bStack || [];
    var length = aStack.length;
    while (length--) {
      // Linear search. Performance is inversely proportional to the number of
      // unique nested structures.
      if (aStack[length] === a) return bStack[length] === b;
    }

    // Add the first object to the stack of traversed objects.
    aStack.push(a);
    bStack.push(b);

    // Recursively compare objects and arrays.
    if (areArrays) {
      // Compare array lengths to determine if a deep comparison is necessary.
      length = a.length;
      if (length !== b.length) return false;
      // Deep compare the contents, ignoring non-numeric properties.
      while (length--) {
        if (!eq(a[length], b[length], aStack, bStack)) return false;
      }
    } else {
      // Deep compare objects.
      var keys = _.keys(a), key;
      length = keys.length;
      // Ensure that both objects contain the same number of properties before comparing deep equality.
      if (_.keys(b).length !== length) return false;
      while (length--) {
        // Deep compare each member
        key = keys[length];
        if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
      }
    }
    // Remove the first object from the stack of traversed objects.
    aStack.pop();
    bStack.pop();
    return true;
  };

  // Perform a deep comparison to check if two objects are equal.
  _.isEqual = function(a, b) {
    return eq(a, b);
  };

  // Is a given array, string, or object empty?
  // An "empty" object has no enumerable own-properties.
  _.isEmpty = function(obj) {
    if (obj == null) return true;
    if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
    return _.keys(obj).length === 0;
  };

  // Is a given value a DOM element?
  _.isElement = function(obj) {
    return !!(obj && obj.nodeType === 1);
  };

  // Is a given value an array?
  // Delegates to ECMA5's native Array.isArray
  _.isArray = nativeIsArray || function(obj) {
    return toString.call(obj) === '[object Array]';
  };

  // Is a given variable an object?
  _.isObject = function(obj) {
    var type = typeof obj;
    return type === 'function' || type === 'object' && !!obj;
  };

  // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.
  _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {
    _['is' + name] = function(obj) {
      return toString.call(obj) === '[object ' + name + ']';
    };
  });

  // Define a fallback version of the method in browsers (ahem, IE < 9), where
  // there isn't any inspectable "Arguments" type.
  if (!_.isArguments(arguments)) {
    _.isArguments = function(obj) {
      return _.has(obj, 'callee');
    };
  }

  // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
  // IE 11 (#1621), and in Safari 8 (#1929).
  if (typeof /./ != 'function' && typeof Int8Array != 'object') {
    _.isFunction = function(obj) {
      return typeof obj == 'function' || false;
    };
  }

  // Is a given object a finite number?
  _.isFinite = function(obj) {
    return isFinite(obj) && !isNaN(parseFloat(obj));
  };

  // Is the given value `NaN`? (NaN is the only number which does not equal itself).
  _.isNaN = function(obj) {
    return _.isNumber(obj) && obj !== +obj;
  };

  // Is a given value a boolean?
  _.isBoolean = function(obj) {
    return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
  };

  // Is a given value equal to null?
  _.isNull = function(obj) {
    return obj === null;
  };

  // Is a given variable undefined?
  _.isUndefined = function(obj) {
    return obj === void 0;
  };

  // Shortcut function for checking if an object has a given property directly
  // on itself (in other words, not on a prototype).
  _.has = function(obj, key) {
    return obj != null && hasOwnProperty.call(obj, key);
  };

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

  // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
  // previous owner. Returns a reference to the Underscore object.
  _.noConflict = function() {
    root._ = previousUnderscore;
    return this;
  };

  // Keep the identity function around for default iteratees.
  _.identity = function(value) {
    return value;
  };

  // Predicate-generating functions. Often useful outside of Underscore.
  _.constant = function(value) {
    return function() {
      return value;
    };
  };

  _.noop = function(){};

  _.property = property;

  // Generates a function for a given object that returns a given property.
  _.propertyOf = function(obj) {
    return obj == null ? function(){} : function(key) {
      return obj[key];
    };
  };

  // Returns a predicate for checking whether an object has a given set of
  // `key:value` pairs.
  _.matcher = _.matches = function(attrs) {
    attrs = _.extendOwn({}, attrs);
    return function(obj) {
      return _.isMatch(obj, attrs);
    };
  };

  // Run a function **n** times.
  _.times = function(n, iteratee, context) {
    var accum = Array(Math.max(0, n));
    iteratee = optimizeCb(iteratee, context, 1);
    for (var i = 0; i < n; i++) accum[i] = iteratee(i);
    return accum;
  };

  // Return a random integer between min and max (inclusive).
  _.random = function(min, max) {
    if (max == null) {
      max = min;
      min = 0;
    }
    return min + Math.floor(Math.random() * (max - min + 1));
  };

  // A (possibly faster) way to get the current timestamp as an integer.
  _.now = Date.now || function() {
    return new Date().getTime();
  };

   // List of HTML entities for escaping.
  var escapeMap = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#x27;',
    '`': '&#x60;'
  };
  var unescapeMap = _.invert(escapeMap);

  // Functions for escaping and unescaping strings to/from HTML interpolation.
  var createEscaper = function(map) {
    var escaper = function(match) {
      return map[match];
    };
    // Regexes for identifying a key that needs to be escaped
    var source = '(?:' + _.keys(map).join('|') + ')';
    var testRegexp = RegExp(source);
    var replaceRegexp = RegExp(source, 'g');
    return function(string) {
      string = string == null ? '' : '' + string;
      return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
    };
  };
  _.escape = createEscaper(escapeMap);
  _.unescape = createEscaper(unescapeMap);

  // If the value of the named `property` is a function then invoke it with the
  // `object` as context; otherwise, return it.
  _.result = function(object, property, fallback) {
    var value = object == null ? void 0 : object[property];
    if (value === void 0) {
      value = fallback;
    }
    return _.isFunction(value) ? value.call(object) : value;
  };

  // Generate a unique integer id (unique within the entire client session).
  // Useful for temporary DOM ids.
  var idCounter = 0;
  _.uniqueId = function(prefix) {
    var id = ++idCounter + '';
    return prefix ? prefix + id : id;
  };

  // By default, Underscore uses ERB-style template delimiters, change the
  // following template settings to use alternative delimiters.
  _.templateSettings = {
    evaluate    : /<%([\s\S]+?)%>/g,
    interpolate : /<%=([\s\S]+?)%>/g,
    escape      : /<%-([\s\S]+?)%>/g
  };

  // When customizing `templateSettings`, if you don't want to define an
  // interpolation, evaluation or escaping regex, we need one that is
  // guaranteed not to match.
  var noMatch = /(.)^/;

  // Certain characters need to be escaped so that they can be put into a
  // string literal.
  var escapes = {
    "'":      "'",
    '\\':     '\\',
    '\r':     'r',
    '\n':     'n',
    '\u2028': 'u2028',
    '\u2029': 'u2029'
  };

  var escaper = /\\|'|\r|\n|\u2028|\u2029/g;

  var escapeChar = function(match) {
    return '\\' + escapes[match];
  };

  // JavaScript micro-templating, similar to John Resig's implementation.
  // Underscore templating handles arbitrary delimiters, preserves whitespace,
  // and correctly escapes quotes within interpolated code.
  // NB: `oldSettings` only exists for backwards compatibility.
  _.template = function(text, settings, oldSettings) {
    if (!settings && oldSettings) settings = oldSettings;
    settings = _.defaults({}, settings, _.templateSettings);

    // Combine delimiters into one regular expression via alternation.
    var matcher = RegExp([
      (settings.escape || noMatch).source,
      (settings.interpolate || noMatch).source,
      (settings.evaluate || noMatch).source
    ].join('|') + '|$', 'g');

    // Compile the template source, escaping string literals appropriately.
    var index = 0;
    var source = "__p+='";
    text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
      source += text.slice(index, offset).replace(escaper, escapeChar);
      index = offset + match.length;

      if (escape) {
        source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
      } else if (interpolate) {
        source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
      } else if (evaluate) {
        source += "';\n" + evaluate + "\n__p+='";
      }

      // Adobe VMs need the match returned to produce the correct offest.
      return match;
    });
    source += "';\n";

    // If a variable is not specified, place data values in local scope.
    if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';

    source = "var __t,__p='',__j=Array.prototype.join," +
      "print=function(){__p+=__j.call(arguments,'');};\n" +
      source + 'return __p;\n';

    try {
      var render = new Function(settings.variable || 'obj', '_', source);
    } catch (e) {
      e.source = source;
      throw e;
    }

    var template = function(data) {
      return render.call(this, data, _);
    };

    // Provide the compiled source as a convenience for precompilation.
    var argument = settings.variable || 'obj';
    template.source = 'function(' + argument + '){\n' + source + '}';

    return template;
  };

  // Add a "chain" function. Start chaining a wrapped Underscore object.
  _.chain = function(obj) {
    var instance = _(obj);
    instance._chain = true;
    return instance;
  };

  // OOP
  // ---------------
  // If Underscore is called as a function, it returns a wrapped object that
  // can be used OO-style. This wrapper holds altered versions of all the
  // underscore functions. Wrapped objects may be chained.

  // Helper function to continue chaining intermediate results.
  var result = function(instance, obj) {
    return instance._chain ? _(obj).chain() : obj;
  };

  // Add your own custom functions to the Underscore object.
  _.mixin = function(obj) {
    _.each(_.functions(obj), function(name) {
      var func = _[name] = obj[name];
      _.prototype[name] = function() {
        var args = [this._wrapped];
        push.apply(args, arguments);
        return result(this, func.apply(_, args));
      };
    });
  };

  // Add all of the Underscore functions to the wrapper object.
  _.mixin(_);

  // Add all mutator Array functions to the wrapper.
  _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
    var method = ArrayProto[name];
    _.prototype[name] = function() {
      var obj = this._wrapped;
      method.apply(obj, arguments);
      if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
      return result(this, obj);
    };
  });

  // Add all accessor Array functions to the wrapper.
  _.each(['concat', 'join', 'slice'], function(name) {
    var method = ArrayProto[name];
    _.prototype[name] = function() {
      return result(this, method.apply(this._wrapped, arguments));
    };
  });

  // Extracts the result from a wrapped and chained object.
  _.prototype.value = function() {
    return this._wrapped;
  };

  // Provide unwrapping proxy for some methods used in engine operations
  // such as arithmetic and JSON stringification.
  _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;

  _.prototype.toString = function() {
    return '' + this._wrapped;
  };

  // AMD registration happens at the end for compatibility with AMD loaders
  // that may not enforce next-turn semantics on modules. Even though general
  // practice for AMD registration is to be anonymous, underscore registers
  // as a named module because, like jQuery, it is a base library that is
  // popular enough to be bundled in a third party lib, but not be part of
  // an AMD load request. Those cases could generate an error when an
  // anonymous define() is called outside of a loader request.
  if (typeof define === 'function' && define.amd) {
    define('underscore', [], function() {
      return _;
    });
  }
}.call(this));

},{}],"api/figure":[function(require,module,exports){
var Collections, ColumnDataSource, FactorRange, Logging, Range1d, _, _get_axis_type, _get_num_minor_ticks, _get_range, _get_sources, _process_annotations, _process_glyphs, _process_guides, _process_tools, add_annotations, add_glyphs, add_guides, add_tools, base, figure, helpers, logger, make_plot, make_sources;

_ = require("underscore");

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

Logging = require("../common/logging");

FactorRange = require("../range/factor_range");

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

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

helpers = "./helpers";

Collections = base.Collections;

logger = Logging.logger;

_get_num_minor_ticks = function(axis_type, num_minor_ticks) {
  if (num_minor_ticks == null) {
    return 0;
  }
  if (_.isNumber(num_minor_ticks)) {
    if (num_minor_ticks <= 1) {
      logger.error("num_minor_ticks must be > 1");
      num_minor_ticks = 0;
    }
    return num_minor_ticks;
  }
  if (num_minor_ticks === 'auto') {
    if ((axis_type != null) === "Log") {
      return 10;
    }
    return 5;
  }
  logger.error("unrecognized num_minor_ticks: " + num_minor_ticks);
  return 0;
};

_get_axis_type = function(axis_type, range) {
  var e, error, error1;
  if (axis_type == null) {
    return null;
  }
  if (axis_type === "auto") {
    if (range instanceof FactorRange.Model) {
      return Collections("CategoricalAxis");
    } else if (range instanceof Range1d.Model) {
      try {
        new Date.parse(range.get('start'));
        return Collections("DatetimeAxis");
      } catch (error) {
        e = error;
        "pass";
      }
      return Collections("LinearAxis");
    }
  }
  try {
    return Collections(axis_type + "Axis");
  } catch (error1) {
    e = error1;
    logger.error("unrecognized axis_type: " + axis_type);
    return null;
  }
};

_get_range = function(range) {
  if (range == null) {
    return Collections("DataRange1d").create();
  }
  if (_.isArray(range)) {
    if (_.every(range, _.isString)) {
      return Collections("FactorRange").create({
        factors: range
      });
    }
    if (range.length === 2 && _.every(range, _.isNumber)) {
      return Collections("Range1d").create({
        start: range[0],
        end: range[1]
      });
    }
  }
  logger.error("Unrecognized range input: " + range.toJSON);
  return null;
};

_get_sources = function(sources, glyph_source) {
  if (glyph_source instanceof ColumnDataSource.Model) {
    return glyph_source;
  }
  if (_.isString(glyph_source)) {
    return sources[glyph_source];
  }
  return Collections("ColumnDataSource").create({
    data: glyph_source
  });
};

_process_annotations = function(annotations) {
  var annotation_objs;
  annotation_objs = [];
  return annotation_objs;
};

_process_tools = function(tools, plot) {
  var e, error, i, len, tool, tool_args, tool_obj, tool_objs, tool_type;
  tool_objs = [];
  for (i = 0, len = tools.length; i < len; i++) {
    tool = tools[i];
    if (_.isString(tool)) {
      tool_type = tool + "Tool";
      tool_args = {
        plot: plot
      };
    } else {
      tool_type = tool.type + "Tool";
      tool_args = _.omit(tool, "type");
    }
    try {
      tool_obj = Collections(tool_type).create(tool_args);
      tool_objs.push(tool_obj);
    } catch (error) {
      e = error;
      logger.error("unrecognized tool: " + tool);
    }
  }
  return tool_objs;
};

_process_glyphs = function(glyphs, sources) {
  var glyph, glyph_args, glyph_obj, glyph_type, i, j, len, len1, ref, renderer, renderer_args, renderers, source, x, x_args, x_obj;
  renderers = [];
  for (i = 0, len = glyphs.length; i < len; i++) {
    glyph = glyphs[i];
    glyph_type = glyph.type;
    source = _get_sources(sources, glyph.source);
    glyph_args = _.omit(glyph, 'source', 'selection', 'inspection', 'nonselection');
    glyph_obj = Collections(glyph_type).create(glyph_args);
    renderer_args = {
      data_source: source,
      glyph: glyph_obj
    };
    ref = ['selection', 'inspection', 'nonselection'];
    for (j = 0, len1 = ref.length; j < len1; j++) {
      x = ref[j];
      if (glyph[x] != null) {
        if (glyph[x].type != null) {
          x_args = _.omit(glyph[x], 'type');
          x_obj = Collections(glyph[x].type).create(x_args);
        } else {
          x_obj = _.clone(glyph_obj);
          x_obj.set(glyph[x]);
        }
        renderer_args[x] = x_obj;
      }
    }
    renderer = Collections("GlyphRenderer").create(renderer_args);
    renderers.push(renderer);
  }
  return renderers;
};

_process_guides = function(guides, plot) {
  var axis, axis_args, axis_type, dim, grid, guide, guide_objs, i, len, location, range;
  guide_objs = [];
  for (i = 0, len = guides.length; i < len; i++) {
    guide = guides[i];
    location = guide.location;
    if (location === "below" || location === "above") {
      dim = 0;
      range = plot.get('x_range');
    } else if (location === "left" || location === "right") {
      dim = 1;
      range = plot.get('y_range');
    } else {
      logger.error("unrecognized axis location: " + location);
      continue;
    }
    axis_type = _get_axis_type(guide.type, range);
    axis_args = _.omit(guide, 'type', 'grid');
    axis_args['plot'] = plot;
    axis = axis_type.create(axis_args);
    guide_objs.push(axis);
    if (guide.grid === true) {
      grid = Collections("Grid").create({
        dimension: dim,
        plot: plot,
        ticker: axis.get('ticker')
      });
      guide_objs.push(grid);
    }
  }
  return guide_objs;
};

make_plot = function(options) {
  var plot;
  options.x_range = _get_range(options.x_range);
  options.y_range = _get_range(options.y_range);
  plot = Collections('Plot').create(options);
  return plot;
};

make_sources = function(data) {
  var key, source_objs, value;
  source_objs = {};
  for (key in data) {
    value = data[key];
    source_objs[key] = Collections("ColumnDataSource").create({
      data: value
    });
  }
  return source_objs;
};

add_glyphs = function(plot, sources, glyphs) {
  glyphs = _process_glyphs(glyphs, sources);
  return plot.add_renderers(glyphs);
};

add_guides = function(plot, guides) {
  var guide, i, len, loc, location;
  guides = _process_guides(guides, plot);
  for (i = 0, len = guides.length; i < len; i++) {
    guide = guides[i];
    location = guide.get('location');
    if (location != null) {
      loc = plot.get(location);
      loc.push(guide);
      plot.set(location, loc);
    }
  }
  return plot.add_renderers(guides);
};

add_annotations = function(plot, annotations) {
  annotations = _process_annotations(annotations);
  return plot.add_renderers(annotations);
};

add_tools = function(plot, tools) {
  var i, len, tool;
  tools = _process_tools(tools, plot);
  for (i = 0, len = tools.length; i < len; i++) {
    tool = tools[i];
    tool.set('plot', plot);
  }
  plot.set_obj('tools', tools);
  plot.get('tool_manager').set_obj('tools', tools);
  return plot.get('tool_manager')._init_tools();
};

figure = function(arg) {
  var annotations, glyphs, guides, options, plot, sources, tools;
  options = arg.options, sources = arg.sources, glyphs = arg.glyphs, guides = arg.guides, annotations = arg.annotations, tools = arg.tools;
  if (options == null) {
    options = {};
  }
  if (sources == null) {
    sources = {};
  }
  if (glyphs == null) {
    glyphs = [];
  }
  if (guides == null) {
    guides = [];
  }
  if (annotations == null) {
    annotations = {};
  }
  if (tools == null) {
    tools = [];
  }
  plot = make_plot(options);
  sources = make_sources(sources);
  add_glyphs(plot, sources, glyphs);
  add_guides(plot, guides);
  add_annotations(plot, annotations);
  add_tools(plot, tools);
  return plot;
};

module.exports = figure;


},{"../common/base":"common/base","../common/logging":"common/logging","../range/factor_range":"range/factor_range","../range/range1d":"range/range1d","../source/column_data_source":"source/column_data_source","underscore":"underscore"}],"api/helpers":[function(require,module,exports){
var Logging, _, logger, show;

_ = require("underscore");

Logging = require("../common/logging");

logger = Logging.logger;

show = function(target, plot) {
  var myrender;
  logger.debug("Scheduling render for plot " + plot + " on target " + target);
  myrender = function() {
    var view;
    view = new plot.default_view({
      model: plot
    });
    return target.append(view.$el);
  };
  return _.defer(myrender);
};

module.exports = {
  show: show
};


},{"../common/logging":"common/logging","underscore":"underscore"}],"api/plugin":[function(require,module,exports){
var $, Logging, _, _api, figure, helpers, logger, show;

_ = require("underscore");

$ = require("jquery");

Logging = require("../common/logging");

figure = require("./figure");

helpers = require("./helpers");

logger = Logging.logger;

show = helpers.show;

_api = {
  "figure": figure
};

$.fn.bokeh = function(type, args) {
  var obj;
  if (!(type in _api)) {
    logger.error("Unknown API type '" + type + "'. Recognized API types: " + (Object.keys(_api)));
    return this;
  }
  obj = _api[type](args);
  show(this, obj);
  return obj;
};

module.exports = $.fn.bokeh;


},{"../common/logging":"common/logging","./figure":"api/figure","./helpers":"api/helpers","jquery":"jquery","underscore":"underscore"}],"ar/transforms":[function(require,module,exports){
var HasProperties, Transform, _make_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;

HasProperties = require("../common/has_properties");

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

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

  return Transform;

})(HasProperties);

_make_transform = function(name) {
  var holder;
  holder = {};
  holder.Model = (function(superClass) {
    extend(_Class, superClass);

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

    _Class.prototype.type = name;

    return _Class;

  })(Transform);
  return holder;
};

module.exports = {
  AutoEncode: _make_transform("AutoEncode"),
  BinarySegment: _make_transform("BinarySegment"),
  Const: _make_transform("Const"),
  Contour: _make_transform("Contour"),
  Count: _make_transform("Count"),
  CountCategories: _make_transform("CountCategories"),
  Cuberoot: _make_transform("Cuberoot"),
  Encode: _make_transform("Encode"),
  HDAlpha: _make_transform("HDAlpha"),
  Id: _make_transform("Id"),
  Interpolate: _make_transform("Interpolate"),
  InterpolateColor: _make_transform("InterpolateColor"),
  Log: _make_transform("Log"),
  NonZero: _make_transform("NonZero"),
  Ratio: _make_transform("Ratio"),
  Seq: _make_transform("Seq"),
  Spread: _make_transform("Spread"),
  ToCounts: _make_transform("ToCounts")
};


},{"../common/has_properties":"common/has_properties"}],"callback/customjs":[function(require,module,exports){
var CustomJS, HasProperties, _, coffee,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

coffee = require("coffee-script");

HasProperties = require("../common/has_properties");

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

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

  CustomJS.prototype.type = 'CustomJS';

  CustomJS.prototype.initialize = function(attrs, options) {
    CustomJS.__super__.initialize.call(this, attrs, options);
    this.register_property('values', this._make_values, true);
    this.add_dependencies('values', this, ['args']);
    this.register_property('func', this._make_func, true);
    return this.add_dependencies('func', this, ['args', 'code']);
  };

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

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

  CustomJS.prototype._make_func = function() {
    var code;
    code = this.get("code");
    code = (function() {
      switch (this.get("lang")) {
        case "javascript":
          return code;
        case "coffeescript":
          return coffee.compile(code, {
            bare: true,
            shiftLine: true
          });
      }
    }).call(this);
    return (function(func, args, ctor) {
      ctor.prototype = func.prototype;
      var child = new ctor, result = func.apply(child, args);
      return Object(result) === result ? result : child;
    })(Function, slice.call(_.keys(this.get("args"))).concat(["cb_obj"], ["cb_data"], ["require"], [code]), function(){});
  };

  CustomJS.prototype.defaults = function() {
    return _.extend({}, CustomJS.__super__.defaults.call(this), {
      args: {},
      code: "",
      lang: "javascript"
    });
  };

  return CustomJS;

})(HasProperties);

module.exports = {
  Model: CustomJS
};


},{"../common/has_properties":"common/has_properties","coffee-script":"coffee-script","underscore":"underscore"}],"callback/open_url":[function(require,module,exports){
var HasProperties, OpenURL, 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");

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

HasProperties = require("../common/has_properties");

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

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

  OpenURL.prototype.type = 'OpenURL';

  OpenURL.prototype.execute = function(data_source) {
    var i, j, len, ref, url;
    ref = Util.get_indices(data_source);
    for (j = 0, len = ref.length; j < len; j++) {
      i = ref[j];
      url = Util.replace_placeholders(this.get("url"), data_source, i);
      window.open(url);
    }
    return null;
  };

  OpenURL.prototype.defaults = function() {
    return _.extend({}, OpenURL.__super__.defaults.call(this), {
      url: 'http://'
    });
  };

  return OpenURL;

})(HasProperties);

module.exports = {
  Model: OpenURL
};


},{"../common/has_properties":"common/has_properties","../util/util":"util/util","underscore":"underscore"}],"common/base":[function(require,module,exports){
var Collection, Collections, Config, _, _get_mod_cache, _mod_cache, browserify, coffee, collection_overrides, index, locations, logger, make_cache, make_collection, url, window,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

Collection = require("./collection");

if (typeof window === "undefined" || window === null) {
  window = {
    location: {
      href: "local"
    }
  };
}

coffee = require("coffee-script");

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

require("./custom").monkey_patch();

Config = {};

url = window.location.href;

if (url.indexOf('/bokeh') > 0) {
  Config.prefix = url.slice(0, url.lastIndexOf('/bokeh')) + "/";
} else {
  Config.prefix = '/';
}

console.log('Bokeh: setting prefix to', Config.prefix);

locations = {
  Plot: require('./plot'),
  GMapPlot: require('./gmap_plot'),
  GeoJSPlot: require('./geojs_plot'),
  GridPlot: require('./grid_plot'),
  Canvas: require('./canvas'),
  LayoutBox: require('./layout_box'),
  CartesianFrame: require('./cartesian_frame'),
  SelectionManager: require('./selection_manager'),
  Selector: require('./selector'),
  ToolEvents: require('./tool_events'),
  CustomJS: require('../callback/customjs'),
  OpenURL: require('../callback/open_url'),
  CategoricalMapper: require('../mapper/categorical_mapper'),
  LinearColorMapper: require('../mapper/linear_color_mapper'),
  LinearMapper: require('../mapper/linear_mapper'),
  LogMapper: require('../mapper/log_mapper'),
  DataRange1d: require('../range/data_range1d'),
  FactorRange: require('../range/factor_range'),
  Range1d: require('../range/range1d'),
  BoxAnnotation: require('../renderer/annotation/box_annotation'),
  Legend: require('../renderer/annotation/legend'),
  Span: require('../renderer/annotation/span'),
  Tooltip: require('../renderer/annotation/tooltip'),
  TileRenderer: require('../renderer/tile/tile_renderer'),
  TileSource: require('../renderer/tile/tile_source'),
  TMSTileSource: require('../renderer/tile/tms_tile_source'),
  WMTSTileSource: require('../renderer/tile/wmts_tile_source'),
  QUADKEYTileSource: require('../renderer/tile/quadkey_tile_source'),
  BBoxTileSource: require('../renderer/tile/bbox_tile_source'),
  GlyphRenderer: require('../renderer/glyph/glyph_renderer'),
  AnnularWedge: require('../renderer/glyph/annular_wedge'),
  Annulus: require('../renderer/glyph/annulus'),
  Arc: require('../renderer/glyph/arc'),
  Bezier: require('../renderer/glyph/bezier'),
  Circle: require('../renderer/glyph/circle'),
  Gear: require('../renderer/glyph/gear'),
  Image: require('../renderer/glyph/image'),
  ImageRGBA: require('../renderer/glyph/image_rgba'),
  ImageURL: require('../renderer/glyph/image_url'),
  Line: require('../renderer/glyph/line'),
  MultiLine: require('../renderer/glyph/multi_line'),
  Oval: require('../renderer/glyph/oval'),
  Patch: require('../renderer/glyph/patch'),
  Patches: require('../renderer/glyph/patches'),
  Quad: require('../renderer/glyph/quad'),
  Quadratic: require('../renderer/glyph/quadratic'),
  Ray: require('../renderer/glyph/ray'),
  Rect: require('../renderer/glyph/rect'),
  Segment: require('../renderer/glyph/segment'),
  Text: require('../renderer/glyph/text'),
  Wedge: require('../renderer/glyph/wedge'),
  Asterisk: require('../renderer/glyph/marker/asterisk'),
  CircleCross: require('../renderer/glyph/marker/circle_cross'),
  CircleX: require('../renderer/glyph/marker/circle_x'),
  Cross: require('../renderer/glyph/marker/cross'),
  Diamond: require('../renderer/glyph/marker/diamond'),
  DiamondCross: require('../renderer/glyph/marker/diamond_cross'),
  InvertedTriangle: require('../renderer/glyph/marker/inverted_triangle'),
  Square: require('../renderer/glyph/marker/square'),
  SquareCross: require('../renderer/glyph/marker/square_cross'),
  SquareX: require('../renderer/glyph/marker/square_x'),
  Triangle: require('../renderer/glyph/marker/triangle'),
  X: require('../renderer/glyph/marker/x'),
  LinearAxis: require('../renderer/guide/linear_axis'),
  LogAxis: require('../renderer/guide/log_axis'),
  CategoricalAxis: require('../renderer/guide/categorical_axis'),
  DatetimeAxis: require('../renderer/guide/datetime_axis'),
  Grid: require('../renderer/guide/grid'),
  BoxSelection: require('../renderer/overlay/box_selection'),
  PolySelection: require('../renderer/overlay/poly_selection'),
  ColumnDataSource: require('../source/column_data_source'),
  ServerDataSource: require('../source/server_data_source'),
  BlazeDataSource: require('../source/blaze_data_source'),
  AjaxDataSource: require('../source/ajax_data_source'),
  AbstractTicker: require('../ticking/abstract_ticker'),
  AdaptiveTicker: require('../ticking/adaptive_ticker'),
  BasicTicker: require('../ticking/basic_ticker'),
  CategoricalTicker: require('../ticking/categorical_ticker'),
  CompositeTicker: require('../ticking/composite_ticker'),
  DatetimeTicker: require('../ticking/datetime_ticker'),
  DaysTicker: require('../ticking/days_ticker'),
  FixedTicker: require('../ticking/fixed_ticker'),
  LogTicker: require('../ticking/log_ticker'),
  MonthsTicker: require('../ticking/months_ticker'),
  SingleIntervalTicker: require('../ticking/single_interval_ticker'),
  YearsTicker: require('../ticking/years_ticker'),
  BasicTickFormatter: require('../ticking/basic_tick_formatter'),
  LogTickFormatter: require('../ticking/log_tick_formatter'),
  CategoricalTickFormatter: require('../ticking/categorical_tick_formatter'),
  DatetimeTickFormatter: require('../ticking/datetime_tick_formatter'),
  NumeralTickFormatter: require('../ticking/numeral_tick_formatter'),
  PrintfTickFormatter: require('../ticking/printf_tick_formatter'),
  ButtonTool: require('../tool/button_tool'),
  ActionTool: require('../tool/actions/action_tool'),
  PreviewSaveTool: require('../tool/actions/preview_save_tool'),
  ResetTool: require('../tool/actions/reset_tool'),
  HelpTool: require('../tool/actions/help_tool'),
  BoxSelectTool: require('../tool/gestures/box_select_tool'),
  BoxZoomTool: require('../tool/gestures/box_zoom_tool'),
  GestureTool: require('../tool/gestures/gesture_tool'),
  LassoSelectTool: require('../tool/gestures/lasso_select_tool'),
  PanTool: require('../tool/gestures/pan_tool'),
  PolySelectTool: require('../tool/gestures/poly_select_tool'),
  SelectTool: require('../tool/gestures/select_tool'),
  ResizeTool: require('../tool/gestures/resize_tool'),
  TapTool: require('../tool/gestures/tap_tool'),
  WheelZoomTool: require('../tool/gestures/wheel_zoom_tool'),
  CrosshairTool: require('../tool/inspectors/crosshair_tool'),
  HoverTool: require('../tool/inspectors/hover_tool'),
  InspectTool: require('../tool/inspectors/inspect_tool'),
  ar_transforms: [require('../ar/transforms')]
};

collection_overrides = {};

make_collection = function(model) {
  var C;
  C = (function(superClass) {
    extend(C, superClass);

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

    C.prototype.model = model;

    return C;

  })(Collection);
  return new C();
};

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

Collections = function(typename) {
  var mod, mod_cache;
  mod_cache = _get_mod_cache();
  if (collection_overrides[typename]) {
    return collection_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.");
  }
  if (mod.Collection == null) {
    mod.Collection = make_collection(mod.Model);
  }
  return mod.Collection;
};

Collections.register = function(name, collection) {
  return collection_overrides[name] = collection;
};

browserify = {
  modules: arguments[4],
  cache: arguments[5]
};

Collections.register_plugin = function(plugin, locations) {
  var errorFn;
  logger.info("Registering plugin: " + plugin);
  return Collections.register_locations(locations, errorFn = function(name) {
    throw new Error(name + " was already registered, attempted to re-register in " + plugin);
  });
};

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

Collections.register_model = function(name, mod) {
  var _locations, compile, deps, force, impl, mod_cache, mod_name;
  logger.info("Registering model: " + name);
  compile = function(code) {
    var body;
    body = coffee.compile(code, {
      bare: true,
      shiftLine: true
    });
    return new Function("require", "module", "exports", body);
  };
  mod_cache = _get_mod_cache();
  mod_name = "custom/" + (name.toLowerCase());
  impl = mod[0], deps = mod[1];
  delete browserify.cache[mod_name];
  browserify.modules[mod_name] = [compile(impl), deps];
  _locations = {};
  _locations[name] = require(mod_name);
  return Collections.register_locations(_locations, force = true);
};

Collections.register_models = function(specs) {
  var impl, name, results;
  results = [];
  for (name in specs) {
    if (!hasProp.call(specs, name)) continue;
    impl = specs[name];
    results.push(Collections.register_model(name, impl));
  }
  return results;
};

index = {};

module.exports = {
  collection_overrides: collection_overrides,
  locations: locations,
  index: index,
  Collections: Collections,
  Config: Config
};


},{"../ar/transforms":"ar/transforms","../callback/customjs":"callback/customjs","../callback/open_url":"callback/open_url","../mapper/categorical_mapper":"mapper/categorical_mapper","../mapper/linear_color_mapper":"mapper/linear_color_mapper","../mapper/linear_mapper":"mapper/linear_mapper","../mapper/log_mapper":"mapper/log_mapper","../range/data_range1d":"range/data_range1d","../range/factor_range":"range/factor_range","../range/range1d":"range/range1d","../renderer/annotation/box_annotation":"renderer/annotation/box_annotation","../renderer/annotation/legend":"renderer/annotation/legend","../renderer/annotation/span":"renderer/annotation/span","../renderer/annotation/tooltip":"renderer/annotation/tooltip","../renderer/glyph/annular_wedge":"renderer/glyph/annular_wedge","../renderer/glyph/annulus":"renderer/glyph/annulus","../renderer/glyph/arc":"renderer/glyph/arc","../renderer/glyph/bezier":"renderer/glyph/bezier","../renderer/glyph/circle":"renderer/glyph/circle","../renderer/glyph/gear":"renderer/glyph/gear","../renderer/glyph/glyph_renderer":"renderer/glyph/glyph_renderer","../renderer/glyph/image":"renderer/glyph/image","../renderer/glyph/image_rgba":"renderer/glyph/image_rgba","../renderer/glyph/image_url":"renderer/glyph/image_url","../renderer/glyph/line":"renderer/glyph/line","../renderer/glyph/marker/asterisk":"renderer/glyph/marker/asterisk","../renderer/glyph/marker/circle_cross":"renderer/glyph/marker/circle_cross","../renderer/glyph/marker/circle_x":"renderer/glyph/marker/circle_x","../renderer/glyph/marker/cross":"renderer/glyph/marker/cross","../renderer/glyph/marker/diamond":"renderer/glyph/marker/diamond","../renderer/glyph/marker/diamond_cross":"renderer/glyph/marker/diamond_cross","../renderer/glyph/marker/inverted_triangle":"renderer/glyph/marker/inverted_triangle","../renderer/glyph/marker/square":"renderer/glyph/marker/square","../renderer/glyph/marker/square_cross":"renderer/glyph/marker/square_cross","../renderer/glyph/marker/square_x":"renderer/glyph/marker/square_x","../renderer/glyph/marker/triangle":"renderer/glyph/marker/triangle","../renderer/glyph/marker/x":"renderer/glyph/marker/x","../renderer/glyph/multi_line":"renderer/glyph/multi_line","../renderer/glyph/oval":"renderer/glyph/oval","../renderer/glyph/patch":"renderer/glyph/patch","../renderer/glyph/patches":"renderer/glyph/patches","../renderer/glyph/quad":"renderer/glyph/quad","../renderer/glyph/quadratic":"renderer/glyph/quadratic","../renderer/glyph/ray":"renderer/glyph/ray","../renderer/glyph/rect":"renderer/glyph/rect","../renderer/glyph/segment":"renderer/glyph/segment","../renderer/glyph/text":"renderer/glyph/text","../renderer/glyph/wedge":"renderer/glyph/wedge","../renderer/guide/categorical_axis":"renderer/guide/categorical_axis","../renderer/guide/datetime_axis":"renderer/guide/datetime_axis","../renderer/guide/grid":"renderer/guide/grid","../renderer/guide/linear_axis":"renderer/guide/linear_axis","../renderer/guide/log_axis":"renderer/guide/log_axis","../renderer/overlay/box_selection":"renderer/overlay/box_selection","../renderer/overlay/poly_selection":"renderer/overlay/poly_selection","../renderer/tile/bbox_tile_source":"renderer/tile/bbox_tile_source","../renderer/tile/quadkey_tile_source":"renderer/tile/quadkey_tile_source","../renderer/tile/tile_renderer":"renderer/tile/tile_renderer","../renderer/tile/tile_source":"renderer/tile/tile_source","../renderer/tile/tms_tile_source":"renderer/tile/tms_tile_source","../renderer/tile/wmts_tile_source":"renderer/tile/wmts_tile_source","../source/ajax_data_source":"source/ajax_data_source","../source/blaze_data_source":"source/blaze_data_source","../source/column_data_source":"source/column_data_source","../source/server_data_source":"source/server_data_source","../ticking/abstract_ticker":"ticking/abstract_ticker","../ticking/adaptive_ticker":"ticking/adaptive_ticker","../ticking/basic_tick_formatter":"ticking/basic_tick_formatter","../ticking/basic_ticker":"ticking/basic_ticker","../ticking/categorical_tick_formatter":"ticking/categorical_tick_formatter","../ticking/categorical_ticker":"ticking/categorical_ticker","../ticking/composite_ticker":"ticking/composite_ticker","../ticking/datetime_tick_formatter":"ticking/datetime_tick_formatter","../ticking/datetime_ticker":"ticking/datetime_ticker","../ticking/days_ticker":"ticking/days_ticker","../ticking/fixed_ticker":"ticking/fixed_ticker","../ticking/log_tick_formatter":"ticking/log_tick_formatter","../ticking/log_ticker":"ticking/log_ticker","../ticking/months_ticker":"ticking/months_ticker","../ticking/numeral_tick_formatter":"ticking/numeral_tick_formatter","../ticking/printf_tick_formatter":"ticking/printf_tick_formatter","../ticking/single_interval_ticker":"ticking/single_interval_ticker","../ticking/years_ticker":"ticking/years_ticker","../tool/actions/action_tool":"tool/actions/action_tool","../tool/actions/help_tool":"tool/actions/help_tool","../tool/actions/preview_save_tool":"tool/actions/preview_save_tool","../tool/actions/reset_tool":"tool/actions/reset_tool","../tool/button_tool":"tool/button_tool","../tool/gestures/box_select_tool":"tool/gestures/box_select_tool","../tool/gestures/box_zoom_tool":"tool/gestures/box_zoom_tool","../tool/gestures/gesture_tool":"tool/gestures/gesture_tool","../tool/gestures/lasso_select_tool":"tool/gestures/lasso_select_tool","../tool/gestures/pan_tool":"tool/gestures/pan_tool","../tool/gestures/poly_select_tool":"tool/gestures/poly_select_tool","../tool/gestures/resize_tool":"tool/gestures/resize_tool","../tool/gestures/select_tool":"tool/gestures/select_tool","../tool/gestures/tap_tool":"tool/gestures/tap_tool","../tool/gestures/wheel_zoom_tool":"tool/gestures/wheel_zoom_tool","../tool/inspectors/crosshair_tool":"tool/inspectors/crosshair_tool","../tool/inspectors/hover_tool":"tool/inspectors/hover_tool","../tool/inspectors/inspect_tool":"tool/inspectors/inspect_tool","./canvas":"common/canvas","./cartesian_frame":"common/cartesian_frame","./collection":"common/collection","./custom":"common/custom","./geojs_plot":"common/geojs_plot","./gmap_plot":"common/gmap_plot","./grid_plot":"common/grid_plot","./layout_box":"common/layout_box","./logging":"common/logging","./plot":"common/plot","./selection_manager":"common/selection_manager","./selector":"common/selector","./tool_events":"common/tool_events","coffee-script":"coffee-script","underscore":"underscore"}],"common/bbox":[function(require,module,exports){
var empty, extend;

empty = function() {
  return [[Infinity, -Infinity], [Infinity, -Infinity]];
};

extend = function(a, b) {
  a[0][0] = Math.min(a[0][0], b[0][0]);
  a[0][1] = Math.max(a[0][1], b[0][1]);
  a[1][0] = Math.min(a[1][0], b[1][0]);
  a[1][1] = Math.max(a[1][1], b[1][1]);
  return a;
};

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


},{}],"common/build_views":[function(require,module,exports){
var _, build_views, jQueryUIPrefixer;

_ = require("underscore");

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

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

build_views.jQueryUIPrefixer = jQueryUIPrefixer;

module.exports = build_views = build_views;


},{"underscore":"underscore"}],"common/canvas":[function(require,module,exports){
var Canvas, CanvasView, Constraint, ContinuumView, Expression, LayoutBox, Operator, Solver, _, canvas_template, kiwi, 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");

kiwi = require("kiwi");

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

canvas_template = require("./canvas_template");

ContinuumView = require("./continuum_view");

LayoutBox = require("./layout_box");

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

Solver = require("./solver");

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, ref, template_data;
    CanvasView.__super__.initialize.call(this, options);
    template_data = {
      map: this.mget('map')
    };
    html = this.template(template_data);
    this.$el.html(html);
    this.canvas_wrapper = this.$el;
    this.canvas = this.$('canvas.bk-canvas');
    this.canvas_events = this.$('div.bk-canvas-events');
    this.canvas_overlay = this.$('div.bk-canvas-overlays');
    this.map_div = (ref = this.$('div.bk-canvas-map')) != null ? ref : null;
    this.ctx = this.canvas[0].getContext('2d');
    this.ctx.glcanvas = null;
    return logger.debug("CanvasView initialized");
  };

  CanvasView.prototype.render = function(force) {
    var backingStoreRatio, devicePixelRatio, height, ratio, width;
    if (force == null) {
      force = false;
    }
    if (!this.model.new_bounds && !force) {
      return;
    }
    if (this.mget('use_hidpi')) {
      devicePixelRatio = window.devicePixelRatio || 1;
      backingStoreRatio = this.ctx.webkitBackingStorePixelRatio || this.ctx.mozBackingStorePixelRatio || this.ctx.msBackingStorePixelRatio || this.ctx.oBackingStorePixelRatio || this.ctx.backingStorePixelRatio || 1;
      ratio = devicePixelRatio / backingStoreRatio;
    } else {
      ratio = 1;
    }
    width = this.mget('width');
    height = this.mget('height');
    this.$el.attr('style', "z-index: 50; width:" + width + "px; height:" + height + "px");
    this.canvas.attr('style', "width:" + width + "px;height:" + height + "px");
    this.canvas.attr('width', width * ratio).attr('height', height * ratio);
    this.$el.attr("width", width).attr('height', height);
    this.canvas_events.attr('style', "z-index:100; position:absolute; top:0; left:0; width:" + width + "px; height:" + height + "px;");
    this.canvas_overlay.attr('style', "z-index:75; position:absolute; top:0; left:0; width:" + width + "px; height:" + height + "px;");
    this.ctx.scale(ratio, ratio);
    this.ctx.translate(0.5, 0.5);
    this._fixup_line_dash(this.ctx);
    this._fixup_line_dash_offset(this.ctx);
    this._fixup_image_smoothing(this.ctx);
    this._fixup_measure_text(this.ctx);
    return this.model.new_bounds = false;
  };

  CanvasView.prototype._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;
      };
    }
  };

  CanvasView.prototype._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;
    };
  };

  CanvasView.prototype._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;
    };
  };

  CanvasView.prototype._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;
      };
    }
  };

  return CanvasView;

})(ContinuumView);

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.prototype.initialize = function(attr, options) {
    var solver;
    solver = new Solver();
    this.set('solver', solver);
    Canvas.__super__.initialize.call(this, attr, options);
    this.new_bounds = true;
    solver.add_constraint(new Constraint(new Expression(this._left), Operator.Eq));
    solver.add_constraint(new Constraint(new Expression(this._bottom), Operator.Eq));
    this._set_dims([this.get('canvas_width'), this.get('canvas_height')]);
    return logger.debug("Canvas initialized");
  };

  Canvas.prototype.vx_to_sx = function(x) {
    return x;
  };

  Canvas.prototype.vy_to_sy = function(y) {
    return this.get('height') - (y + 1);
  };

  Canvas.prototype.v_vx_to_sx = function(xx) {
    var i, idx, len, x;
    for (idx = i = 0, len = xx.length; i < len; idx = ++i) {
      x = xx[idx];
      xx[idx] = x;
    }
    return xx;
  };

  Canvas.prototype.v_vy_to_sy = function(yy) {
    var canvas_height, i, idx, len, y;
    canvas_height = this.get('height');
    for (idx = i = 0, len = yy.length; i < len; idx = ++i) {
      y = yy[idx];
      yy[idx] = canvas_height - (y + 1);
    }
    return yy;
  };

  Canvas.prototype.sx_to_vx = function(x) {
    return x;
  };

  Canvas.prototype.sy_to_vy = function(y) {
    return this.get('height') - (y + 1);
  };

  Canvas.prototype.v_sx_to_vx = function(xx) {
    var i, idx, len, x;
    for (idx = i = 0, len = xx.length; i < len; idx = ++i) {
      x = xx[idx];
      xx[idx] = x;
    }
    return xx;
  };

  Canvas.prototype.v_sy_to_vy = function(yy) {
    var canvas_height, i, idx, len, y;
    canvas_height = this.get('height');
    for (idx = i = 0, len = yy.length; i < len; idx = ++i) {
      y = yy[idx];
      yy[idx] = canvas_height - (y + 1);
    }
    return yy;
  };

  Canvas.prototype._set_width = function(width, update) {
    if (update == null) {
      update = true;
    }
    if (this._width_constraint != null) {
      this.solver.remove_constraint(this._width_constraint);
    }
    this._width_constraint = new Constraint(new Expression(this._width, -width), Operator.Eq);
    this.solver.add_constraint(this._width_constraint);
    if (update) {
      this.solver.update_variables();
    }
    return this.new_bounds = true;
  };

  Canvas.prototype._set_height = function(height, update) {
    if (update == null) {
      update = true;
    }
    if (this._height_constraint != null) {
      this.solver.remove_constraint(this._height_constraint);
    }
    this._height_constraint = new Constraint(new Expression(this._height, -height), Operator.Eq);
    this.solver.add_constraint(this._height_constraint);
    if (update) {
      this.solver.update_variables();
    }
    return this.new_bounds = true;
  };

  Canvas.prototype._set_dims = function(dims, trigger) {
    if (trigger == null) {
      trigger = true;
    }
    this._set_width(dims[0], false);
    this._set_height(dims[1], false);
    return this.solver.update_variables(trigger);
  };

  Canvas.prototype.defaults = function() {
    return _.extend({}, Canvas.__super__.defaults.call(this), {
      width: 300,
      height: 300,
      map: false,
      mousedown_callbacks: [],
      mousemove_callbacks: [],
      use_hidpi: true
    });
  };

  return Canvas;

})(LayoutBox.Model);

module.exports = {
  Model: Canvas
};


},{"./canvas_template":"common/canvas_template","./continuum_view":"common/continuum_view","./layout_box":"common/layout_box","./logging":"common/logging","./solver":"common/solver","kiwi":"kiwi","underscore":"underscore"}],"common/canvas_template":[function(require,module,exports){
module.exports = function(__obj) {
  if (!__obj) __obj = {};
  var __out = [], __capture = function(callback) {
    var out = __out, result;
    __out = [];
    callback.call(this);
    result = __out.join('');
    __out = out;
    return __safe(result);
  }, __sanitize = function(value) {
    if (value && value.ecoSafe) {
      return value;
    } else if (typeof value !== 'undefined' && value != null) {
      return __escape(value);
    } else {
      return '';
    }
  }, __safe, __objSafe = __obj.safe, __escape = __obj.escape;
  __safe = __obj.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;
    }
  };
  if (!__escape) {
    __escape = __obj.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);
  __obj.safe = __objSafe, __obj.escape = __escape;
  return __out.join('');
}
},{}],"common/cartesian_frame":[function(require,module,exports){
var CartesianFrame, CategoricalMapper, GridMapper, LayoutBox, LinearMapper, LogMapper, _, logging,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

LayoutBox = require("./layout_box");

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

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

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

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

GridMapper = require("../mapper/grid_mapper");

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.register_property('x_ranges', function() {
      return this._get_ranges('x');
    }, true);
    this.add_dependencies('x_ranges', this, ['x_range', 'extra_x_ranges']);
    this.register_property('y_ranges', function() {
      return this._get_ranges('y');
    }, true);
    this.add_dependencies('y_ranges', this, ['y_range', 'extra_y_ranges']);
    this.register_property('x_mappers', function() {
      return this._get_mappers('x', this.get('x_ranges'), this.get('h_range'));
    }, true);
    this.add_dependencies('x_ranges', this, ['x_ranges', 'h_range']);
    this.register_property('y_mappers', function() {
      return this._get_mappers('y', this.get('y_ranges'), this.get('v_range'));
    }, true);
    this.add_dependencies('y_ranges', this, ['y_ranges', 'v_range']);
    this.register_property('mapper', function() {
      return new GridMapper.Model({
        domain_mapper: this.get('x_mapper'),
        codomain_mapper: this.get('y_mapper')
      });
    }, true);
    this.add_dependencies('mapper', this, ['x_mapper', 'y_mapper']);
    return this.listenTo(this.solver, 'layout_update', this._update_mappers);
  };

  CartesianFrame.prototype.map_to_screen = function(x, y, canvas, x_name, y_name) {
    var sx, sy, vx, vy;
    if (x_name == null) {
      x_name = 'default';
    }
    if (y_name == null) {
      y_name = 'default';
    }
    vx = this.get('x_mappers')[x_name].v_map_to_target(x);
    sx = canvas.v_vx_to_sx(vx);
    vy = this.get('y_mappers')[y_name].v_map_to_target(y);
    sy = canvas.v_vy_to_sy(vy);
    return [sx, sy];
  };

  CartesianFrame.prototype._get_ranges = function(dim) {
    var extra_ranges, name, range, ranges;
    ranges = {};
    ranges['default'] = this.get(dim + "_range");
    extra_ranges = this.get("extra_" + dim + "_ranges");
    if (extra_ranges != null) {
      for (name in extra_ranges) {
        range = extra_ranges[name];
        ranges[name] = this.resolve_ref(range);
      }
    }
    return ranges;
  };

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

  CartesianFrame.prototype._update_mappers = function() {
    var mapper, name, ref, ref1, results;
    ref = this.get('x_mappers');
    for (name in ref) {
      mapper = ref[name];
      mapper.set('target_range', this.get('h_range'));
    }
    ref1 = this.get('y_mappers');
    results = [];
    for (name in ref1) {
      mapper = ref1[name];
      results.push(mapper.set('target_range', this.get('v_range')));
    }
    return results;
  };

  CartesianFrame.prototype.defaults = function() {
    return _.extend({}, CartesianFrame.__super__.defaults.call(this), {
      extra_x_ranges: {},
      extra_y_ranges: {}
    });
  };

  return CartesianFrame;

})(LayoutBox.Model);

module.exports = {
  Model: CartesianFrame
};


},{"../mapper/categorical_mapper":"mapper/categorical_mapper","../mapper/grid_mapper":"mapper/grid_mapper","../mapper/linear_mapper":"mapper/linear_mapper","../mapper/log_mapper":"mapper/log_mapper","./layout_box":"common/layout_box","./logging":"common/logging","underscore":"underscore"}],"common/client":[function(require,module,exports){
var ClientConnection, ClientSession, DEFAULT_SERVER_WEBSOCKET_URL, DEFAULT_SESSION_ID, Document, HasProperties, Message, ModelChangedEvent, Promise, RootAddedEvent, RootRemovedEvent, _, logger, message_handlers, pull_session, ref;

_ = require("underscore");

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

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

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

HasProperties = require("./has_properties");

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

DEFAULT_SESSION_ID = "default";

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

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

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

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

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

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

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

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

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

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

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

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

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

  return Message;

})();

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

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

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

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

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

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

  ClientConnection.prototype._schedule_reconnect = function(milliseconds) {
    var retry;
    retry = (function(_this) {
      return function() {
        if (true || _this.closed_permanently) {
          if (!_this.closed_permanently) {
            logger.info("Bokeh client " + _this._number + " never reconnects for now; connection to server lost");
          }
        } else {
          logger.debug("Attempting to reconnect websocket " + _this._number);
          return _this.connect();
        }
      };
    })(this);
    return setTimeout(retry, milliseconds);
  };

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

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

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

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

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

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

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

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

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

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

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

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

  return ClientConnection;

})();

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

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

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

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

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

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

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

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

  return ClientSession;

})();

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

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


},{"./document":"common/document","./has_properties":"common/has_properties","./logging":"common/logging","es6-promise":"es6-promise","underscore":"underscore"}],"common/collection":[function(require,module,exports){
var Backbone, Collection,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

Backbone = require("backbone");

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

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

  return Collection;

})(Backbone.Collection);

module.exports = Collection;


},{"backbone":"backbone"}],"common/color":[function(require,module,exports){
var _color_dict, _component2hex, color2hex, color2rgba;

_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 (_color_dict[color] != null) {
    return _color_dict[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);
};

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

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


},{}],"common/continuum_view":[function(require,module,exports){
var Backbone, ContinuumView, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

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

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

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

  ContinuumView.prototype.bind_bokeh_events = function() {
    return 'pass';
  };

  ContinuumView.prototype.delegateEvents = function(events) {
    return ContinuumView.__super__.delegateEvents.call(this, events);
  };

  ContinuumView.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 ContinuumView.__super__.remove.call(this);
  };

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

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

  ContinuumView.prototype.render_end = function() {
    return "pass";
  };

  return ContinuumView;

})(Backbone.View);

module.exports = ContinuumView;


},{"backbone":"backbone","underscore":"underscore"}],"common/custom":[function(require,module,exports){
var _, monkey_patch;

_ = require("underscore");

monkey_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 = {
  monkey_patch: monkey_patch
};


},{"underscore":"underscore"}],"common/document":[function(require,module,exports){
var Collections, DEFAULT_TITLE, Document, DocumentChangedEvent, HasProperties, ModelChangedEvent, RootAddedEvent, RootRemovedEvent, TitleChangedEvent, _, 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,
  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");

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

HasProperties = require("./has_properties");

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

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

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

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

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

  return RootRemovedEvent;

})(DocumentChangedEvent);

DEFAULT_TITLE = "Bokeh Application";

Document = (function() {
  function Document() {
    this._title = DEFAULT_TITLE;
    this._roots = [];
    this._all_models = {};
    this._all_model_counts = {};
    this._callbacks = [];
  }

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

  Document.prototype._destructively_move = function(dest_doc) {
    var r;
    dest_doc.clear();
    while (len(this._roots) > 0) {
      r = this._roots[0];
      this.remove_root(r);
      dest_doc.add_root(r);
    }
    return dest_doc.set_title(this._title);
  };

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

  Document.prototype.add_root = function(model) {
    if (indexOf.call(this._roots, model) >= 0) {
      return;
    }
    this._roots.push(model);
    model.attach_document(this);
    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;
    } else {
      this._roots.splice(i, 1);
    }
    model.detach_document();
    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.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, len1, ref1, results;
    ref1 = this._callbacks;
    results = [];
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      cb = ref1[j];
      results.push(cb(event));
    }
    return results;
  };

  Document.prototype._notify_change = function(model, attr, old, new_) {
    return this._trigger_on_change(new ModelChangedEvent(this, model, attr, old, new_));
  };

  Document.prototype._notify_attach = function(model) {
    if (!model.serializable_in_document()) {
      console.log("Attempted to attach nonserializable to document ", model);
      throw new Error("Should not attach nonserializable model " + model.constructor.name + " to document");
    }
    if (model.id in this._all_model_counts) {
      this._all_model_counts[model.id] = this._all_model_counts[model.id] + 1;
    } else {
      this._all_model_counts[model.id] = 1;
    }
    return this._all_models[model.id] = model;
  };

  Document.prototype._notify_detach = function(model) {
    var attach_count;
    this._all_model_counts[model.id] -= 1;
    attach_count = this._all_model_counts[model.id];
    if (attach_count === 0) {
      delete this._all_models[model.id];
      delete this._all_model_counts[model.id];
    }
    return attach_count;
  };

  Document._references_json = function(references) {
    var j, len1, r, ref, references_json;
    references_json = [];
    for (j = 0, len1 = references.length; j < len1; j++) {
      r = references[j];
      if (!r.serializable_in_document()) {
        console.log("nonserializable value in references ", r);
        throw new Error("references should never contain nonserializable value");
      }
      ref = r.ref();
      ref['attributes'] = r.attributes_as_json();
      delete ref['attributes']['id'];
      references_json.push(ref);
    }
    return references_json;
  };

  Document._instantiate_object = function(obj_id, obj_type, obj_attrs) {
    var coll, full_attrs;
    full_attrs = _.extend({}, obj_attrs, {
      id: obj_id
    });
    coll = Collections(obj_type);
    if (coll == null) {
      throw new Error("unknown model type " + obj_type + " for " + obj_id);
    }
    return new coll.model(full_attrs, {
      'silent': true,
      'defer_initialization': true
    });
  };

  Document._instantiate_references_json = function(references_json, existing_models) {
    var instance, j, len1, obj, obj_attrs, obj_id, obj_type, references;
    references = {};
    for (j = 0, len1 = references_json.length; j < len1; j++) {
      obj = references_json[j];
      obj_id = obj['id'];
      obj_type = obj['type'];
      if (indexOf.call(obj, 'subtype') >= 0) {
        obj_type = obj['subtype'];
      }
      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);
      }
      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 (HasProperties._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, len1, results, v;
      results = [];
      for (j = 0, len1 = array.length; j < len1; 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, len1, obj, obj_attrs, obj_id, to_update, was_new;
    to_update = {};
    for (j = 0, len1 = references_json.length; j < len1; 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, len2, ref1, results, results1, same_as_v;
        if (v instanceof HasProperties) {
          if (!(v.id in already_started) && v.id in items) {
            already_started[v.id] = true;
            ref1 = items[v.id], same_as_v = ref1[0], attrs = ref1[1], was_new = ref1[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, len2 = v.length; l < len2; 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) {
      return instance.set(attrs);
    });
    return foreach_depth_first(to_update, function(instance, attrs, was_new) {
      if (was_new) {
        return instance.initialize(attrs);
      }
    });
  };

  Document._event_for_attribute_change = function(changed_obj, key, new_value, doc, value_refs) {
    var changed_model, event;
    changed_model = doc.get_model_by_id(changed_obj.id);
    if (!changed_model.attribute_is_serializable(key)) {
      return null;
    }
    event = {
      'kind': 'ModelChanged',
      'model': {
        id: changed_obj.id,
        type: changed_obj.type
      },
      'attr': key,
      'new': new_value
    };
    HasProperties._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, len1, len2, len3, m, 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, len1 = removed.length; j < len1; j++) {
      key = removed[j];
      events.push(Document._event_for_attribute_change(from_obj, key, null, to_doc, value_refs));
    }
    for (l = 0, len2 = added.length; l < len2; 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 (m = 0, len3 = shared.length; m < len3; m++) {
      key = shared[m];
      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, j, l, len1, len2, model, r, ref1, ref2, ref3, refs, to_json, to_references, to_root_ids, to_roots, update_model_events, value_refs;
    to_json = to_doc.to_json();
    refs = function(json) {
      var j, len1, obj, ref1, result;
      result = {};
      ref1 = json['roots']['references'];
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        obj = ref1[j];
        result[obj.id] = obj;
      }
      return result;
    };
    from_references = refs(from_json);
    from_roots = {};
    from_root_ids = [];
    ref1 = from_json['roots']['root_ids'];
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      r = ref1[j];
      from_roots[r] = from_references[r];
      from_root_ids.push(r);
    }
    to_references = refs(to_json);
    to_roots = {};
    to_root_ids = [];
    ref2 = to_json['roots']['root_ids'];
    for (l = 0, len2 = ref2.length; l < len2; l++) {
      r = ref2[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) {
      throw new Error("Not implemented: computing add/remove of document roots");
    }
    value_refs = {};
    events = [];
    ref3 = to_doc._all_models;
    for (id in ref3) {
      model = ref3[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))
    };
  };

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

  Document.prototype.to_json = function() {
    var j, k, len1, r, ref1, root_ids, root_references, v;
    root_ids = [];
    ref1 = this._roots;
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      r = ref1[j];
      root_ids.push(r.id);
    }
    root_references = (function() {
      var ref2, results;
      ref2 = this._all_models;
      results = [];
      for (k in ref2) {
        v = ref2[k];
        results.push(v);
      }
      return results;
    }).call(this);
    return {
      'title': this._title,
      'roots': {
        'root_ids': root_ids,
        'references': Document._references_json(root_references)
      }
    };
  };

  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, len1, r, references, references_json, root_ids, roots_json;
    if (typeof json !== 'object') {
      throw new Error("JSON object has wrong type " + (typeof json));
    }
    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, len1 = root_ids.length; j < len1; 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, id, j, json_event, json_events, len1, references, value, value_json, value_refs;
    references = {};
    json_events = [];
    for (j = 0, len1 = events.length; j < len1; 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");
      }
      if (event instanceof ModelChangedEvent) {
        if (event.attr === 'id') {
          console.log("'id' field is immutable and should never be in a ModelChangedEvent ", event);
          throw new Error("'id' field should never change, whatever code just set it is wrong");
        }
        value = event.new_;
        value_json = HasProperties._value_to_json('new_', value, event.model);
        value_refs = {};
        HasProperties._value_record_references(value, value_refs, true);
        if (event.model.id in value_refs && event.model !== value) {
          delete value_refs[event.model.id];
        }
        for (id in value_refs) {
          references[id] = value_refs[id];
        }
        json_event = {
          'kind': 'ModelChanged',
          'model': event.model.ref(),
          'attr': event.attr,
          'new': value_json
        };
        json_events.push(json_event);
      } else if (event instanceof RootAddedEvent) {
        HasProperties._value_record_references(event.model, references, true);
        json_event = {
          'kind': 'RootAdded',
          'model': event.model.ref()
        };
        json_events.push(json_event);
      } else if (event instanceof RootRemovedEvent) {
        json_event = {
          'kind': 'RootRemoved',
          'model': event.model.ref()
        };
        json_events.push(json_event);
      } else if (event instanceof TitleChangedEvent) {
        json_event = {
          'kind': 'TitleChanged',
          'title': event.title
        };
        json_events.push(json_event);
      }
    }
    return {
      '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, event_json, events_json, id, j, l, len1, len2, model_id, new_references, obj1, old_references, patched_id, patched_obj, references, references_json, results, 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, len1 = events_json.length; j < len1; 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 {
          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, len2 = events_json.length; l < len2; l++) {
      event_json = events_json[l];
      if (event_json['kind'] === 'ModelChanged') {
        patched_id = event_json['model']['id'];
        if (!(patched_id in this._all_models)) {
          throw new Error("Cannot apply patch to " + patched_id + " which is not in the document");
        }
        patched_obj = this._all_models[patched_id];
        attr = event_json['attr'];
        value = Document._resolve_refs(event_json['new'], old_references, new_references);
        results.push(patched_obj.set((
          obj1 = {},
          obj1["" + attr] = value,
          obj1
        )));
      } else if (event_json['kind'] === 'RootAdded') {
        root_id = event_json['model']['id'];
        root_obj = references[root_id];
        results.push(this.add_root(root_obj));
      } else if (event_json['kind'] === 'RootRemoved') {
        root_id = event_json['model']['id'];
        root_obj = references[root_id];
        results.push(this.remove_root(root_obj));
      } else if (event_json['kind'] === 'TitleChanged') {
        results.push(this.set_title(event_json['title']));
      } else {
        throw new Error("Unknown patch event " + JSON.stringify(event_json));
      }
    }
    return results;
  };

  return Document;

})();

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


},{"./base":"common/base","./has_properties":"common/has_properties","./logging":"common/logging","underscore":"underscore"}],"common/embed":[function(require,module,exports){
var $, Backbone, Document, HasProperties, Promise, RootAddedEvent, RootRemovedEvent, TitleChangedEvent, _, _create_view, _get_session, _render_document_to_element, _sessions, _websocket_url, add_document_from_session, add_document_static, add_model_from_session, add_model_static, base, embed_items, fill_render_item_from_script_tag, inject_css, logger, pull_session, ref, ref1, set_log_level, set_websocket_url;

$ = require("jquery");

_ = require("underscore");

Backbone = require("backbone");

base = require("./base");

HasProperties = require("./has_properties");

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

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

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

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

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

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

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

_websocket_url = null;

set_websocket_url = function(url) {
  return _websocket_url = url;
};

_sessions = {};

_get_session = function(session_id) {
  if (_websocket_url === null) {
    throw new Error("set_websocket_url was not called");
  }
  if (!(session_id in _sessions)) {
    _sessions[session_id] = pull_session(_websocket_url, session_id);
  }
  return _sessions[session_id];
};

add_document_from_session = function(element, session_id, use_for_title) {
  var promise;
  promise = _get_session(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, model_id, session_id) {
  var promise;
  promise = _get_session(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);
};

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

embed_items = function(docs_json, render_items, websocket_url) {
  var container, docid, docs, elem, element_id, i, item, len, promise, results, use_for_title;
  if (websocket_url != null) {
    set_websocket_url(websocket_url);
  }
  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];
    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-container'
      });
      elem.replaceWith(container);
      elem = container;
    }
    use_for_title = (item.use_for_title != null) && item.use_for_title;
    promise = null;
    if (item.modelid != null) {
      if (item.docid != null) {
        add_model_static(elem, item.modelid, docs[item.docid]);
      } else if (item.sessionid != null) {
        promise = add_model_from_session(elem, 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, 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,
  inject_css: inject_css
};


},{"./base":"common/base","./client":"common/client","./document":"common/document","./has_properties":"common/has_properties","./logging":"common/logging","backbone":"backbone","es6-promise":"es6-promise","jquery":"jquery","underscore":"underscore"}],"common/geojs_plot":[function(require,module,exports){
var GeoJSPlot, GeoJSPlotView, Plot, Solver, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

Solver = require("./solver");

Plot = require("./plot");

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

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

  GeoJSPlotView.prototype.initialize = function(options) {
    GeoJSPlotView.__super__.initialize.call(this, _.defaults(options, this.default_options));
    return this.zoom_count = null;
  };

  GeoJSPlotView.prototype.bind_bokeh_events = function() {
    var build_map, height, left, top, width;
    GeoJSPlotView.__super__.bind_bokeh_events.call(this);
    width = this.frame.get('width');
    height = this.frame.get('height');
    left = this.canvas.vx_to_sx(this.frame.get('left'));
    top = this.canvas.vy_to_sy(this.frame.get('top'));
    this.canvas_view.map_div.attr("style", "top: " + top + "px; left: " + left + "px; position: absolute");
    this.canvas_view.map_div.attr('style', "width:" + width + "px;");
    this.canvas_view.map_div.attr('style', "height:" + height + "px;");
    this.canvas_view.map_div.width(width + "px").height(height + "px");
    this.initial_zoom = this.mget('map_options').zoom;
    build_map = (function(_this) {
      return function() {
        var map_options, mo;
        mo = _this.mget('map_options');
        map_options = {
          center: [mo.lat, mo.lng],
          zoom: mo.zoom,
          node: _this.canvas_view.map_div[0]
        };
        _this.map = geo.map(map_options);
        return _this.map.createLayer('osm');
      };
    })(this);
    return $.getScript("http://opengeoscience.github.io/geojs/lib/gl-matrix.js", function() {
      return $.getScript("http://opengeoscience.github.io/geojs/lib/d3.v3.min.js", function() {
        return $.getScript("http://opengeoscience.github.io/geojs/lib/proj4.js", function() {
          return $.getScript("http://opengeoscience.github.io/geojs/lib/vgl.js", function() {
            return $.getScript("http://opengeoscience.github.io/geojs/lib/geo.js", function() {
              return build_map();
            });
          });
        });
      });
    });
  };

  GeoJSPlotView.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");
  };

  GeoJSPlotView.prototype._paint_empty = function(ctx, frame_box) {
    var ih, iw, left, oh, ow, top;
    ow = this.canvas.get('width');
    oh = this.canvas.get('height');
    left = frame_box[0], top = frame_box[1], iw = frame_box[2], ih = frame_box[3];
    ctx.clearRect(0, 0, ow, oh);
    ctx.beginPath();
    ctx.moveTo(0, 0);
    ctx.lineTo(0, oh);
    ctx.lineTo(ow, oh);
    ctx.lineTo(ow, 0);
    ctx.lineTo(0, 0);
    ctx.moveTo(left, top);
    ctx.lineTo(left + iw, top);
    ctx.lineTo(left + iw, top + ih);
    ctx.lineTo(left, top + ih);
    ctx.lineTo(left, top);
    ctx.closePath();
    ctx.fillStyle = this.mget('border_fill');
    return ctx.fill();
  };

  return GeoJSPlotView;

})(Plot.View);

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

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

  GeoJSPlot.prototype.type = 'GeoJSPlot';

  GeoJSPlot.prototype.default_view = GeoJSPlotView;

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

  GeoJSPlot.prototype.parent_properties = ['border_fill', 'min_border', 'min_border_top', 'min_border_bottom', 'min_border_left', 'min_border_right'];

  GeoJSPlot.prototype.defaults = function() {
    return _.extend({}, GeoJSPlot.__super__.defaults.call(this), {
      title: 'GeoJSPlot'
    });
  };

  GeoJSPlot.prototype.display_defaults = function() {
    return _.extend({}, GeoJSPlot.__super__.display_defaults.call(this), {
      border_fill: "#fff"
    });
  };

  return GeoJSPlot;

})(Plot.Model);

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


},{"./plot":"common/plot","./solver":"common/solver","underscore":"underscore"}],"common/gmap_plot":[function(require,module,exports){
var GMapPlot, GMapPlotView, Plot, Solver, _, 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");

Solver = require("./solver");

Plot = require("./plot");

proj4 = require("proj4");

toProjection = proj4.defs('GOOGLE');

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

  function GMapPlotView() {
    this.setRanges = bind(this.setRanges, this);
    this.getProjectedBounds = bind(this.getProjectedBounds, this);
    this.getLatLngBounds = bind(this.getLatLngBounds, this);
    return GMapPlotView.__super__.constructor.apply(this, arguments);
  }

  GMapPlotView.prototype.initialize = function(options) {
    GMapPlotView.__super__.initialize.call(this, _.defaults(options, this.default_options));
    return this.zoom_count = 0;
  };

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

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

  GMapPlotView.prototype.setRanges = function() {
    var proj_xend, proj_xstart, proj_yend, proj_ystart, ref;
    ref = this.getProjectedBounds(), proj_xstart = ref[0], proj_xend = ref[1], proj_ystart = ref[2], proj_yend = ref[3];
    this.x_range.set({
      start: proj_xstart,
      end: proj_xend,
      silent: true
    });
    return this.y_range.set({
      start: proj_ystart,
      end: proj_yend,
      silent: true
    });
  };

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

  GMapPlotView.prototype.bind_bokeh_events = function() {
    var build_map, height, left, script, top, width;
    GMapPlotView.__super__.bind_bokeh_events.call(this);
    width = this.frame.get('width');
    height = this.frame.get('height');
    left = this.canvas.vx_to_sx(this.frame.get('left'));
    top = this.canvas.vy_to_sy(this.frame.get('top'));
    this.canvas_view.map_div.attr("style", "top: " + top + "px; left: " + left + "px; position: absolute");
    this.canvas_view.map_div.attr('style', "width:" + width + "px;");
    this.canvas_view.map_div.attr('style', "height:" + height + "px;");
    this.canvas_view.map_div.width(width + "px").height(height + "px");
    this.initial_zoom = this.mget('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.mget('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?v=3&callback=_bokeh_gmap_callback";
      return document.body.appendChild(script);
    }
  };

  GMapPlotView.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");
  };

  GMapPlotView.prototype._paint_empty = function(ctx, frame_box) {
    var ih, iw, left, oh, ow, top;
    ow = this.canvas.get('width');
    oh = this.canvas.get('height');
    left = frame_box[0], top = frame_box[1], iw = frame_box[2], ih = frame_box[3];
    ctx.clearRect(0, 0, ow, oh);
    ctx.beginPath();
    ctx.moveTo(0, 0);
    ctx.lineTo(0, oh);
    ctx.lineTo(ow, oh);
    ctx.lineTo(ow, 0);
    ctx.lineTo(0, 0);
    ctx.moveTo(left, top);
    ctx.lineTo(left + iw, top);
    ctx.lineTo(left + iw, top + ih);
    ctx.lineTo(left, top + ih);
    ctx.lineTo(left, top);
    ctx.closePath();
    ctx.fillStyle = this.mget('border_fill');
    return ctx.fill();
  };

  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(attrs, options) {
    this.use_map = true;
    return GMapPlot.__super__.initialize.call(this, attrs, options);
  };

  GMapPlot.prototype.parent_properties = ['border_fill', 'min_border', 'min_border_top', 'min_border_bottom', 'min_border_left', 'min_border_right'];

  GMapPlot.prototype.defaults = function() {
    return _.extend({}, GMapPlot.__super__.defaults.call(this), {
      title: 'GMapPlot'
    });
  };

  GMapPlot.prototype.display_defaults = function() {
    return _.extend({}, GMapPlot.__super__.display_defaults.call(this), {
      border_fill: "#fff"
    });
  };

  return GMapPlot;

})(Plot.Model);

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


},{"./plot":"common/plot","./solver":"common/solver","proj4":"proj4","underscore":"underscore"}],"common/grid_plot":[function(require,module,exports){
var $, Backbone, ContinuumView, GridPlot, GridPlotView, GridToolManager, GridViewState, HasProperties, ToolManager, ToolProxy, _, build_views, logger, plot_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("jquery");

_ = require("underscore");

Backbone = require("backbone");

build_views = require("./build_views");

ContinuumView = require("./continuum_view");

HasProperties = require("./has_properties");

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

ToolManager = require("./tool_manager");

plot_template = require("./plot_template");

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"]);
    this.listenTo(this, 'change:active', this.active);
    return null;
  };

  ToolProxy.prototype["do"] = function() {
    var i, len, ref, tool;
    ref = this.attributes.tools;
    for (i = 0, len = ref.length; i < len; i++) {
      tool = ref[i];
      tool.trigger('do');
    }
    return null;
  };

  ToolProxy.prototype.active = function() {
    var i, len, ref, tool;
    ref = this.attributes.tools;
    for (i = 0, len = ref.length; i < len; i++) {
      tool = ref[i];
      tool.set('active', this.attributes.active);
    }
    return null;
  };

  ToolProxy.prototype.attrs_and_props = function() {
    return this.attributes.tools[0].attrs_and_props();
  };

  ToolProxy.prototype.get = function(attr) {
    return this.attributes.tools[0].get(attr);
  };

  ToolProxy.prototype.set = function(attr, value) {
    var i, len, ref, tool;
    ToolProxy.__super__.set.call(this, attr, value);
    ref = this.attributes.tools;
    for (i = 0, len = ref.length; i < len; i++) {
      tool = ref[i];
      tool.set(attr, value);
    }
    return null;
  };

  return ToolProxy;

})(Backbone.Model);

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

  function GridToolManager() {
    this._active_change = bind(this._active_change, this);
    return GridToolManager.__super__.constructor.apply(this, arguments);
  }

  GridToolManager.prototype._init_tools = function() {
    var actions, et, gestures, i, info, inspectors, j, k, l, len, len1, len2, len3, proxy, ref, ref1, ref2, ref3, ref4, ref5, ref6, results, tm, tmp, tool, tools, typ;
    inspectors = {};
    actions = {};
    gestures = {};
    ref = this.get('tool_managers');
    for (i = 0, len = ref.length; i < len; i++) {
      tm = ref[i];
      ref1 = tm.get('gestures');
      for (et in ref1) {
        info = ref1[et];
        if (!(et in gestures)) {
          gestures[et] = {};
        }
        ref2 = info.tools;
        for (j = 0, len1 = ref2.length; j < len1; j++) {
          tool = ref2[j];
          if (!(tool.type in gestures[et])) {
            gestures[et][tool.type] = [];
          }
          gestures[et][tool.type].push(tool);
        }
      }
      ref3 = tm.get('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 = tm.get('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);
      }
    }
    for (et in gestures) {
      ref5 = gestures[et];
      for (typ in ref5) {
        tools = ref5[typ];
        if (tools.length !== this.get('num_plots')) {
          continue;
        }
        proxy = new ToolProxy({
          tools: tools
        });
        this.get('gestures')[et].tools.push(proxy);
        this.listenTo(proxy, 'change:active', _.bind(this._active_change, proxy));
      }
    }
    for (typ in actions) {
      tools = actions[typ];
      if (tools.length !== this.get('num_plots')) {
        continue;
      }
      proxy = new ToolProxy({
        tools: tools
      });
      tmp = this.get('actions');
      tmp.push(proxy);
      this.set('actions', tmp);
    }
    for (typ in inspectors) {
      tools = inspectors[typ];
      if (tools.length !== this.get('num_plots')) {
        continue;
      }
      proxy = new ToolProxy({
        tools: tools
      });
      tmp = this.get('inspectors');
      tmp.push(proxy);
      this.set('inspectors', tmp);
    }
    ref6 = this.get('gestures');
    results = [];
    for (et in ref6) {
      info = ref6[et];
      tools = info.tools;
      if (tools.length === 0) {
        continue;
      }
      info.tools = _.sortBy(tools, function(tool) {
        return tool.get('default_order');
      });
      results.push(info.tools[0].set('active', true));
    }
    return results;
  };

  GridToolManager.prototype._active_change = function(tool) {
    var active, et, gestures, prev;
    et = tool.get('event_type');
    active = tool.get('active');
    if (!active) {
      return null;
    }
    gestures = this.get('gestures');
    prev = gestures[et].active;
    if (prev != null) {
      logger.debug("GridToolManager: deactivating tool: " + prev.type + " (for event type '" + et + "'");
      prev.set('active', false);
    }
    gestures[et].active = tool;
    this.set('gestures', gestures);
    logger.debug("GridToolManager: activating tool: " + tool.type + " (for event type '" + et + "'");
    return null;
  };

  GridToolManager.prototype.defaults = function() {
    return _.extend({}, GridToolManager.__super__.defaults.call(this), {
      tool_manangers: []
    });
  };

  return GridToolManager;

})(ToolManager.Model);

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

  function GridViewState() {
    this.layout_widths = bind(this.layout_widths, this);
    this.layout_heights = bind(this.layout_heights, this);
    this.setup_layout_properties = bind(this.setup_layout_properties, this);
    return GridViewState.__super__.constructor.apply(this, arguments);
  }

  GridViewState.prototype.setup_layout_properties = function() {
    var i, len, ref, results, row, viewstate;
    this.register_property('layout_heights', this.layout_heights, false);
    this.register_property('layout_widths', this.layout_widths, false);
    ref = this.get('viewstates');
    results = [];
    for (i = 0, len = ref.length; i < len; i++) {
      row = ref[i];
      results.push((function() {
        var j, len1, results1;
        results1 = [];
        for (j = 0, len1 = row.length; j < len1; j++) {
          viewstate = row[j];
          this.add_dependencies('layout_heights', viewstate, 'height');
          results1.push(this.add_dependencies('layout_widths', viewstate, 'width'));
        }
        return results1;
      }).call(this));
    }
    return results;
  };

  GridViewState.prototype.initialize = function(attrs, options) {
    var calculateHeight, calculateWidth;
    GridViewState.__super__.initialize.call(this, attrs, options);
    this.setup_layout_properties();
    this.listenTo(this, 'change:viewstates', this.setup_layout_properties);
    calculateHeight = (function(_this) {
      return function() {
        return _.reduce(_this.get("layout_heights"), (function(x, y) {
          return x + y;
        }), 0);
      };
    })(this);
    this.register_property('height', calculateHeight, false);
    this.add_dependencies('height', this, 'layout_heights');
    calculateWidth = (function(_this) {
      return function() {
        return _.reduce(_this.get("layout_widths"), (function(x, y) {
          return x + y;
        }), 0);
      };
    })(this);
    this.register_property('width', calculateWidth, false);
    return this.add_dependencies('width', this, 'layout_widths');
  };

  GridViewState.prototype.position_child_x = function(offset, childsize) {
    return offset;
  };

  GridViewState.prototype.position_child_y = function(offset, childsize) {
    return this.get('height') - offset - childsize;
  };

  GridViewState.prototype.maxdim = function(dim, row) {
    if (row.length === 0) {
      return 0;
    } else {
      return _.max(_.map(row, function(x) {
        if (x != null) {
          return x.get(dim);
        }
        return 0;
      }));
    }
  };

  GridViewState.prototype.layout_heights = function() {
    var row, row_heights;
    row_heights = (function() {
      var i, len, ref, results;
      ref = this.get('viewstates');
      results = [];
      for (i = 0, len = ref.length; i < len; i++) {
        row = ref[i];
        results.push(this.maxdim('height', row));
      }
      return results;
    }).call(this);
    return row_heights;
  };

  GridViewState.prototype.layout_widths = function() {
    var col, col_widths, columns, n, num_cols, row;
    num_cols = this.get('viewstates')[0].length;
    columns = (function() {
      var i, len, ref, results;
      ref = _.range(num_cols);
      results = [];
      for (i = 0, len = ref.length; i < len; i++) {
        n = ref[i];
        results.push((function() {
          var j, len1, ref1, results1;
          ref1 = this.get('viewstates');
          results1 = [];
          for (j = 0, len1 = ref1.length; j < len1; j++) {
            row = ref1[j];
            results1.push(row[n]);
          }
          return results1;
        }).call(this));
      }
      return results;
    }).call(this);
    col_widths = (function() {
      var i, len, results;
      results = [];
      for (i = 0, len = columns.length; i < len; i++) {
        col = columns[i];
        results.push(this.maxdim('width', col));
      }
      return results;
    }).call(this);
    return col_widths;
  };

  GridViewState.prototype.defaults = function() {
    return _.extend({}, GridViewState.__super__.defaults.call(this), {
      viewstates: [[]],
      border_space: 0
    });
  };

  return GridViewState;

})(HasProperties);

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

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

  GridPlotView.prototype.className = "";

  GridPlotView.prototype.template = plot_template;

  GridPlotView.prototype.initialize = function(options) {
    var toolbar_location, toolbar_selector;
    GridPlotView.__super__.initialize.call(this, options);
    this.viewstate = new GridViewState();
    this.child_views = {};
    this.build_children();
    this.bind_bokeh_events();
    this.$el.html(this.template());
    toolbar_location = this.mget('toolbar_location');
    if (toolbar_location != null) {
      toolbar_selector = '.bk-plot-' + toolbar_location;
      logger.debug("attaching toolbar to " + toolbar_selector + " for plot " + this.model.id);
      this.tm_view = new ToolManager.View({
        model: this.mget('tool_manager'),
        el: this.$(toolbar_selector)
      });
    }
    this.render();
    return this;
  };

  GridPlotView.prototype.bind_bokeh_events = function() {
    this.listenTo(this.model, 'change:children', this.build_children);
    this.listenTo(this.model, 'change', this.render);
    this.listenTo(this.viewstate, 'change', this.render);
    return this.listenTo(this.model, 'destroy', this.remove);
  };

  GridPlotView.prototype.build_children = function() {
    var childmodels, i, j, k, l, len, len1, len2, len3, len4, m, plot, ref, ref1, ref2, results, row, viewstates, vsrow;
    childmodels = [];
    ref = this.mget('children');
    for (i = 0, len = ref.length; i < len; i++) {
      row = ref[i];
      for (j = 0, len1 = row.length; j < len1; j++) {
        plot = row[j];
        if (plot == null) {
          continue;
        }
        plot.set('toolbar_location', null);
        childmodels.push(plot);
      }
    }
    build_views(this.child_views, childmodels, {});
    viewstates = [];
    ref1 = this.mget('children');
    for (k = 0, len2 = ref1.length; k < len2; k++) {
      row = ref1[k];
      vsrow = [];
      for (l = 0, len3 = row.length; l < len3; l++) {
        plot = row[l];
        if (plot == null) {
          continue;
        }
        vsrow.push(this.child_views[plot.id].canvas);
      }
      viewstates.push(vsrow);
    }
    this.viewstate.set('viewstates', viewstates);
    ref2 = this.mget('children');
    results = [];
    for (m = 0, len4 = ref2.length; m < len4; m++) {
      row = ref2[m];
      results.push((function() {
        var len5, o, results1;
        results1 = [];
        for (o = 0, len5 = row.length; o < len5; o++) {
          plot = row[o];
          if (plot == null) {
            continue;
          }
          results1.push(this.listenTo(plot.solver, 'layout_update', this.render));
        }
        return results1;
      }).call(this));
    }
    return results;
  };

  GridPlotView.prototype.render = function() {
    var add, cidx, col_widths, div, height, i, j, k, last_plot, len, len1, len2, plot, plot_divs, plot_wrapper, ref, ref1, ridx, row, row_heights, toolbar_location, toolbar_selector, total_height, view, width, x_coords, xpos, y_coords, ypos;
    GridPlotView.__super__.render.call(this);
    ref = _.values(this.child_views);
    for (i = 0, len = ref.length; i < len; i++) {
      view = ref[i];
      view.$el.detach();
    }
    div = $('<div />');
    this.$('.bk-plot-canvas-wrapper').empty();
    this.$('.bk-plot-canvas-wrapper').append(div);
    toolbar_location = this.mget('toolbar_location');
    if (toolbar_location != null) {
      toolbar_selector = '.bk-plot-' + toolbar_location;
      this.tm_view = new ToolManager.View({
        model: this.mget('tool_manager'),
        el: this.$(toolbar_selector)
      });
      this.tm_view.render();
    }
    row_heights = this.viewstate.get('layout_heights');
    col_widths = this.viewstate.get('layout_widths');
    y_coords = [0];
    _.reduceRight(row_heights.slice(1), function(x, y) {
      var val;
      val = x + y;
      y_coords.push(val);
      return val;
    }, 0);
    y_coords.reverse();
    x_coords = [0];
    _.reduce(col_widths.slice(0), function(x, y) {
      var val;
      val = x + y;
      x_coords.push(val);
      return val;
    }, 0);
    plot_divs = [];
    last_plot = null;
    ref1 = this.mget('children');
    for (ridx = j = 0, len1 = ref1.length; j < len1; ridx = ++j) {
      row = ref1[ridx];
      for (cidx = k = 0, len2 = row.length; k < len2; cidx = ++k) {
        plot = row[cidx];
        if (plot == null) {
          continue;
        }
        view = this.child_views[plot.id];
        ypos = this.viewstate.position_child_y(y_coords[ridx], view.canvas.get('height'));
        xpos = this.viewstate.position_child_x(x_coords[cidx], view.canvas.get('width'));
        plot_wrapper = $("<div class='gp_plotwrapper'></div>");
        plot_wrapper.attr('style', "position: absolute; left:" + xpos + "px; top:" + ypos + "px");
        plot_wrapper.append(view.$el);
        div.append(plot_wrapper);
      }
    }
    add = function(a, b) {
      return a + b;
    };
    total_height = _.reduce(row_heights, add, 0);
    height = total_height;
    width = _.reduce(col_widths, add, 0);
    return div.attr('style', "position:relative; height:" + height + "px;width:" + width + "px");
  };

  return GridPlotView;

})(ContinuumView);

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

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

  GridPlot.prototype.type = 'GridPlot';

  GridPlot.prototype.default_view = GridPlotView;

  GridPlot.prototype.initialize = function(attrs, options) {
    GridPlot.__super__.initialize.call(this, attrs, options);
    return this.register_property('tool_manager', function() {
      var children, i, len, plot, ref;
      children = [];
      ref = _.flatten(this.get('children'));
      for (i = 0, len = ref.length; i < len; i++) {
        plot = ref[i];
        if (plot != null) {
          children.push(plot);
        }
      }
      return new GridToolManager({
        tool_managers: (function() {
          var j, len1, results;
          results = [];
          for (j = 0, len1 = children.length; j < len1; j++) {
            plot = children[j];
            results.push(plot.get('tool_manager'));
          }
          return results;
        })(),
        toolbar_location: this.get('toolbar_location'),
        num_plots: children.length
      });
    }, true);
  };

  GridPlot.prototype.defaults = function() {
    return _.extend({}, GridPlot.__super__.defaults.call(this), {
      children: [[]],
      toolbar_location: "left"
    });
  };

  return GridPlot;

})(HasProperties);

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


},{"./build_views":"common/build_views","./continuum_view":"common/continuum_view","./has_properties":"common/has_properties","./logging":"common/logging","./plot_template":"common/plot_template","./tool_manager":"common/tool_manager","backbone":"backbone","jquery":"jquery","underscore":"underscore"}],"common/has_parent":[function(require,module,exports){
var HasParent, HasProperties, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

HasProperties = require("./has_properties");

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

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

  HasParent.prototype.initialize = function(attrs, options) {
    HasParent.__super__.initialize.call(this, attrs, options);
    return this._parent = HasProperties.prototype.get.apply(this, ['parent']);
  };

  HasParent.prototype.nonserializable_attribute_names = function() {
    return HasParent.__super__.nonserializable_attribute_names.call(this).concat(['parent']);
  };

  HasParent.prototype.get = function(attr, resolve_refs) {
    var val;
    if (resolve_refs == null) {
      resolve_refs = true;
    }
    if (!this._display_defaults) {
      this._display_defaults = this.display_defaults();
    }
    if (attr === 'parent') {
      return this._parent;
    }
    val = HasParent.__super__.get.call(this, attr, resolve_refs);
    if (!_.isUndefined(val)) {
      return val;
    }
    if (this._parent && _.indexOf(this._parent.parent_properties, attr) >= 0) {
      val = this._parent.get(attr, resolve_refs);
      if (!_.isUndefined(val)) {
        return val;
      }
    }
    return this._display_defaults[attr];
  };

  HasParent.prototype.display_defaults = function() {
    return {};
  };

  return HasParent;

})(HasProperties);

module.exports = HasParent;


},{"./has_properties":"common/has_properties","underscore":"underscore"}],"common/has_properties":[function(require,module,exports){
var $, Backbone, HasProperties, _, logger,
  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");

Backbone = require("backbone");

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

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

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

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

  HasProperties.prototype.isNew = function() {
    return false;
  };

  HasProperties.prototype.attrs_and_props = function() {
    var data, j, len, prop_name, ref;
    data = _.clone(this.attributes);
    ref = _.keys(this.properties);
    for (j = 0, len = ref.length; j < len; j++) {
      prop_name = ref[j];
      data[prop_name] = this.get(prop_name);
    }
    return data;
  };

  function HasProperties(attributes, options) {
    this.resolve_ref = bind(this.resolve_ref, this);
    this.convert_to_ref = bind(this.convert_to_ref, this);
    var attrs;
    this.document = null;
    attrs = attributes || {};
    if (!options) {
      options = {};
    }
    this.cid = _.uniqueId('c');
    this.attributes = {};
    if (options.collection) {
      this.collection = options.collection;
    }
    if (options.parse) {
      attrs = this.parse(attrs, options) || {};
    }
    attrs = _.defaults({}, attrs, _.result(this, 'defaults'));
    this.set(attrs, options);
    this.changed = {};
    this._base = false;
    this.properties = {};
    this.property_cache = {};
    if (!_.has(attrs, this.idAttribute)) {
      this.id = _.uniqueId(this.type);
      this.attributes[this.idAttribute] = this.id;
    }
    if (!options.defer_initialization) {
      this.initialize.apply(this, arguments);
    }
  }

  HasProperties.prototype.forceTrigger = function(changes) {
    var change, changing, j, len, options;
    if (!_.isArray(changes)) {
      changes = [changes];
    }
    options = {};
    changing = this._changing;
    this._changing = true;
    if (changes.length) {
      this._pending = true;
    }
    for (j = 0, len = changes.length; j < len; j++) {
      change = changes[j];
      this.trigger('change:' + change, this, this.attributes[change], options);
    }
    if (changing) {
      return this;
    }
    while (this._pending) {
      this._pending = false;
      this.trigger('change', this, options);
    }
    this._pending = false;
    this._changing = false;
    return this;
  };

  HasProperties.prototype.set_obj = function(key, value, options) {
    var attrs, 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];
      attrs[key] = this.convert_to_ref(val);
    }
    return this.set(attrs, options);
  };

  HasProperties.prototype.set = function(key, value, options) {
    var attrs, j, len, old, resolve_refs, results, toremove, val;
    if (_.isObject(key) || key === null) {
      attrs = key;
      options = value;
    } else {
      attrs = {};
      attrs[key] = value;
    }
    toremove = [];
    for (key in attrs) {
      if (!hasProp.call(attrs, key)) continue;
      val = attrs[key];
      if (_.has(this, 'properties') && _.has(this.properties, key) && this.properties[key]['setter']) {
        this.properties[key]['setter'].call(this, val, key);
        toremove.push(key);
      }
    }
    if (!_.isEmpty(toremove)) {
      attrs = _.clone(attrs);
      for (j = 0, len = toremove.length; j < len; j++) {
        key = toremove[j];
        delete attrs[key];
      }
    }
    if (!_.isEmpty(attrs)) {
      old = {};
      for (key in attrs) {
        value = attrs[key];
        old[key] = this.get(key, resolve_refs = false);
      }
      HasProperties.__super__.set.call(this, attrs, options);
      results = [];
      for (key in attrs) {
        value = attrs[key];
        results.push(this._tell_document_about_change(key, old[key], this.get(key, resolve_refs = false)));
      }
      return results;
    }
  };

  HasProperties.prototype.convert_to_ref = function(value) {
    if (_.isArray(value)) {
      return _.map(value, this.convert_to_ref);
    } else {
      if (value instanceof HasProperties) {
        return value.ref();
      }
    }
  };

  HasProperties.prototype.add_dependencies = function(prop_name, object, fields) {
    var fld, j, len, prop_spec, results;
    if (!_.isArray(fields)) {
      fields = [fields];
    }
    prop_spec = this.properties[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;
  };

  HasProperties.prototype.register_setter = function(prop_name, setter) {
    var prop_spec;
    prop_spec = this.properties[prop_name];
    return prop_spec.setter = setter;
  };

  HasProperties.prototype.register_property = function(prop_name, getter, use_cache) {
    var changedep, prop_spec, propchange;
    if (_.isUndefined(use_cache)) {
      use_cache = true;
    }
    if (_.has(this.properties, prop_name)) {
      this.remove_property(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 = _this.get_cache(prop_name);
          _this.clear_cache(prop_name);
          new_val = _this.get(prop_name);
          firechange = new_val !== old_val;
        }
        if (firechange) {
          _this.trigger('change:' + prop_name, _this, _this.get(prop_name));
          return _this.trigger('change', _this);
        }
      };
    })(this);
    prop_spec = {
      'getter': getter,
      'dependencies': [],
      'use_cache': use_cache,
      'setter': null,
      'callbacks': {
        changedep: changedep,
        propchange: propchange
      }
    };
    this.properties[prop_name] = prop_spec;
    this.listenTo(this, "changedep:" + prop_name, prop_spec['callbacks']['propchange']);
    return prop_spec;
  };

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

  HasProperties.prototype.has_cache = function(prop_name) {
    return _.has(this.property_cache, prop_name);
  };

  HasProperties.prototype.add_cache = function(prop_name, val) {
    return this.property_cache[prop_name] = val;
  };

  HasProperties.prototype.clear_cache = function(prop_name, val) {
    return delete this.property_cache[prop_name];
  };

  HasProperties.prototype.get_cache = function(prop_name) {
    return this.property_cache[prop_name];
  };

  HasProperties.prototype.get = function(prop_name, resolve_refs) {
    var ref_or_val;
    if (resolve_refs == null) {
      resolve_refs = true;
    }
    if (_.has(this.properties, prop_name)) {
      return this._get_prop(prop_name);
    } else {
      ref_or_val = HasProperties.__super__.get.call(this, prop_name);
      if (!resolve_refs) {
        return ref_or_val;
      }
      return this.resolve_ref(ref_or_val);
    }
  };

  HasProperties.prototype._get_prop = function(prop_name) {
    var computed, getter, prop_spec;
    prop_spec = this.properties[prop_name];
    if (prop_spec.use_cache && this.has_cache(prop_name)) {
      return this.property_cache[prop_name];
    } else {
      getter = prop_spec.getter;
      computed = getter.apply(this, [prop_name]);
      if (this.properties[prop_name].use_cache) {
        this.add_cache(prop_name, computed);
      }
      return computed;
    }
  };

  HasProperties.prototype.ref = function() {
    return {
      'type': this.type,
      'id': this.id
    };
  };

  HasProperties._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;
  };

  HasProperties.prototype.resolve_ref = function(arg) {
    var model, x;
    if (_.isUndefined(arg)) {
      return arg;
    }
    if (_.isArray(arg)) {
      return (function() {
        var j, len, results;
        results = [];
        for (j = 0, len = arg.length; j < len; j++) {
          x = arg[j];
          results.push(this.resolve_ref(x));
        }
        return results;
      }).call(this);
    }
    if (HasProperties._is_ref(arg)) {
      if (arg['type'] === this.type && arg['id'] === this.id) {
        return this;
      } else if (this.document) {
        model = this.document.get_model_by_id(arg['id']);
        if (model === null) {
          throw new Error(this + " refers to " + (JSON.stringify(arg)) + " but it isn't in document " + this._document);
        } else {
          return model;
        }
      } else {
        throw new Error(this + " Cannot resolve ref " + (JSON.stringify(arg)) + " when not in a Document");
      }
    }
    return arg;
  };

  HasProperties.prototype.get_base = function() {
    if (!this._base) {
      this._base = require('./base');
    }
    return this._base;
  };

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

  HasProperties.prototype.defaults = function() {
    return {};
  };

  HasProperties.prototype.serializable_in_document = function() {
    return true;
  };

  HasProperties.prototype.nonserializable_attribute_names = function() {
    return [];
  };

  HasProperties.prototype._get_nonserializable_dict = function() {
    var j, len, n, names, ref;
    if (this.constructor._nonserializable_names_cache == null) {
      names = {};
      ref = this.nonserializable_attribute_names();
      for (j = 0, len = ref.length; j < len; j++) {
        n = ref[j];
        names[n] = true;
      }
      this.constructor._nonserializable_names_cache = names;
    }
    return this.constructor._nonserializable_names_cache;
  };

  HasProperties.prototype.attribute_is_serializable = function(attr) {
    return (!(attr in this._get_nonserializable_dict())) && (attr in this.attributes);
  };

  HasProperties.prototype.serializable_attributes = function() {
    var attrs, k, nonserializable, ref, v;
    nonserializable = this._get_nonserializable_dict();
    attrs = {};
    ref = this.attributes;
    for (k in ref) {
      v = ref[k];
      if (!(k in nonserializable)) {
        attrs[k] = v;
      }
    }
    return attrs;
  };

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

  HasProperties._value_to_json = function(key, value, optional_parent_object) {
    var i, j, len, ref_array, ref_obj, subkey, v;
    if (value instanceof HasProperties) {
      return value.ref();
    } else if (_.isArray(value)) {
      ref_array = [];
      for (i = j = 0, len = value.length; j < len; i = ++j) {
        v = value[i];
        if (v instanceof HasProperties && !v.serializable_in_document()) {
          console.log("May need to add " + key + " to nonserializable_attribute_names of " + (optional_parent_object != null ? optional_parent_object.constructor.name : void 0) + " because array contains a nonserializable type " + v.constructor.name + " under index " + i);
        } else {
          ref_array.push(HasProperties._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;
        if (value[subkey] instanceof HasProperties && !value[subkey].serializable_in_document()) {
          console.log("May need to add " + key + " to nonserializable_attribute_names of " + (optional_parent_object != null ? optional_parent_object.constructor.name : void 0) + " because value of type " + value.constructor.name + " contains a nonserializable type " + value[subkey].constructor.name + " under " + subkey);
        } else {
          ref_obj[subkey] = HasProperties._value_to_json(subkey, value[subkey], value);
        }
      }
      return ref_obj;
    } else {
      return value;
    }
  };

  HasProperties.prototype.attributes_as_json = function() {
    var fail, key, ref, value;
    fail = false;
    ref = this.serializable_attributes();
    for (key in ref) {
      if (!hasProp.call(ref, key)) continue;
      value = ref[key];
      if (value instanceof HasProperties && !value.serializable_in_document()) {
        console.log("May need to add " + key + " to nonserializable_attribute_names of " + this.constructor.name + " because value " + value.constructor.name + " is not serializable");
        fail = true;
      }
    }
    if (fail) {
      return {};
    }
    return HasProperties._value_to_json("attributes", this.serializable_attributes(), this);
  };

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

    } else if (HasProperties._is_ref(v)) {
      if (!(v.id in result)) {
        model = doc.get_model_by_id(v.id);
        return HasProperties._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(HasProperties._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(HasProperties._json_record_references(doc, elem, result, recurse));
      }
      return results1;
    }
  };

  HasProperties._value_record_references = function(v, result, recurse) {
    var attrs, elem, j, k, key, len, results, results1, results2, value;
    if (v === null) {

    } else if (v instanceof HasProperties) {
      if (!(v.id in result)) {
        result[v.id] = v;
        attrs = v.serializable_attributes();
        results = [];
        for (key in attrs) {
          value = attrs[key];
          if (value instanceof HasProperties && !value.serializable_in_document()) {
            console.log("May need to add " + key + " to nonserializable_attribute_names of " + v.constructor.name + " because value " + value.constructor.name + " is not serializable");
          }
          results.push(HasProperties._value_record_references(value, result, recurse));
        }
        return results;
      }
    } else if (_.isArray(v)) {
      results1 = [];
      for (j = 0, len = v.length; j < len; j++) {
        elem = v[j];
        if (elem instanceof HasProperties && !elem.serializable_in_document()) {
          console.log("Array contains nonserializable item, we shouldn't traverse this property ", elem);
          throw new Error("Trying to record refs for array with nonserializable item");
        }
        results1.push(HasProperties._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];
        if (elem instanceof HasProperties && !elem.serializable_in_document()) {
          console.log("Dict contains nonserializable item under " + k + ", we shouldn't traverse this property ", elem);
          throw new Error("Trying to record refs for dict with nonserializable item");
        }
        results2.push(HasProperties._value_record_references(elem, result, recurse));
      }
      return results2;
    }
  };

  HasProperties.prototype._immediate_references = function() {
    var result;
    result = {};
    HasProperties._value_record_references(this, result, false);
    delete result[this.id];
    return _.values(result);
  };

  HasProperties.prototype.attach_document = function(doc) {
    var c, first_attach, j, len, ref, results;
    if (this.document !== null && this.document !== doc) {
      throw new Error("Models must be owned by only a single document");
    }
    first_attach = this.document === null;
    this.document = doc;
    if (doc !== null) {
      doc._notify_attach(this);
      if (first_attach) {
        ref = this._immediate_references();
        results = [];
        for (j = 0, len = ref.length; j < len; j++) {
          c = ref[j];
          results.push(c.attach_document(doc));
        }
        return results;
      }
    }
  };

  HasProperties.prototype.detach_document = function() {
    var c, j, len, ref, results;
    if (this.document !== null) {
      if (this.document._notify_detach(this) === 0) {
        this.document = null;
        ref = this._immediate_references();
        results = [];
        for (j = 0, len = ref.length; j < len; j++) {
          c = ref[j];
          results.push(c.detach_document());
        }
        return results;
      }
    }
  };

  HasProperties.prototype._tell_document_about_change = function(attr, old, new_) {
    if (!this.attribute_is_serializable(attr)) {
      return;
    }
    if (old instanceof HasProperties && !old.serializable_in_document()) {
      console.log("May need to add " + attr + " to nonserializable_attribute_names of " + this.constructor.name + " because old value " + old.constructor.name + " is not serializable");
      return;
    }
    if (new_ instanceof HasProperties && !new_.serializable_in_document()) {
      console.log("May need to add " + attr + " to nonserializable_attribute_names of " + this.constructor.name + " because new value " + new_.constructor.name + " is not serializable");
      return;
    }
    if (new_ instanceof HasProperties && this.document !== null) {
      new_.attach_document(this.document);
    }
    if (old instanceof HasProperties) {
      old.detach_document();
    }
    if (this.document !== null) {
      return this.document._notify_change(this, attr, old, new_);
    }
  };

  return HasProperties;

})(Backbone.Model);

module.exports = HasProperties;


},{"./base":"common/base","./logging":"common/logging","backbone":"backbone","jquery":"jquery","underscore":"underscore"}],"common/hittest":[function(require,module,exports){
var check_2_segments_intersect, create_hit_test_result, dist_2_pts, dist_to_segment, dist_to_segment_squared, point_in_poly, sqr;

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

create_hit_test_result = function() {
  var result;
  result = {
    '0d': {
      flag: false,
      indices: []
    },
    '1d': {
      indices: []
    },
    '2d': {
      indices: []
    }
  };
  return result;
};

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


},{}],"common/layout_box":[function(require,module,exports){
var Constraint, Eq, Expression, Ge, HasProperties, LayoutBox, Le, Operator, Range1d, Variable, _, kiwi,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

kiwi = require("kiwi");

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

Eq = Operator.Eq, Le = Operator.Le, Ge = Operator.Ge;

HasProperties = require("./has_properties");

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

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

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

  LayoutBox.prototype.type = 'LayoutBox';

  LayoutBox.prototype.initialize = function(attrs, options) {
    var i, j, len, len1, name, ref, ref1, v;
    LayoutBox.__super__.initialize.call(this, attrs, options);
    this.solver = this.get('solver');
    this.var_constraints = {};
    ref = ['top', 'left', 'width', 'height'];
    for (i = 0, len = ref.length; i < len; i++) {
      v = ref[i];
      name = '_' + v;
      this[name] = new Variable(v);
      this.register_property(v, this._get_var, false);
      this.register_setter(v, this._set_var);
      this.solver.add_edit_variable(this[name], kiwi.Strength.strong);
    }
    ref1 = ['right', 'bottom'];
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      v = ref1[j];
      name = '_' + v;
      this[name] = new Variable(v);
      this.register_property(v, this._get_var, false);
    }
    this.solver.add_constraint(new Constraint(new Expression(this._top), Ge));
    this.solver.add_constraint(new Constraint(new Expression(this._bottom), Ge));
    this.solver.add_constraint(new Constraint(new Expression(this._left), Ge));
    this.solver.add_constraint(new Constraint(new Expression(this._right), Ge));
    this.solver.add_constraint(new Constraint(new Expression(this._width), Ge));
    this.solver.add_constraint(new Constraint(new Expression(this._height), Ge));
    this.solver.add_constraint(new Constraint(new Expression(this._left, this._width, [-1, this._right]), Eq));
    this.solver.add_constraint(new Constraint(new Expression(this._bottom, this._height, [-1, this._top]), Eq));
    this._h_range = new Range1d.Model({
      start: this.get('left'),
      end: this.get('left') + this.get('width')
    });
    this.register_property('h_range', (function(_this) {
      return function() {
        _this._h_range.set('start', _this.get('left'));
        _this._h_range.set('end', _this.get('left') + _this.get('width'));
        return _this._h_range;
      };
    })(this), false);
    this.add_dependencies('h_range', this, ['left', 'width']);
    this._v_range = new Range1d.Model({
      start: this.get('bottom'),
      end: this.get('bottom') + this.get('height')
    });
    this.register_property('v_range', (function(_this) {
      return function() {
        _this._v_range.set('start', _this.get('bottom'));
        _this._v_range.set('end', _this.get('bottom') + _this.get('height'));
        return _this._v_range;
      };
    })(this), false);
    this.add_dependencies('v_range', this, ['bottom', 'height']);
    this._aspect_constraint = null;
    this.register_property('aspect', (function(_this) {
      return function() {
        return _this.get('width') / _this.get('height');
      };
    })(this), true);
    this.register_setter('aspect', this._set_aspect);
    return this.add_dependencies('aspect', this, ['width', 'height']);
  };

  LayoutBox.prototype.serializable_in_document = function() {
    return false;
  };

  LayoutBox.prototype.contains = function(vx, vy) {
    return vx >= this.get('left') && vx <= this.get('right') && vy >= this.get('bottom') && vy <= this.get('top');
  };

  LayoutBox.prototype._set_var = function(value, prop_name) {
    var c, v;
    v = this['_' + prop_name];
    if (_.isNumber(value)) {
      return this.solver.suggest_value(v, value);
    } else if (_.isString(value)) {

    } else {
      c = new Constraint(new Expression(v, [-1, value]), Eq);
      if (this.var_constraints[prop_name] == null) {
        this.var_constraints[prop_name] = [];
      }
      this.var_constraints[prop_name].push(c);
      return this.solver.add_constraint(c);
    }
  };

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

  LayoutBox.prototype._set_aspect = function(aspect) {
    var c;
    if (this._aspect_constraint != null) {
      this.solver.remove_constraint(this.aspect_constraint);
      c = new Constraint(new Expression([aspect, this._height], [-1, this._width]), Eq);
      this._aspect_constraint = c;
      return this.solver.add_constraint(c);
    }
  };

  LayoutBox.prototype.defaults = function() {
    return _.extend({}, LayoutBox.__super__.defaults.call(this), {
      'top_strength': kiwi.Strength.strong,
      'bottom_strength': kiwi.Strength.strong,
      'left_strength': kiwi.Strength.strong,
      'right_strength': kiwi.Strength.strong,
      'width_strength': kiwi.Strength.strong,
      'height_strength': kiwi.Strength.strong
    });
  };

  return LayoutBox;

})(HasProperties);

module.exports = {
  Model: LayoutBox
};


},{"../range/range1d":"range/range1d","./has_properties":"common/has_properties","kiwi":"kiwi","underscore":"underscore"}],"common/logging":[function(require,module,exports){
var JL, logger, set_log_level;

JL = require("jsnlog").JL;

logger = JL("Bokeh");

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

set_log_level = function(level) {
  var valid_levels;
  valid_levels = {
    "trace": JL.getTraceLevel(),
    "debug": JL.getDebugLevel(),
    "info": JL.getInfoLevel(),
    "warn": JL.getWarnLevel(),
    "error": JL.getErrorLevel(),
    "fatal": JL.getFatalLevel()
  };
  if (!(level in valid_levels)) {
    console.log("Bokeh: Unrecognized logging level '" + level + "' passed to Bokeh.set_log_level, ignoring.");
    console.log("Bokeh: Valid log levels are: " + (Object.keys(valid_levels)));
    return;
  }
  console.log("Bokeh: setting log level to: '" + level + "'");
  return logger.setOptions({
    "level": valid_levels[level]
  });
};

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


},{"jsnlog":"jsnlog"}],"common/mathutils":[function(require,module,exports){
var angle_between, angle_dist, angle_norm, arrayMax, arrayMin;

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

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

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

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

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

module.exports = {
  arrayMin: arrayMin,
  arrayMax: arrayMax,
  angle_norm: angle_norm,
  angle_dist: angle_dist,
  angle_between: angle_between
};


},{}],"common/plot":[function(require,module,exports){
var $, Backbone, Canvas, CartesianFrame, Constraint, ContinuumView, Eq, Expression, Ge, HasParent, LayoutBox, Le, Operator, Plot, PlotView, Solver, ToolManager, UIEvents, _, build_views, global_gl_canvas, kiwi, logger, plot_template, plot_utils, properties,
  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");

$ = require("jquery");

Backbone = require("backbone");

kiwi = require("kiwi");

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

Eq = Operator.Eq, Le = Operator.Le, Ge = Operator.Ge;

build_views = require("./build_views");

Canvas = require("./canvas");

CartesianFrame = require("./cartesian_frame");

ContinuumView = require("./continuum_view");

UIEvents = require("./ui_events");

HasParent = require("./has_parent");

LayoutBox = require("./layout_box");

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

plot_utils = require("./plot_utils");

Solver = require("./solver");

ToolManager = require("./tool_manager");

plot_template = require("./plot_template");

properties = require("./properties");

global_gl_canvas = null;

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

  function PlotView() {
    this.resize_width_height = bind(this.resize_width_height, this);
    this.resize = bind(this.resize, this);
    this.remove = bind(this.remove, this);
    this.request_render = bind(this.request_render, this);
    return PlotView.__super__.constructor.apply(this, arguments);
  }

  PlotView.prototype.className = "bk-plot";

  PlotView.prototype.template = plot_template;

  PlotView.prototype.view_options = function() {
    return _.extend({
      plot_model: this.model,
      plot_view: this
    }, this.options);
  };

  PlotView.prototype.pause = function() {
    return this.is_paused = true;
  };

  PlotView.prototype.unpause = function() {
    this.is_paused = false;
    return this.request_render();
  };

  PlotView.prototype.request_render = function() {
    if (!this.is_paused) {
      this.throttled_render(true);
    }
  };

  PlotView.prototype.remove = function() {
    var id, ref, results, tool_view;
    PlotView.__super__.remove.call(this);
    ref = this.tools;
    results = [];
    for (id in ref) {
      tool_view = ref[id];
      results.push(tool_view.remove());
    }
    return results;
  };

  PlotView.prototype.initialize = function(options) {
    var id, j, len, level, ref, ref1, throttled_resize, tool_view, toolbar_location, toolbar_selector;
    PlotView.__super__.initialize.call(this, options);
    this.pause();
    this.model.initialize_layout(this.model.solver);
    this.frame = this.mget('frame');
    this.x_range = this.frame.get('x_ranges')['default'];
    this.y_range = this.frame.get('y_ranges')['default'];
    this.xmapper = this.frame.get('x_mappers')['default'];
    this.ymapper = this.frame.get('y_mappers')['default'];
    this.$el.html(this.template());
    this.canvas = this.mget('canvas');
    this.canvas_view = new this.canvas.default_view({
      'model': this.canvas
    });
    this.$('.bk-plot-canvas-wrapper').append(this.canvas_view.el);
    this.canvas_view.render();
    if (this.mget('webgl') || window.location.search.indexOf('webgl=1') > 0) {
      if (window.location.search.indexOf('webgl=0') === -1) {
        this.init_webgl();
      }
    }
    this.throttled_render = plot_utils.throttle_animation(this.render, 15);
    this.outline_props = new properties.Line({
      obj: this.model,
      prefix: 'outline_'
    });
    this.title_props = new properties.Text({
      obj: this.model,
      prefix: 'title_'
    });
    this.renderers = {};
    this.tools = {};
    this.levels = {};
    ref = plot_utils.LEVELS;
    for (j = 0, len = ref.length; j < len; j++) {
      level = ref[j];
      this.levels[level] = {};
    }
    this.build_levels();
    this.bind_bokeh_events();
    this.model.add_constraints(this.canvas.solver);
    this.listenTo(this.canvas.solver, 'layout_update', this.request_render);
    this.ui_event_bus = new UIEvents({
      tool_manager: this.mget('tool_manager'),
      hit_area: this.canvas_view.$el
    });
    ref1 = this.tools;
    for (id in ref1) {
      tool_view = ref1[id];
      this.ui_event_bus.register_tool(tool_view);
    }
    toolbar_location = this.mget('toolbar_location');
    if (toolbar_location != null) {
      toolbar_selector = '.bk-plot-' + toolbar_location;
      logger.debug("attaching toolbar to " + toolbar_selector + " for plot " + this.model.id);
      this.tm_view = new ToolManager.View({
        model: this.mget('tool_manager'),
        el: this.$(toolbar_selector)
      });
    }
    this.update_dataranges();
    if (this.mget('responsive')) {
      throttled_resize = _.throttle(this.resize, 100);
      $(window).on("resize", throttled_resize);
      _.delay(this.resize, 10);
    }
    this.unpause();
    logger.debug("PlotView initialized");
    return this;
  };

  PlotView.prototype.init_webgl = function() {
    var glcanvas, opts;
    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 this.canvas_view.ctx.glcanvas = glcanvas;
    } else {
      return logger.warn('WebGL is not supported, falling back to 2D canvas.');
    }
  };

  PlotView.prototype.update_dataranges = function() {
    var bds, bounds, frame, j, k, l, len, len1, ref, ref1, ref2, ref3, v, xr, yr;
    frame = this.model.get('frame');
    bounds = {};
    ref = this.renderers;
    for (k in ref) {
      v = ref[k];
      bds = (ref1 = v.glyph) != null ? typeof ref1.bounds === "function" ? ref1.bounds() : void 0 : void 0;
      if (bds != null) {
        bounds[k] = bds;
      }
    }
    ref2 = _.values(frame.get('x_ranges'));
    for (j = 0, len = ref2.length; j < len; j++) {
      xr = ref2[j];
      if (typeof xr.update === "function") {
        xr.update(bounds, 0, this);
      }
    }
    ref3 = _.values(frame.get('y_ranges'));
    for (l = 0, len1 = ref3.length; l < len1; l++) {
      yr = ref3[l];
      if (typeof yr.update === "function") {
        yr.update(bounds, 1, this);
      }
    }
    return this.range_update_timestamp = Date.now();
  };

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

  PlotView.prototype.update_range = function(range_info) {
    var name, ref, ref1, ref2, ref3, rng;
    if (range_info == null) {
      range_info = this.initial_range_info;
    }
    this.pause();
    ref = this.frame.get('x_ranges');
    for (name in ref) {
      rng = ref[name];
      if (rng.get('start') !== range_info.xrs[name]['start'] || rng.get('end') !== range_info.xrs[name]['end']) {
        rng.set(range_info.xrs[name]);
        if ((ref1 = rng.get('callback')) != null) {
          ref1.execute(this.model);
        }
      }
    }
    ref2 = this.frame.get('y_ranges');
    for (name in ref2) {
      rng = ref2[name];
      if (rng.get('start') !== range_info.yrs[name]['start'] || rng.get('end') !== range_info.yrs[name]['end']) {
        rng.set(range_info.yrs[name]);
        if ((ref3 = rng.get('callback')) != null) {
          ref3.execute(this.model);
        }
      }
    }
    return this.unpause();
  };

  PlotView.prototype.build_levels = function() {
    var id_, j, l, len, len1, len2, level, m, old_renderers, renderers_to_remove, t, tools, v, views;
    old_renderers = _.keys(this.renderers);
    views = build_views(this.renderers, this.mget('renderers'), this.view_options());
    renderers_to_remove = _.difference(old_renderers, _.pluck(this.mget('renderers'), 'id'));
    for (j = 0, len = renderers_to_remove.length; j < len; j++) {
      id_ = renderers_to_remove[j];
      delete this.levels.glyph[id_];
    }
    tools = build_views(this.tools, this.mget('tools'), this.view_options());
    for (l = 0, len1 = views.length; l < len1; l++) {
      v = views[l];
      level = v.mget('level');
      this.levels[level][v.model.id] = v;
      v.bind_bokeh_events();
    }
    for (m = 0, len2 = tools.length; m < len2; m++) {
      t = tools[m];
      level = t.mget('level');
      this.levels[level][t.model.id] = t;
      t.bind_bokeh_events();
    }
    return this;
  };

  PlotView.prototype.bind_bokeh_events = function() {
    var name, ref, ref1, rng;
    ref = this.mget('frame').get('x_ranges');
    for (name in ref) {
      rng = ref[name];
      this.listenTo(rng, 'change', this.request_render);
    }
    ref1 = this.mget('frame').get('y_ranges');
    for (name in ref1) {
      rng = ref1[name];
      this.listenTo(rng, 'change', this.request_render);
    }
    this.listenTo(this.model, 'change:renderers', this.build_levels);
    this.listenTo(this.model, 'change:tool', this.build_levels);
    this.listenTo(this.model, 'change', this.request_render);
    return this.listenTo(this.model, 'destroy', (function(_this) {
      return function() {
        return _this.remove();
      };
    })(this));
  };

  PlotView.prototype.set_initial_range = function() {
    var good_vals, name, ref, ref1, rng, xrs, yrs;
    good_vals = true;
    xrs = {};
    ref = this.frame.get('x_ranges');
    for (name in ref) {
      rng = ref[name];
      if ((rng.get('start') == null) || (rng.get('end') == null) || _.isNaN(rng.get('start') + rng.get('end'))) {
        good_vals = false;
        break;
      }
      xrs[name] = {
        start: rng.get('start'),
        end: rng.get('end')
      };
    }
    if (good_vals) {
      yrs = {};
      ref1 = this.frame.get('y_ranges');
      for (name in ref1) {
        rng = ref1[name];
        if ((rng.get('start') == null) || (rng.get('end') == null) || _.isNaN(rng.get('start') + rng.get('end'))) {
          good_vals = false;
          break;
        }
        yrs[name] = {
          start: rng.get('start'),
          end: rng.get('end')
        };
      }
    }
    if (good_vals) {
      this.initial_range_info = {
        xrs: xrs,
        yrs: yrs
      };
      return logger.debug("initial ranges set");
    } else {
      return logger.warn('could not set initial ranges');
    }
  };

  PlotView.prototype.render = function(force_canvas) {
    var canvas, ctx, flipped_top, frame, frame_box, gl, height, j, k, l, len, len1, lod_timeout, prefix, ref, ref1, ref2, ref3, sx, sy, th, title, trigger, v, width;
    if (force_canvas == null) {
      force_canvas = false;
    }
    logger.trace("Plot.render(force_canvas=" + force_canvas + ")");
    if (Date.now() - this.interactive_timestamp < this.mget('lod_interval')) {
      this.interactive = true;
      lod_timeout = this.mget('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;
    }
    width = this.mget("plot_width");
    height = this.mget("plot_height");
    if (this.canvas.get("canvas_width") !== width || this.canvas.get("canvas_height") !== height) {
      this.canvas._set_dims([width, height], trigger = false);
    }
    PlotView.__super__.render.call(this);
    this.canvas_view.render(force_canvas);
    if (this.tm_view != null) {
      this.tm_view.render();
    }
    ctx = this.canvas_view.ctx;
    frame = this.model.get('frame');
    canvas = this.model.get('canvas');
    ref = this.renderers;
    for (k in ref) {
      v = ref[k];
      if (v.model.update_layout != null) {
        v.model.update_layout(v, this.canvas.solver);
      }
    }
    ref1 = this.renderers;
    for (k in ref1) {
      v = ref1[k];
      if (v.set_data_timestamp > (this.range_update_timestamp != null)) {
        this.update_dataranges();
        break;
      }
    }
    title = this.mget('title');
    if (title) {
      this.title_props.set_value(this.canvas_view.ctx);
      th = ctx.measureText(this.mget('title')).ascent + this.model.get('title_standoff');
      if (th !== this.model.title_panel.get('height')) {
        this.model.title_panel.set('height', th);
      }
    }
    this.model.get('frame').set('width', canvas.get('width') - 1);
    this.model.get('frame').set('height', canvas.get('height') - 1);
    this.canvas.solver.update_variables(false);
    this.model.get('frame')._update_mappers();
    frame_box = [this.canvas.vx_to_sx(this.frame.get('left')), this.canvas.vy_to_sy(this.frame.get('top')), this.frame.get('width'), this.frame.get('height')];
    this._map_hook(ctx, frame_box);
    this._paint_empty(ctx, frame_box);
    if (ctx.glcanvas) {
      ctx.glcanvas.width = this.canvas_view.canvas[0].width;
      ctx.glcanvas.height = this.canvas_view.canvas[0].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 - (frame_box[1] + frame_box[3]);
      gl.scissor(frame_box[0], flipped_top, frame_box[2], frame_box[3]);
      gl.enable(gl.BLEND);
      gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE_MINUS_DST_ALPHA, gl.ONE);
    }
    if (this.outline_props.do_stroke) {
      this.outline_props.set_value(ctx);
      ctx.strokeRect.apply(ctx, frame_box);
    }
    this._render_levels(ctx, ['image', 'underlay', 'glyph', 'annotation'], frame_box);
    if (ctx.glcanvas) {
      ref2 = ['image', 'mozImage', 'webkitImage', 'msImage'];
      for (j = 0, len = ref2.length; j < len; j++) {
        prefix = ref2[j];
        ctx[prefix + 'SmoothingEnabled'] = false;
      }
      ctx.drawImage(ctx.glcanvas, 0.1, 0.1);
      ref3 = ['image', 'mozImage', 'webkitImage', 'msImage'];
      for (l = 0, len1 = ref3.length; l < len1; l++) {
        prefix = ref3[l];
        ctx[prefix + 'SmoothingEnabled'] = true;
      }
      logger.debug('drawing with WebGL');
    }
    this._render_levels(ctx, ['overlay', 'tool']);
    if (title) {
      sx = this.canvas.vx_to_sx(this.canvas.get('width') / 2);
      sy = this.canvas.vy_to_sy(this.model.title_panel.get('bottom') + this.model.get('title_standoff'));
      this.title_props.set_value(ctx);
      ctx.fillText(title, sx, sy);
    }
    if (this.initial_range_info == null) {
      return this.set_initial_range();
    }
  };

  PlotView.prototype.resize = function() {
    return this.resize_width_height(true, false);
  };

  PlotView.prototype.resize_width_height = function(use_width, use_height) {
    var aspect_ratio, canvas_height, canvas_width, min_size, new_height1, new_height2, new_width1, new_width2;
    canvas_height = this.canvas.get('height');
    canvas_width = this.canvas.get('width');
    aspect_ratio = canvas_width / canvas_height;
    min_size = this.mget('min_size');
    if (use_width) {
      new_width1 = Math.max(this.el.clientWidth, min_size);
      new_height1 = parseInt(new_width1 / aspect_ratio);
    }
    if (use_height) {
      new_height2 = Math.max(this.el.parentNode.clientHeight - 50, min_size);
      new_width2 = parseInt(new_height2 * aspect_ratio);
    }
    if ((!use_height) && (!use_width)) {

    } else if (use_height && use_width) {
      if (new_width2 < new_width1 && new_width2 > min_size) {
        this.canvas._set_dims([new_width2, new_height2]);
      } else {
        this.canvas._set_dims([new_width1, new_height1]);
      }
    } else if (use_height && new_width2 > min_size) {
      this.canvas._set_dims([new_width2, new_height2]);
    } else if (use_width && new_width1 > min_size) {
      this.canvas._set_dims([new_width1, new_height1]);
    } else if (aspect_ratio < 1) {
      this.canvas._set_dims([min_size, min_size / aspect_ratio]);
    } else {
      this.canvas._set_dims([min_size * aspect_ratio, min_size]);
    }
    return null;
  };

  PlotView.prototype._render_levels = function(ctx, levels, clip_region) {
    var i, indices, j, l, len, len1, len2, level, m, ref, 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 = {};
    ref = this.mget("renderers");
    for (i = j = 0, len = ref.length; j < len; i = ++j) {
      renderer = ref[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();
  };

  PlotView.prototype._map_hook = function(ctx, frame_box) {};

  PlotView.prototype._paint_empty = function(ctx, frame_box) {
    ctx.fillStyle = this.mget('border_fill');
    ctx.fillRect(0, 0, this.canvas_view.mget('canvas_width'), this.canvas_view.mget('canvas_height'));
    ctx.fillStyle = this.mget('background_fill');
    return ctx.fillRect.apply(ctx, frame_box);
  };

  return PlotView;

})(ContinuumView);

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(attrs, options) {
    var canvas, j, l, len, len1, len2, m, plots, r, ref, ref1, ref2, ref3, xr, yr;
    Plot.__super__.initialize.call(this, attrs, options);
    ref = _.values(this.get('extra_x_ranges')).concat(this.get('x_range'));
    for (j = 0, len = ref.length; j < len; j++) {
      xr = ref[j];
      xr = this.resolve_ref(xr);
      plots = xr.get('plots');
      if (_.isArray(plots)) {
        plots = plots.concat(this);
        xr.set('plots', plots);
      }
    }
    ref1 = _.values(this.get('extra_y_ranges')).concat(this.get('y_range'));
    for (l = 0, len1 = ref1.length; l < len1; l++) {
      yr = ref1[l];
      yr = this.resolve_ref(yr);
      plots = yr.get('plots');
      if (_.isArray(plots)) {
        plots = plots.concat(this);
        yr.set('plots', plots);
      }
    }
    canvas = new Canvas.Model({
      map: (ref2 = this.use_map) != null ? ref2 : false,
      canvas_width: this.get('plot_width'),
      canvas_height: this.get('plot_height'),
      hidpi: this.get('hidpi'),
      solver: new Solver()
    });
    this.set('canvas', canvas);
    this.solver = canvas.get('solver');
    ref3 = this.get('renderers');
    for (m = 0, len2 = ref3.length; m < len2; m++) {
      r = ref3[m];
      r.set('parent', this);
    }
    this.set('tool_manager', new ToolManager.Model({
      tools: this.get('tools'),
      toolbar_location: this.get('toolbar_location'),
      logo: this.get('logo')
    }));
    return logger.debug("Plot initialized");
  };

  Plot.prototype.initialize_layout = function(solver) {
    var canvas, elts, frame;
    canvas = this.get('canvas');
    frame = new CartesianFrame.Model({
      x_range: this.get('x_range'),
      extra_x_ranges: this.get('extra_x_ranges'),
      x_mapper_type: this.get('x_mapper_type'),
      y_range: this.get('y_range'),
      extra_y_ranges: this.get('extra_y_ranges'),
      y_mapper_type: this.get('y_mapper_type'),
      solver: solver
    });
    this.set('frame', frame);
    this.title_panel = new LayoutBox.Model({
      solver: solver
    });
    this.title_panel._anchor = this.title_panel._bottom;
    elts = this.get('above');
    elts.push(this.title_panel);
    return this.set('above', elts);
  };

  Plot.prototype.add_constraints = function(solver) {
    var do_side, min_border_bottom, min_border_left, min_border_right, min_border_top, ref, ref1, ref2, ref3;
    min_border_top = (ref = this.get('min_border_top')) != null ? ref : this.get('min_border');
    min_border_bottom = (ref1 = this.get('min_border_bottom')) != null ? ref1 : this.get('min_border');
    min_border_left = (ref2 = this.get('min_border_left')) != null ? ref2 : this.get('min_border');
    min_border_right = (ref3 = this.get('min_border_right')) != null ? ref3 : this.get('min_border');
    do_side = (function(_this) {
      return function(solver, min_size, side, cnames, dim, op) {
        var box, c0, c1, canvas, elts, frame, j, last, len, padding, r, ref4;
        canvas = _this.get('canvas');
        frame = _this.get('frame');
        box = new LayoutBox.Model({
          solver: solver
        });
        c0 = '_' + cnames[0];
        c1 = '_' + cnames[1];
        solver.add_constraint(new Constraint(new Expression(box['_' + dim], -min_size), Ge), kiwi.Strength.strong);
        solver.add_constraint(new Constraint(new Expression(frame[c0], [-1, box[c1]]), Eq));
        solver.add_constraint(new Constraint(new Expression(box[c0], [-1, canvas[c0]]), Eq));
        last = frame;
        elts = _this.get(side);
        for (j = 0, len = elts.length; j < len; j++) {
          r = elts[j];
          if ((ref4 = r.get('location')) != null ? ref4 : 'auto' === 'auto') {
            r.set('layout_location', side, {
              silent: true
            });
          } else {
            r.set('layout_location', r.get('location'), {
              silent: true
            });
          }
          if (r.initialize_layout != null) {
            r.initialize_layout(solver);
          }
          solver.add_constraint(new Constraint(new Expression(last[c0], [-1, r[c1]]), Eq), kiwi.Strength.strong);
          last = r;
        }
        padding = new LayoutBox.Model({
          solver: solver
        });
        solver.add_constraint(new Constraint(new Expression(last[c0], [-1, padding[c1]]), Eq), kiwi.Strength.strong);
        return solver.add_constraint(new Constraint(new Expression(padding[c0], [-1, canvas[c0]]), Eq), kiwi.Strength.strong);
      };
    })(this);
    do_side(solver, min_border_top, 'above', ['top', 'bottom'], 'height', Le);
    do_side(solver, min_border_bottom, 'below', ['bottom', 'top'], 'height', Ge);
    do_side(solver, min_border_left, 'left', ['left', 'right'], 'width', Ge);
    return do_side(solver, min_border_right, 'right', ['right', 'left'], 'width', Le);
  };

  Plot.prototype.add_renderers = function(new_renderers) {
    var renderers;
    renderers = this.get('renderers');
    renderers = renderers.concat(new_renderers);
    return this.set('renderers', renderers);
  };

  Plot.prototype.parent_properties = ['background_fill', 'border_fill', 'min_border', 'min_border_top', 'min_border_bottom', 'min_border_left', 'min_border_right'];

  Plot.prototype.nonserializable_attribute_names = function() {
    return Plot.__super__.nonserializable_attribute_names.call(this).concat(['solver', 'above', 'below', 'left', 'right', 'canvas', 'tool_manager', 'frame', 'min_size']);
  };

  Plot.prototype.serializable_attributes = function() {
    var attrs;
    attrs = Plot.__super__.serializable_attributes.call(this);
    if ('renderers' in attrs) {
      attrs['renderers'] = _.filter(attrs['renderers'], function(r) {
        return r.serializable_in_document();
      });
    }
    return attrs;
  };

  Plot.prototype.defaults = function() {
    return _.extend({}, Plot.__super__.defaults.call(this), {
      renderers: [],
      tools: [],
      h_symmetry: true,
      v_symmetry: false,
      x_mapper_type: 'auto',
      y_mapper_type: 'auto',
      plot_width: 600,
      plot_height: 600,
      title: '',
      above: [],
      below: [],
      left: [],
      right: [],
      toolbar_location: "above",
      logo: "normal",
      lod_factor: 10,
      lod_interval: 300,
      lod_threshold: 2000,
      lod_timeout: 500,
      webgl: false,
      responsive: false,
      min_size: 100
    });
  };

  Plot.prototype.display_defaults = function() {
    return _.extend({}, Plot.__super__.display_defaults.call(this), {
      hidpi: true,
      background_fill: "#fff",
      border_fill: "#fff",
      min_border: 40,
      title_standoff: 8,
      title_text_font: "helvetica",
      title_text_font_size: "20pt",
      title_text_font_style: "normal",
      title_text_color: "#444444",
      title_text_alpha: 1.0,
      title_text_align: "center",
      title_text_baseline: "alphabetic",
      outline_line_color: '#aaaaaa',
      outline_line_width: 1,
      outline_line_alpha: 1.0,
      outline_line_join: 'miter',
      outline_line_cap: 'butt',
      outline_line_dash: [],
      outline_line_dash_offset: 0
    });
  };

  return Plot;

})(HasParent);

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


},{"./build_views":"common/build_views","./canvas":"common/canvas","./cartesian_frame":"common/cartesian_frame","./continuum_view":"common/continuum_view","./has_parent":"common/has_parent","./layout_box":"common/layout_box","./logging":"common/logging","./plot_template":"common/plot_template","./plot_utils":"common/plot_utils","./properties":"common/properties","./solver":"common/solver","./tool_manager":"common/tool_manager","./ui_events":"common/ui_events","backbone":"backbone","jquery":"jquery","kiwi":"kiwi","underscore":"underscore"}],"common/plot_template":[function(require,module,exports){
module.exports = function(__obj) {
  if (!__obj) __obj = {};
  var __out = [], __capture = function(callback) {
    var out = __out, result;
    __out = [];
    callback.call(this);
    result = __out.join('');
    __out = out;
    return __safe(result);
  }, __sanitize = function(value) {
    if (value && value.ecoSafe) {
      return value;
    } else if (typeof value !== 'undefined' && value != null) {
      return __escape(value);
    } else {
      return '';
    }
  }, __safe, __objSafe = __obj.safe, __escape = __obj.escape;
  __safe = __obj.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;
    }
  };
  if (!__escape) {
    __escape = __obj.escape = function(value) {
      return ('' + value)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;');
    };
  }
  (function() {
    (function() {
      __out.push('<div class=\'bk-plot-wrapper\'>\n\t<table>\n\t\t<tr>\n\t\t\t<td></td>\n\t\t\t<td class=\'bk-plot-above\'></td>\n\t\t\t<td></td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td class="bk-plot-left"></td>\n\t\t\t<td class=\'bk-plot-canvas-wrapper\'></td>\n\t\t\t<td class="bk-plot-right"></td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td></td>\n\t\t\t<td class=\'bk-plot-below\'></td>\n\t\t\t<td></td>\n\t\t</tr>\n\t</table>\n</div>\n');
    
    }).call(this);
    
  }).call(__obj);
  __obj.safe = __objSafe, __obj.escape = __escape;
  return __out.join('');
}
},{}],"common/plot_utils":[function(require,module,exports){
var LEVELS, _delay_animation, delay_animation, throttle_animation;

LEVELS = ['image', 'underlay', 'glyph', 'overlay', 'annotation', 'tool'];

_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_animation = 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) {
      timeout = setTimeout((function() {
        return delay_animation(later);
      }), remaining);
    }
    return result;
  };
};

module.exports = {
  LEVELS: LEVELS,
  throttle_animation: throttle_animation
};


},{}],"common/plot_widget":[function(require,module,exports){
var ContinuumView, PlotWidget,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

ContinuumView = require("./continuum_view");

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

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

  PlotWidget.prototype.tagName = 'div';

  PlotWidget.prototype.initialize = function(options) {
    this.plot_model = options.plot_model;
    return this.plot_view = options.plot_view;
  };

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

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

  module.exports = PlotWidget;

  return PlotWidget;

})(ContinuumView);


},{"./continuum_view":"common/continuum_view"}],"common/properties":[function(require,module,exports){
var Angle, Array, Bool, Color, ContextProperties, Coord, Direction, Distance, Enum, Fill, HasProperties, Line, Numeric, Property, String, Text, _, angles, coords, distances, fields, svg_colors, visuals,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

HasProperties = require("./has_properties");

svg_colors = require("./svg_colors");

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

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

  Property.prototype.initialize = function(attrs, options) {
    Property.__super__.initialize.call(this, attrs, options);
    this.obj = this.get('obj');
    this.attr = this.get('attr');
    this.listenTo(this.obj, "change:" + this.attr, function() {
      this._init();
      return this.obj.trigger("propchange");
    });
    return this._init();
  };

  Property.prototype.serializable_in_document = function() {
    var result;
    if (this.get('obj') != null) {
      result = this.get('obj').serializable_in_document();
      if (!result) {
        console.log("  'obj' field of " + this.constructor.name + " has a nonserializable value of type " + (this.get('obj').constructor.name));
      }
      return result;
    } else {
      return true;
    }
  };

  Property.prototype._init = function() {
    var attr_value;
    attr_value = this.obj.get(this.attr);
    if (_.isObject(attr_value) && !_.isArray(attr_value)) {
      this.spec = attr_value;
      if (!_.isUndefined(this.spec.value)) {
        this.fixed_value = this.spec.value;
      } else if (this.spec.field != null) {
        this.field = this.spec.field;
      } else {
        throw new Error("spec for property '" + attr + "' needs one of 'value' or 'field'");
      }
    } else {
      this.fixed_value = attr_value;
    }
    if ((this.field != null) && !_.isString(this.field)) {
      throw new Error("field value for property '" + attr + "' is not a string");
    }
    if (this.fixed_value != null) {
      return this.validate(this.fixed_value, this.attr);
    }
  };

  Property.prototype.value = function() {
    var result;
    result = this.fixed_value != null ? this.fixed_value : NaN;
    return this.transform([result])[0];
  };

  Property.prototype.array = function(source) {
    var data, i, length, value;
    data = source.get('data');
    if ((this.field != null) && (this.field in data)) {
      return this.transform(source.get_column(this.field));
    } else {
      length = source.get_length();
      if (length == null) {
        length = 1;
      }
      value = this.value();
      return (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;
      })();
    }
  };

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

  Property.prototype.validate = function(value, attr) {
    return true;
  };

  return Property;

})(HasProperties);

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

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

  Numeric.prototype.validate = function(value, attr) {
    if (!_.isNumber(value)) {
      throw new Error("numeric property '" + attr + "' given invalid value: " + value);
    }
    return true;
  };

  Numeric.prototype.transform = function(values) {
    var i, j, ref, result;
    result = new Float64Array(values.length);
    for (i = j = 0, ref = values.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      result[i] = values[i];
    }
    return result;
  };

  return Numeric;

})(Property);

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

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

  Angle.prototype.initialize = function(attrs, options) {
    var attr, obj, ref, ref1, ref2;
    Angle.__super__.initialize.call(this, attrs, options);
    obj = this.get('obj');
    attr = this.get('attr');
    this.units = (ref = (ref1 = (ref2 = this.spec) != null ? ref2.units : void 0) != null ? ref1 : obj.get(attr + "_units")) != null ? ref : "rad";
    if (this.units !== "deg" && this.units !== "rad") {
      throw new Error("Angle units must be one of 'deg' or 'rad', given invalid value: " + this.units);
    }
  };

  Angle.prototype.transform = function(values) {
    var x;
    if (this.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;

})(Numeric);

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

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

  Distance.prototype.initialize = function(attrs, options) {
    var attr, obj, ref, ref1, ref2;
    Distance.__super__.initialize.call(this, attrs, options);
    obj = this.get('obj');
    attr = this.get('attr');
    this.units = (ref = (ref1 = (ref2 = this.spec) != null ? ref2.units : void 0) != null ? ref1 : obj.get(attr + "_units")) != null ? ref : "data";
    if (this.units !== "data" && this.units !== "screen") {
      throw new Error("Distance units must be one of 'data' or 'screen', given invalid value: " + this.units);
    }
  };

  return Distance;

})(Numeric);

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

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

  Array.prototype.validate = function(value, attr) {
    if (!_.isArray(value)) {
      throw new Error("array property '" + attr + "' given invalid value: " + value);
    }
    return true;
  };

  return Array;

})(Property);

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

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

  Bool.prototype.validate = function(value, attr) {
    if (!_.isBoolean(value)) {
      throw new Error("boolean property '" + attr + "' given invalid value: " + value);
    }
    return true;
  };

  return Bool;

})(Property);

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

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

  Coord.prototype.validate = function(value, attr) {
    if (!_.isNumber(value) && !_.isString(value)) {
      throw new Error("coordinate property '" + attr + "' given invalid value: " + value);
    }
    return true;
  };

  return Coord;

})(Property);

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

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

  Color.prototype.validate = function(value, attr) {
    if ((svg_colors[value.toLowerCase()] == null) && value.substring(0, 1) !== "#" && !this.valid_rgb(value)) {
      throw new Error("color property '" + attr + "' given invalid value: " + value);
    }
    return true;
  };

  Color.prototype.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;
  };

  return Color;

})(Property);

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

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

  String.prototype.validate = function(value, attr) {
    if (!_.isString(value)) {
      throw new Error("string property '" + attr + "' given invalid value: " + value);
    }
    return true;
  };

  return String;

})(Property);

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

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

  Enum.prototype.initialize = function(attrs, options) {
    this.levels = attrs.values.split(" ");
    return Enum.__super__.initialize.call(this, attrs, options);
  };

  Enum.prototype.validate = function(value, attr) {
    if (indexOf.call(this.levels, value) < 0) {
      throw new Error("enum property '" + attr + "' given invalid value: " + value + ", valid values are: " + this.levels);
    }
    return true;
  };

  return Enum;

})(Property);

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

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

  Direction.prototype.initialize = function(attrs, options) {
    attrs.values = "anticlock clock";
    return Direction.__super__.initialize.call(this, attrs, options);
  };

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

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

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

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

  ContextProperties.prototype.warm_cache = function(source, attrs) {
    var attr, j, len, prop, results;
    results = [];
    for (j = 0, len = attrs.length; j < len; j++) {
      attr = attrs[j];
      prop = this[attr];
      if (prop.fixed_value != null) {
        results.push(this.cache[attr] = prop.fixed_value);
      } else {
        results.push(this.cache[attr + "_array"] = prop.array(source));
      }
    }
    return results;
  };

  ContextProperties.prototype.cache_select = function(attr, i) {
    var prop;
    prop = this[attr];
    if (prop.fixed_value != null) {
      return this.cache[attr] = prop.fixed_value;
    } else {
      return this.cache[attr] = this.cache[attr + "_array"][i];
    }
  };

  return ContextProperties;

})(HasProperties);

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

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

  Line.prototype.initialize = function(attrs, options) {
    var obj, prefix;
    Line.__super__.initialize.call(this, attrs, options);
    obj = this.get('obj');
    prefix = this.get('prefix');
    this.color = new Color({
      obj: obj,
      attr: prefix + "line_color"
    });
    this.width = new Numeric({
      obj: obj,
      attr: prefix + "line_width"
    });
    this.alpha = new Numeric({
      obj: obj,
      attr: prefix + "line_alpha"
    });
    this.join = new Enum({
      obj: obj,
      attr: prefix + "line_join",
      values: "miter round bevel"
    });
    this.cap = new Enum({
      obj: obj,
      attr: prefix + "line_cap",
      values: "butt round square"
    });
    this.dash = new Array({
      obj: obj,
      attr: prefix + "line_dash"
    });
    this.dash_offset = new Numeric({
      obj: obj,
      attr: prefix + "line_dash_offset"
    });
    this.do_stroke = true;
    if (!_.isUndefined(this.color.fixed_value)) {
      if (_.isNull(this.color.fixed_value)) {
        return this.do_stroke = false;
      }
    }
  };

  Line.prototype.warm_cache = function(source) {
    return Line.__super__.warm_cache.call(this, source, ["color", "width", "alpha", "join", "cap", "dash", "dash_offset"]);
  };

  Line.prototype.set_value = function(ctx) {
    ctx.strokeStyle = this.color.value();
    ctx.globalAlpha = this.alpha.value();
    ctx.lineWidth = this.width.value();
    ctx.lineJoin = this.join.value();
    ctx.lineCap = this.cap.value();
    ctx.setLineDash(this.dash.value());
    return ctx.setLineDashOffset(this.dash_offset.value());
  };

  Line.prototype.set_vectorize = function(ctx, i) {
    this.cache_select("color", i);
    if (ctx.strokeStyle !== this.cache.fill) {
      ctx.strokeStyle = this.cache.color;
    }
    this.cache_select("alpha", i);
    if (ctx.globalAlpha !== this.cache.alpha) {
      ctx.globalAlpha = this.cache.alpha;
    }
    this.cache_select("width", i);
    if (ctx.lineWidth !== this.cache.width) {
      ctx.lineWidth = this.cache.width;
    }
    this.cache_select("join", i);
    if (ctx.lineJoin !== this.cache.join) {
      ctx.lineJoin = this.cache.join;
    }
    this.cache_select("cap", i);
    if (ctx.lineCap !== this.cache.cap) {
      ctx.lineCap = this.cache.cap;
    }
    this.cache_select("dash", i);
    if (ctx.getLineDash() !== this.cache.dash) {
      ctx.setLineDash(this.cache.dash);
    }
    this.cache_select("dash_offset", i);
    if (ctx.getLineDashOffset() !== this.cache.dash_offset) {
      return ctx.setLineDashOffset(this.cache.dash_offset);
    }
  };

  return Line;

})(ContextProperties);

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

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

  Fill.prototype.initialize = function(attrs, options) {
    var obj, prefix;
    Fill.__super__.initialize.call(this, attrs, options);
    obj = this.get('obj');
    prefix = this.get('prefix');
    this.color = new Color({
      obj: obj,
      attr: prefix + "fill_color"
    });
    this.alpha = new Numeric({
      obj: obj,
      attr: prefix + "fill_alpha"
    });
    this.do_fill = true;
    if (!_.isUndefined(this.color.fixed_value)) {
      if (_.isNull(this.color.fixed_value)) {
        return this.do_fill = false;
      }
    }
  };

  Fill.prototype.warm_cache = function(source) {
    return Fill.__super__.warm_cache.call(this, source, ["color", "alpha"]);
  };

  Fill.prototype.set_value = function(ctx) {
    ctx.fillStyle = this.color.value();
    return ctx.globalAlpha = this.alpha.value();
  };

  Fill.prototype.set_vectorize = function(ctx, i) {
    this.cache_select("color", i);
    if (ctx.fillStyle !== this.cache.fill) {
      ctx.fillStyle = this.cache.color;
    }
    this.cache_select("alpha", i);
    if (ctx.globalAlpha !== this.cache.alpha) {
      return ctx.globalAlpha = this.cache.alpha;
    }
  };

  return Fill;

})(ContextProperties);

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

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

  Text.prototype.initialize = function(attrs, options) {
    var obj, prefix;
    Text.__super__.initialize.call(this, attrs, options);
    obj = this.get('obj');
    prefix = this.get('prefix');
    this.font = new String({
      obj: obj,
      attr: prefix + "text_font"
    });
    this.font_size = new String({
      obj: obj,
      attr: prefix + "text_font_size"
    });
    this.font_style = new Enum({
      obj: obj,
      attr: prefix + "text_font_style",
      values: "normal italic bold"
    });
    this.color = new Color({
      obj: obj,
      attr: prefix + "text_color"
    });
    this.alpha = new Numeric({
      obj: obj,
      attr: prefix + "text_alpha"
    });
    this.align = new Enum({
      obj: obj,
      attr: prefix + "text_align",
      values: "left right center"
    });
    return this.baseline = new Enum({
      obj: obj,
      attr: prefix + "text_baseline",
      values: "top middle bottom alphabetic hanging"
    });
  };

  Text.prototype.warm_cache = function(source) {
    return Text.__super__.warm_cache.call(this, source, ["font", "font_size", "font_style", "color", "alpha", "align", "baseline"]);
  };

  Text.prototype.cache_select = function(name, i) {
    var val;
    if (name === "font") {
      val = Text.__super__.cache_select.call(this, "font_style", i) + " " + Text.__super__.cache_select.call(this, "font_size", i) + " " + Text.__super__.cache_select.call(this, "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.font.value();
    font_size = this.font_size.value();
    font_style = this.font_style.value();
    return font_style + " " + font_size + " " + font;
  };

  Text.prototype.set_value = function(ctx) {
    ctx.font = this.font_value();
    ctx.fillStyle = this.color.value();
    ctx.globalAlpha = this.alpha.value();
    ctx.textAlign = this.align.value();
    return ctx.textBaseline = this.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("color", i);
    if (ctx.fillStyle !== this.cache.color) {
      ctx.fillStyle = this.cache.color;
    }
    this.cache_select("alpha", i);
    if (ctx.globalAlpha !== this.cache.alpha) {
      ctx.globalAlpha = this.cache.alpha;
    }
    this.cache_select("align", i);
    if (ctx.textAlign !== this.cache.align) {
      ctx.textAlign = this.cache.align;
    }
    this.cache_select("baseline", i);
    if (ctx.textBaseline !== this.cache.baseline) {
      return ctx.textBaseline = this.cache.baseline;
    }
  };

  return Text;

})(ContextProperties);

angles = function(model, attr) {
  var angle, j, len, ref, result;
  if (attr == null) {
    attr = "angles";
  }
  result = {};
  ref = model[attr];
  for (j = 0, len = ref.length; j < len; j++) {
    angle = ref[j];
    result[angle] = new Angle({
      obj: model,
      attr: angle
    });
  }
  return result;
};

coords = function(model, attr) {
  var j, len, ref, ref1, result, x, y;
  if (attr == null) {
    attr = "coords";
  }
  result = {};
  ref = model[attr];
  for (j = 0, len = ref.length; j < len; j++) {
    ref1 = ref[j], x = ref1[0], y = ref1[1];
    result[x] = new Coord({
      obj: model,
      attr: x
    });
    result[y] = new Coord({
      obj: model,
      attr: y
    });
  }
  return result;
};

distances = function(model, attr) {
  var dist, j, len, ref, result;
  if (attr == null) {
    attr = "distances";
  }
  result = {};
  ref = model[attr];
  for (j = 0, len = ref.length; j < len; j++) {
    dist = ref[j];
    if (dist[0] === "?") {
      dist = dist.slice(1);
      if (model.get(dist) == null) {
        continue;
      }
    }
    result[dist] = new Distance({
      obj: model,
      attr: dist
    });
  }
  return result;
};

fields = function(model, attr) {
  var arg, field, j, len, ref, ref1, result, type;
  if (attr == null) {
    attr = "fields";
  }
  result = {};
  ref = model[attr];
  for (j = 0, len = ref.length; j < len; j++) {
    field = ref[j];
    type = "number";
    if (field.indexOf(":") > -1) {
      ref1 = field.split(":"), field = ref1[0], type = ref1[1], arg = ref1[2];
    }
    if (field[0] === "?") {
      field = field.slice(1);
      if (model.attributes[field] == null) {
        continue;
      }
    }
    switch (type) {
      case "array":
        result[field] = new Array({
          obj: model,
          attr: field
        });
        break;
      case "bool":
        result[field] = new Bool({
          obj: model,
          attr: field
        });
        break;
      case "color":
        result[field] = new Color({
          obj: model,
          attr: field
        });
        break;
      case "direction":
        result[field] = new Direction({
          obj: model,
          attr: field
        });
        break;
      case "enum":
        result[field] = new Enum({
          obj: model,
          attr: field,
          values: arg
        });
        break;
      case "number":
        result[field] = new Numeric({
          obj: model,
          attr: field
        });
        break;
      case "string":
        result[field] = new String({
          obj: model,
          attr: field
        });
    }
  }
  return result;
};

visuals = function(model, attr) {
  var j, len, name, prefix, prop, ref, ref1, result;
  if (attr == null) {
    attr = "visuals";
  }
  result = {};
  ref = model[attr];
  for (j = 0, len = ref.length; j < len; j++) {
    prop = ref[j];
    prefix = "";
    if (prop.indexOf(":") > -1) {
      ref1 = prop.split(":"), prop = ref1[0], prefix = ref1[1];
    }
    name = "" + prefix + prop;
    switch (prop) {
      case "line":
        result[name] = new Line({
          obj: model,
          prefix: prefix
        });
        break;
      case "fill":
        result[name] = new Fill({
          obj: model,
          prefix: prefix
        });
        break;
      case "text":
        result[name] = new Text({
          obj: model,
          prefix: prefix
        });
    }
  }
  return result;
};

module.exports = {
  Angle: Angle,
  Array: Array,
  Bool: Bool,
  Color: Color,
  Coord: Coord,
  Direction: Direction,
  Distance: Distance,
  Enum: Enum,
  Numeric: Numeric,
  Property: Property,
  String: String,
  Line: Line,
  Fill: Fill,
  Text: Text,
  factories: {
    coords: coords,
    distances: distances,
    angles: angles,
    fields: fields,
    visuals: visuals
  }
};


},{"./has_properties":"common/has_properties","./svg_colors":"common/svg_colors","underscore":"underscore"}],"common/random":[function(require,module,exports){
var Random;

Random = (function() {
  function Random(seed1) {
    var ref;
    this.seed = seed1;
    this.multiplier = 1664525;
    this.modulo = 4294967296;
    this.offset = 1013904223;
    if (!((this.seed != null) && (0 <= (ref = this.seed) && ref < this.modulo))) {
      this.seed = (new Date().valueOf() * new Date().getMilliseconds()) % this.modulo;
    }
  }

  Random.prototype.seed = function(seed) {
    return this.seed = seed;
  };

  Random.prototype.randn = function() {
    return this.seed = (this.multiplier * this.seed + this.offset) % this.modulo;
  };

  Random.prototype.randf = function() {
    return this.randn() / this.modulo;
  };

  Random.prototype.rand = function(n) {
    return Math.floor(this.randf() * n);
  };

  Random.prototype.rand2 = function(min, max) {
    return min + this.rand(max - min);
  };

  return Random;

})();

module.exports = Random;


},{}],"common/selection_manager":[function(require,module,exports){
var HasProperties, SelectionManager, Selector, _, hittest, 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");

HasProperties = require("./has_properties");

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

Selector = require("./selector");

hittest = require("./hittest");

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

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

  SelectionManager.prototype.type = 'SelectionManager';

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

  SelectionManager.prototype.serializable_in_document = function() {
    return false;
  };

  SelectionManager.prototype.set_selection = function(indices) {
    var source;
    this._save_indices(indices);
    source = this.get('source');
    return source.trigger('select');
  };

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

  SelectionManager.prototype.inspect = function(tool, renderer_view, geometry, data) {
    var indices, source;
    source = this.get('source');
    if (source !== renderer_view.mget('data_source')) {
      logger.warn('inspect called with mis-matched data sources');
    }
    indices = renderer_view.hit_test(geometry);
    if (indices != null) {
      source.trigger('inspect', indices, tool, renderer_view, source, data);
      return source.trigger("inspect" + (renderer_view.mget('id')), indices, tool, renderer_view, source, data);
    }
  };

  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._save_indices(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._save_indices = function(indices) {
    return this.get('source').set({
      "selected": indices
    });
  };

  return SelectionManager;

})(HasProperties);

module.exports = SelectionManager;


},{"./has_properties":"common/has_properties","./hittest":"common/hittest","./logging":"common/logging","./selector":"common/selector","underscore":"underscore"}],"common/selector":[function(require,module,exports){
var HasProperties, Selector, _, hittest, 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");

HasProperties = require("./has_properties");

hittest = require("./hittest");

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

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) {
    this.set('timestamp', new Date());
    this.set('final', final);
    if (append) {
      indices['0d'].indices = _.union(this.get('indices')['0d'].indices, indices['0d'].indices);
      indices['0d'].flag = this.get('indices')['0d'].flag || indices['0d'].flag;
      indices['1d'].indices = _.union(this.get('indices')['1d'].indices, indices['1d'].indices);
      indices['2d'].indices = _.union(this.get('indices')['2d'].indices, indices['2d'].indices);
    }
    return this.set('indices', indices);
  };

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

  Selector.prototype.defaults = function() {
    return _.extend({}, Selector.__super__.defaults.call(this), {
      indices: hittest.create_hit_test_result()
    });
  };

  return Selector;

})(HasProperties);

module.exports = Selector;


},{"./has_properties":"common/has_properties","./hittest":"common/hittest","./logging":"common/logging","underscore":"underscore"}],"common/solver":[function(require,module,exports){
var Backbone, Solver, _, kiwi;

_ = require("underscore");

Backbone = require("backbone");

kiwi = require("kiwi");

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

  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) {
    if (strength == null) {
      strength = kiwi.Strength.strong;
    }
    return this.solver.addEditVariable(variable, strength);
  };

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

  return Solver;

})();

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

module.exports = Solver;


},{"backbone":"backbone","kiwi":"kiwi","underscore":"underscore"}],"common/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",
  lightgrey: "#D3D3D3",
  silver: "#C0C0C0",
  darkgray: "#A9A9A9",
  darkgrey: "#A9A9A9",
  gray: "#808080",
  grey: "#808080",
  dimgray: "#696969",
  dimgrey: "#696969",
  lightslategray: "#778899",
  lightslategrey: "#778899",
  slategray: "#708090",
  darkslategray: "#2F4F4F",
  darkslategrey: "#2F4F4F",
  black: "#000000"
};


},{}],"common/textutils":[function(require,module,exports){
var $, cache, getTextHeight;

$ = require("jquery");

cache = {};

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


},{"jquery":"jquery"}],"common/tool_events":[function(require,module,exports){
var HasProperties, ToolEvents, 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;

HasProperties = require("./has_properties");

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

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

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

  ToolEvents.prototype.type = 'ToolEvents';

  return ToolEvents;

})(HasProperties);

module.exports = {
  Model: ToolEvents
};


},{"./has_properties":"common/has_properties","./logging":"common/logging"}],"common/tool_manager":[function(require,module,exports){
var $, $$1, ActionTool, Backbone, GestureTool, HasProperties, HelpTool, InspectTool, ToolManager, ToolManagerView, _, logger, 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");

Backbone = require("backbone");

ActionTool = require("../tool/actions/action_tool");

HelpTool = require("../tool/actions/help_tool");

GestureTool = require("../tool/gestures/gesture_tool");

InspectTool = require("../tool/inspectors/inspect_tool");

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

toolbar_template = require("./toolbar_template");

HasProperties = require("./has_properties");

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

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

  ToolManagerView.prototype.template = toolbar_template;

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

  ToolManagerView.prototype.render = function() {
    var anchor, button_bar_list, et, gestures, inspectors, ul;
    this.$el.html(this.template(this.model.attributes));
    this.$el.addClass("bk-sidebar");
    this.$el.addClass("bk-toolbar-active");
    button_bar_list = this.$('.bk-button-bar-list');
    inspectors = this.model.get('inspectors');
    button_bar_list = this.$(".bk-bs-dropdown[type='inspectors']");
    if (inspectors.length === 0) {
      button_bar_list.hide();
    } else {
      anchor = $('<a href="#" data-bk-bs-toggle="dropdown" class="bk-bs-dropdown-toggle">inspect <span class="bk-bs-caret"></a>');
      anchor.appendTo(button_bar_list);
      ul = $('<ul class="bk-bs-dropdown-menu" />');
      _.each(inspectors, function(tool) {
        var item;
        item = $('<li />');
        item.append(new InspectTool.ListItemView({
          model: tool
        }).el);
        return item.appendTo(ul);
      });
      ul.on('click', function(e) {
        return e.stopPropagation();
      });
      ul.appendTo(button_bar_list);
      anchor.dropdown();
    }
    button_bar_list = this.$(".bk-button-bar-list[type='help']");
    _.each(this.model.get('help'), function(item) {
      return button_bar_list.append(new ActionTool.ButtonView({
        model: item
      }).el);
    });
    button_bar_list = this.$(".bk-button-bar-list[type='actions']");
    _.each(this.model.get('actions'), function(item) {
      return button_bar_list.append(new ActionTool.ButtonView({
        model: item
      }).el);
    });
    gestures = this.model.get('gestures');
    for (et in gestures) {
      button_bar_list = this.$(".bk-button-bar-list[type='" + et + "']");
      _.each(gestures[et].tools, function(item) {
        return button_bar_list.append(new GestureTool.ButtonView({
          model: item
        }).el);
      });
    }
    return this;
  };

  return ToolManagerView;

})(Backbone.View);

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

  function ToolManager() {
    this._active_change = bind(this._active_change, this);
    return ToolManager.__super__.constructor.apply(this, arguments);
  }

  ToolManager.prototype.type = 'ToolManager';

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

  ToolManager.prototype.serializable_in_document = function() {
    return false;
  };

  ToolManager.prototype._init_tools = function() {
    var actions, et, gestures, help, i, inspectors, len, ref, results, tool, tools;
    gestures = this.get('gestures');
    ref = this.get('tools');
    for (i = 0, len = ref.length; i < len; i++) {
      tool = ref[i];
      if (tool instanceof InspectTool.Model) {
        inspectors = this.get('inspectors');
        inspectors.push(tool);
        this.set('inspectors', inspectors);
      } else if (tool instanceof HelpTool.Model) {
        help = this.get('help');
        help.push(tool);
        this.set('help', help);
      } else if (tool instanceof ActionTool.Model) {
        actions = this.get('actions');
        actions.push(tool);
        this.set('actions', actions);
      } else if (tool instanceof GestureTool.Model) {
        et = tool.get('event_type');
        if (!(et in gestures)) {
          logger.warn("ToolManager: unknown event type '" + et + "' for tool: " + tool.type + " (" + tool.id + ")");
          continue;
        }
        gestures[et].tools.push(tool);
        this.listenTo(tool, 'change:active', _.bind(this._active_change, tool));
      }
    }
    results = [];
    for (et in gestures) {
      tools = gestures[et].tools;
      if (tools.length === 0) {
        continue;
      }
      gestures[et].tools = _.sortBy(tools, function(tool) {
        return tool.get('default_order');
      });
      if (et !== 'pinch' && et !== 'scroll') {
        results.push(gestures[et].tools[0].set('active', true));
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  ToolManager.prototype._active_change = function(tool) {
    var currently_active_tool, event_type, gestures;
    event_type = tool.get('event_type');
    gestures = this.get('gestures');
    currently_active_tool = gestures[event_type].active;
    if ((currently_active_tool != null) && currently_active_tool !== tool) {
      logger.debug("ToolManager: deactivating tool: " + currently_active_tool.type + " (" + currently_active_tool.id + ") for event type '" + event_type + "'");
      currently_active_tool.set('active', false);
    }
    gestures[event_type].active = tool;
    this.set('gestures', gestures);
    logger.debug("ToolManager: activating tool: " + tool.type + " (" + tool.id + ") for event type '" + event_type + "'");
    return null;
  };

  ToolManager.prototype.defaults = function() {
    return {
      gestures: {
        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: [],
      inspectors: [],
      help: []
    };
  };

  return ToolManager;

})(HasProperties);

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


},{"../tool/actions/action_tool":"tool/actions/action_tool","../tool/actions/help_tool":"tool/actions/help_tool","../tool/gestures/gesture_tool":"tool/gestures/gesture_tool","../tool/inspectors/inspect_tool":"tool/inspectors/inspect_tool","./has_properties":"common/has_properties","./logging":"common/logging","./toolbar_template":"common/toolbar_template","backbone":"backbone","bootstrap/dropdown":"bootstrap/dropdown","jquery":"jquery","underscore":"underscore"}],"common/toolbar_template":[function(require,module,exports){
module.exports = function(__obj) {
  if (!__obj) __obj = {};
  var __out = [], __capture = function(callback) {
    var out = __out, result;
    __out = [];
    callback.call(this);
    result = __out.join('');
    __out = out;
    return __safe(result);
  }, __sanitize = function(value) {
    if (value && value.ecoSafe) {
      return value;
    } else if (typeof value !== 'undefined' && value != null) {
      return __escape(value);
    } else {
      return '';
    }
  }, __safe, __objSafe = __obj.safe, __escape = __obj.escape;
  __safe = __obj.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;
    }
  };
  if (!__escape) {
    __escape = __obj.escape = function(value) {
      return ('' + value)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;');
    };
  }
  (function() {
    (function() {
      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');
    
    }).call(this);
    
  }).call(__obj);
  __obj.safe = __objSafe, __obj.escape = __escape;
  return __out.join('');
}
},{}],"common/ui_events":[function(require,module,exports){
var $, Backbone, Hammer, UIEvents, logger, mousewheel,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

$ = require("jquery");

Backbone = require("backbone");

Hammer = require("hammerjs");

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

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

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

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

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

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

  UIEvents.prototype.register_tool = function(tool_view) {
    var et, id, type;
    et = tool_view.mget('event_type');
    id = tool_view.mget('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'");
      return tool_view.listenTo(this, "doubletap", tool_view._doubletap);
    }
  };

  UIEvents.prototype._trigger = function(event_type, e) {
    var active_tool, base_event_type, gestures, tm;
    tm = this.get('tool_manager');
    base_event_type = event_type.split(":")[0];
    gestures = tm.get('gestures');
    active_tool = gestures[base_event_type].active;
    if (active_tool != null) {
      return this._trigger_event(event_type, active_tool, e);
    }
  };

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  return UIEvents;

})(Backbone.Model);

module.exports = UIEvents;


},{"./logging":"common/logging","backbone":"backbone","hammerjs":"hammerjs/hammer","jquery":"jquery","jquery-mousewheel":"jquery-mousewheel"}],"main":[function(require,module,exports){
var Bokeh, logging;

Bokeh = {};

Bokeh.require = require;

Bokeh.version = '0.10.0';

Bokeh._ = require("underscore");

Bokeh.$ = require("jquery");

Bokeh.Backbone = require("backbone");

Bokeh.Backbone.$ = Bokeh.$;

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

Bokeh.logger = logging.logger;

Bokeh.set_log_level = logging.set_log_level;

if (!window.Float64Array) {
  Bokeh.logger.warn("Float64Array is not supported. Using generic Array instead.");
  window.Float64Array = Array;
}

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

Bokeh.Collections = require("./common/base").Collections;

Bokeh.Config = require("./common/base").Config;

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

Bokeh.CartesianFrame = require("./common/cartesian_frame");

Bokeh.Canvas = require("./common/canvas");

Bokeh.GMapPlot = require("./common/gmap_plot");

Bokeh.GeoJSPlot = require("./common/geojs_plot");

Bokeh.GridPlot = require("./common/grid_plot");

Bokeh.HasParent = require("./common/has_parent");

Bokeh.HasProperties = require("./common/has_properties");

Bokeh.LayoutBox = require("./common/layout_box");

Bokeh.Plot = require("./common/plot");

Bokeh.Properties = require("./common/properties");

Bokeh.SelectionManager = require("./common/selection_manager");

Bokeh.Selector = require("./common/selector");

Bokeh.ToolEvents = require("./common/tool_events");

Bokeh.build_views = require("./common/build_views");

Bokeh.ContinuumView = require("./common/continuum_view");

Bokeh.PlotWidget = require("./common/plot_widget");

Bokeh.Random = require("./common/random");

Bokeh.SVGColors = require("./common/svg_colors");

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

Bokeh.LinearMapper = require("./mapper/linear_mapper");

Bokeh.LogMapper = require("./mapper/log_mapper");

Bokeh.CategoricalMapper = require("./mapper/categorical_mapper");

Bokeh.GridMapper = require("./mapper/grid_mapper");

Bokeh.LinearColorMapper = require("./mapper/linear_color_mapper");

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

Bokeh.BoxAnnotation = require("./renderer/annotation/box_annotation");

Bokeh.Legend = require("./renderer/annotation/legend");

Bokeh.Span = require("./renderer/annotation/span");

Bokeh.Tooltip = require("./renderer/annotation/tooltip");

Bokeh.CategoricalAxis = require("./renderer/guide/categorical_axis");

Bokeh.DatetimeAxis = require("./renderer/guide/datetime_axis");

Bokeh.Grid = require("./renderer/guide/grid");

Bokeh.LinearAxis = require("./renderer/guide/linear_axis");

Bokeh.LogAxis = require("./renderer/guide/log_axis");

Bokeh.BoxSelection = require("./renderer/overlay/box_selection");

Bokeh.PolySelection = require("./renderer/overlay/poly_selection");

Bokeh.ColumnDataSource = require("./source/column_data_source");

Bokeh.AbstractTicker = require("./ticking/abstract_ticker");

Bokeh.AdaptiveTicker = require("./ticking/adaptive_ticker");

Bokeh.BasicTicker = require("./ticking/basic_ticker");

Bokeh.BasicTickFormatter = require("./ticking/basic_tick_formatter");

Bokeh.LogTicker = require("./ticking/log_ticker");

Bokeh.LogTickFormatter = require("./ticking/log_tick_formatter");

Bokeh.CategoricalTicker = require("./ticking/categorical_ticker");

Bokeh.CategoricalTickFormatter = require("./ticking/categorical_tick_formatter");

Bokeh.CompositeTicker = require("./ticking/composite_ticker");

Bokeh.DatetimeTicker = require("./ticking/datetime_ticker");

Bokeh.DatetimeTickFormatter = require("./ticking/datetime_tick_formatter");

Bokeh.DaysTicker = require("./ticking/days_ticker");

Bokeh.MonthsTicker = require("./ticking/months_ticker");

Bokeh.SingleIntervalTicker = require("./ticking/single_interval_ticker");

Bokeh.YearsTicker = require("./ticking/years_ticker");

Bokeh.ActionTool = require("./tool/actions/action_tool");

Bokeh.PreviewSaveTool = require("./tool/actions/preview_save_tool");

Bokeh.ResetTool = require("./tool/actions/reset_tool");

Bokeh.HelpTool = require("./tool/actions/help_tool");

Bokeh.BoxSelectTool = require("./tool/gestures/box_select_tool");

Bokeh.BoxZoomTool = require("./tool/gestures/box_zoom_tool");

Bokeh.LassoSelectTool = require("./tool/gestures/lasso_select_tool");

Bokeh.PanTool = require("./tool/gestures/pan_tool");

Bokeh.PolySelectTool = require("./tool/gestures/poly_select_tool");

Bokeh.ResizeTool = require("./tool/gestures/resize_tool");

Bokeh.SelectTool = require("./tool/gestures/select_tool");

Bokeh.TapTool = require("./tool/gestures/tap_tool");

Bokeh.WheelZoomTool = require("./tool/gestures/wheel_zoom_tool");

Bokeh.InspectTool = require("./tool/inspectors/inspect_tool");

Bokeh.HoverTool = require("./tool/inspectors/hover_tool");

Bokeh.CrosshairTool = require("./tool/inspectors/crosshair_tool");

require("./api/plugin");

Bokeh.Bokeh = Bokeh;

window.Bokeh = Bokeh;

module.exports = Bokeh;


},{"./api/plugin":"api/plugin","./common/base":"common/base","./common/build_views":"common/build_views","./common/canvas":"common/canvas","./common/cartesian_frame":"common/cartesian_frame","./common/continuum_view":"common/continuum_view","./common/document":"common/document","./common/embed":"common/embed","./common/geojs_plot":"common/geojs_plot","./common/gmap_plot":"common/gmap_plot","./common/grid_plot":"common/grid_plot","./common/has_parent":"common/has_parent","./common/has_properties":"common/has_properties","./common/layout_box":"common/layout_box","./common/logging":"common/logging","./common/plot":"common/plot","./common/plot_widget":"common/plot_widget","./common/properties":"common/properties","./common/random":"common/random","./common/selection_manager":"common/selection_manager","./common/selector":"common/selector","./common/svg_colors":"common/svg_colors","./common/tool_events":"common/tool_events","./mapper/categorical_mapper":"mapper/categorical_mapper","./mapper/grid_mapper":"mapper/grid_mapper","./mapper/linear_color_mapper":"mapper/linear_color_mapper","./mapper/linear_mapper":"mapper/linear_mapper","./mapper/log_mapper":"mapper/log_mapper","./palettes/palettes":"palettes/palettes","./renderer/annotation/box_annotation":"renderer/annotation/box_annotation","./renderer/annotation/legend":"renderer/annotation/legend","./renderer/annotation/span":"renderer/annotation/span","./renderer/annotation/tooltip":"renderer/annotation/tooltip","./renderer/guide/categorical_axis":"renderer/guide/categorical_axis","./renderer/guide/datetime_axis":"renderer/guide/datetime_axis","./renderer/guide/grid":"renderer/guide/grid","./renderer/guide/linear_axis":"renderer/guide/linear_axis","./renderer/guide/log_axis":"renderer/guide/log_axis","./renderer/overlay/box_selection":"renderer/overlay/box_selection","./renderer/overlay/poly_selection":"renderer/overlay/poly_selection","./source/column_data_source":"source/column_data_source","./ticking/abstract_ticker":"ticking/abstract_ticker","./ticking/adaptive_ticker":"ticking/adaptive_ticker","./ticking/basic_tick_formatter":"ticking/basic_tick_formatter","./ticking/basic_ticker":"ticking/basic_ticker","./ticking/categorical_tick_formatter":"ticking/categorical_tick_formatter","./ticking/categorical_ticker":"ticking/categorical_ticker","./ticking/composite_ticker":"ticking/composite_ticker","./ticking/datetime_tick_formatter":"ticking/datetime_tick_formatter","./ticking/datetime_ticker":"ticking/datetime_ticker","./ticking/days_ticker":"ticking/days_ticker","./ticking/log_tick_formatter":"ticking/log_tick_formatter","./ticking/log_ticker":"ticking/log_ticker","./ticking/months_ticker":"ticking/months_ticker","./ticking/single_interval_ticker":"ticking/single_interval_ticker","./ticking/years_ticker":"ticking/years_ticker","./tool/actions/action_tool":"tool/actions/action_tool","./tool/actions/help_tool":"tool/actions/help_tool","./tool/actions/preview_save_tool":"tool/actions/preview_save_tool","./tool/actions/reset_tool":"tool/actions/reset_tool","./tool/gestures/box_select_tool":"tool/gestures/box_select_tool","./tool/gestures/box_zoom_tool":"tool/gestures/box_zoom_tool","./tool/gestures/lasso_select_tool":"tool/gestures/lasso_select_tool","./tool/gestures/pan_tool":"tool/gestures/pan_tool","./tool/gestures/poly_select_tool":"tool/gestures/poly_select_tool","./tool/gestures/resize_tool":"tool/gestures/resize_tool","./tool/gestures/select_tool":"tool/gestures/select_tool","./tool/gestures/tap_tool":"tool/gestures/tap_tool","./tool/gestures/wheel_zoom_tool":"tool/gestures/wheel_zoom_tool","./tool/inspectors/crosshair_tool":"tool/inspectors/crosshair_tool","./tool/inspectors/hover_tool":"tool/inspectors/hover_tool","./tool/inspectors/inspect_tool":"tool/inspectors/inspect_tool","backbone":"backbone","jquery":"jquery","underscore":"underscore"}],"mapper/categorical_mapper":[function(require,module,exports){
var CategoricalMapper, LinearMapper, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

LinearMapper = require("./linear_mapper");

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

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

  CategoricalMapper.prototype.map_to_target = function(x, return_synthetic) {
    var factor, factors, percent, range, ref, result;
    if (return_synthetic == null) {
      return_synthetic = false;
    }
    if (_.isNumber(x)) {
      if (return_synthetic) {
        return x;
      } else {
        return CategoricalMapper.__super__.map_to_target.call(this, x);
      }
    }
    range = this.get('source_range');
    factors = range.get('factors');
    if (x.indexOf(':') >= 0) {
      ref = x.split(':'), factor = ref[0], percent = ref[1];
      percent = parseFloat(percent);
      result = factors.indexOf(factor) + 0.5 + range.get('offset') + percent;
    } else {
      result = factors.indexOf(x) + 1 + range.get('offset');
    }
    if (return_synthetic) {
      return result;
    } else {
      return CategoricalMapper.__super__.map_to_target.call(this, result);
    }
  };

  CategoricalMapper.prototype.v_map_to_target = function(xs, return_synthetic) {
    var factor, factors, i, j, percent, range, ref, ref1, results, x;
    if (return_synthetic == null) {
      return_synthetic = false;
    }
    if (_.isNumber(xs[0])) {
      if (return_synthetic) {
        return xs;
      } else {
        return CategoricalMapper.__super__.v_map_to_target.call(this, xs);
      }
    }
    range = this.get('source_range');
    factors = range.get('factors');
    results = Array(xs.length);
    for (i = j = 0, ref = xs.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      x = xs[i];
      if (x.indexOf(':') >= 0) {
        ref1 = x.split(':'), factor = ref1[0], percent = ref1[1];
        percent = parseFloat(percent);
        results[i] = factors.indexOf(factor) + 0.5 + range.get('offset') + percent;
      } else {
        results[i] = factors.indexOf(x) + 1 + range.get('offset');
      }
    }
    if (return_synthetic) {
      return results;
    } else {
      return CategoricalMapper.__super__.v_map_to_target.call(this, results);
    }
  };

  CategoricalMapper.prototype.map_from_target = function(xprime, skip_cat) {
    var factors, range;
    if (skip_cat == null) {
      skip_cat = false;
    }
    xprime = CategoricalMapper.__super__.map_from_target.call(this, xprime);
    if (skip_cat) {
      return xprime;
    }
    range = this.get('source_range');
    factors = range.get('factors');
    return factors[Math.floor(xprime - 0.5 - range.get('offset'))];
  };

  CategoricalMapper.prototype.v_map_from_target = function(xprimes, skip_cat) {
    var factors, i, j, k, range, ref, ref1, result, x;
    if (skip_cat == null) {
      skip_cat = false;
    }
    x = CategoricalMapper.__super__.v_map_from_target.call(this, xprimes);
    for (i = j = 0, ref = x.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      x[i] = x[i];
    }
    if (skip_cat) {
      return x;
    }
    result = Array(x);
    range = this.get('source_range');
    factors = range.get('factors');
    for (i = k = 0, ref1 = xprimes.length; 0 <= ref1 ? k < ref1 : k > ref1; i = 0 <= ref1 ? ++k : --k) {
      result[i] = factors[Math.floor(x[i] - 0.5 - range.get('offset'))];
    }
    return result;
  };

  return CategoricalMapper;

})(LinearMapper.Model);

module.exports = {
  Model: CategoricalMapper
};


},{"./linear_mapper":"mapper/linear_mapper","underscore":"underscore"}],"mapper/grid_mapper":[function(require,module,exports){
var GridMapper, HasProperties,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

HasProperties = require("../common/has_properties");

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

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

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

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

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

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

  return GridMapper;

})(HasProperties);

module.exports = {
  Model: GridMapper
};


},{"../common/has_properties":"common/has_properties"}],"mapper/linear_color_mapper":[function(require,module,exports){
var HasProperties, LinearColorMapper, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

HasProperties = require("../common/has_properties");

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

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

  LinearColorMapper.prototype.initialize = function(attrs, options) {
    LinearColorMapper.__super__.initialize.call(this, attrs, options);
    this.palette = this._build_palette(this.get('palette'));
    this.little_endian = this._is_little_endian();
    if (this.get('reserve_color') != null) {
      this.reserve_color = parseInt(this.get('reserve_color').slice(1), 16);
      return this.reserve_val = this.get('reserve_val');
    }
  };

  LinearColorMapper.prototype.v_map_screen = function(data) {
    var N, buf, color, d, high, i, j, k, low, offset, ref, ref1, ref2, ref3, scale, value;
    buf = new ArrayBuffer(data.length * 4);
    color = new Uint32Array(buf);
    low = (ref = this.get('low')) != null ? ref : _.min(data);
    high = (ref1 = this.get('high')) != null ? ref1 : _.max(data);
    N = this.palette.length - 1;
    scale = N / (high - low);
    offset = -scale * low;
    if (this.little_endian) {
      for (i = j = 0, ref2 = data.length; 0 <= ref2 ? j < ref2 : j > ref2; i = 0 <= ref2 ? ++j : --j) {
        d = data[i];
        if (d === this.reserve_val) {
          value = this.reserve_color;
        } else {
          if (d > high) {
            d = high;
          }
          if (d < low) {
            d = low;
          }
          value = this.palette[Math.floor(d * scale + offset)];
        }
        color[i] = (0xff << 24) | ((value & 0xff0000) >> 16) | (value & 0xff00) | ((value & 0xff) << 16);
      }
    } else {
      for (i = k = 0, ref3 = data.length; 0 <= ref3 ? k < ref3 : k > ref3; i = 0 <= ref3 ? ++k : --k) {
        d = data[i];
        if (d === this.reserve_val) {
          value = this.reserve_color;
        } else {
          if (d > high) {
            d = high;
          }
          if (d < low) {
            d = low;
          }
          value = this.palette[Math.floor(d * scale + offset)];
        }
        color[i] = (value << 8) | 0xff;
      }
    }
    return buf;
  };

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

  LinearColorMapper.prototype._build_palette = function(palette) {
    var _convert, i, j, new_palette, ref;
    new_palette = new Uint32Array(palette.length + 1);
    _convert = function(value) {
      if (_.isNumber(value)) {
        return value;
      } else {
        return parseInt(value.slice(1), 16);
      }
    };
    for (i = j = 0, ref = palette.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      new_palette[i] = _convert(palette[i]);
    }
    new_palette[new_palette.length - 1] = _convert(palette[palette.length - 1]);
    return new_palette;
  };

  return LinearColorMapper;

})(HasProperties);

module.exports = {
  Model: LinearColorMapper
};


},{"../common/has_properties":"common/has_properties","underscore":"underscore"}],"mapper/linear_mapper":[function(require,module,exports){
var HasProperties, 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;

HasProperties = require("../common/has_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.register_property('mapper_state', this._mapper_state, true);
    this.add_dependencies('mapper_state', this, ['source_range', 'target_range']);
    this.add_dependencies('mapper_state', this.get('source_range'), ['start', 'end']);
    return this.add_dependencies('mapper_state', this.get('target_range'), ['start', 'end']);
  };

  LinearMapper.prototype.map_to_target = function(x) {
    var offset, ref, scale;
    ref = this.get('mapper_state'), scale = ref[0], offset = ref[1];
    return scale * x + offset;
  };

  LinearMapper.prototype.v_map_to_target = function(xs) {
    var i, idx, len, offset, ref, result, scale, x;
    ref = this.get('mapper_state'), scale = ref[0], offset = ref[1];
    result = new Float64Array(xs.length);
    for (idx = i = 0, len = xs.length; i < len; idx = ++i) {
      x = xs[idx];
      result[idx] = scale * x + offset;
    }
    return result;
  };

  LinearMapper.prototype.map_from_target = function(xprime) {
    var offset, ref, scale;
    ref = this.get('mapper_state'), scale = ref[0], offset = ref[1];
    return (xprime - offset) / scale;
  };

  LinearMapper.prototype.v_map_from_target = function(xprimes) {
    var i, idx, len, offset, ref, result, scale, xprime;
    ref = this.get('mapper_state'), scale = ref[0], offset = ref[1];
    result = new Float64Array(xprimes.length);
    for (idx = i = 0, len = xprimes.length; i < len; idx = ++i) {
      xprime = xprimes[idx];
      result[idx] = (xprime - offset) / scale;
    }
    return result;
  };

  LinearMapper.prototype._mapper_state = function() {
    var offset, scale, source_end, source_start, target_end, target_start;
    source_start = this.get('source_range').get('start');
    source_end = this.get('source_range').get('end');
    target_start = this.get('target_range').get('start');
    target_end = this.get('target_range').get('end');
    scale = (target_end - target_start) / (source_end - source_start);
    offset = -(scale * source_start) + target_start;
    return [scale, offset];
  };

  return LinearMapper;

})(HasProperties);

module.exports = {
  Model: LinearMapper
};


},{"../common/has_properties":"common/has_properties"}],"mapper/log_mapper":[function(require,module,exports){
var HasProperties, LogMapper,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

HasProperties = require("../common/has_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.register_property('mapper_state', this._mapper_state, true);
    this.add_dependencies('mapper_state', this, ['source_range', 'target_range']);
    this.add_dependencies('mapper_state', this.get('source_range'), ['start', 'end']);
    return this.add_dependencies('mapper_state', this.get('target_range'), ['start', 'end']);
  };

  LogMapper.prototype.map_to_target = function(x) {
    var inter_offset, inter_scale, intermediate, offset, ref, result, scale;
    ref = this.get('mapper_state'), scale = ref[0], offset = ref[1], inter_scale = ref[2], inter_offset = ref[3];
    result = 0;
    if (inter_scale === 0) {
      intermediate = 0;
    } else {
      intermediate = (Math.log(x) - inter_offset) / inter_scale;
      if (isNaN(intermediate) || !isFinite(intermediate)) {
        intermediate = 0;
      }
    }
    result = intermediate * scale + offset;
    return result;
  };

  LogMapper.prototype.v_map_to_target = function(xs) {
    var idx, inter_offset, inter_scale, intermediate, j, k, len, len1, offset, ref, result, scale, x;
    ref = this.get('mapper_state'), scale = ref[0], offset = ref[1], inter_scale = ref[2], inter_offset = ref[3];
    result = new Float64Array(xs.length);
    if (inter_scale === 0) {
      intermediate = xs.map(function(i) {
        return 0;
      });
    } else {
      intermediate = xs.map(function(i) {
        return (Math.log(i) - inter_offset) / inter_scale;
      });
      for (idx = j = 0, len = intermediate.length; j < len; idx = ++j) {
        x = intermediate[idx];
        if (isNaN(intermediate[idx]) || !isFinite(intermediate[idx])) {
          intermediate[idx] = 0;
        }
      }
    }
    for (idx = k = 0, len1 = xs.length; k < len1; idx = ++k) {
      x = xs[idx];
      result[idx] = intermediate[idx] * scale + offset;
    }
    return result;
  };

  LogMapper.prototype.map_from_target = function(xprime) {
    var inter_offset, inter_scale, intermediate, offset, ref, scale;
    ref = this.get('mapper_state'), scale = ref[0], offset = ref[1], inter_scale = ref[2], inter_offset = ref[3];
    intermediate = (xprime - offset) / scale;
    intermediate = Math.exp(inter_scale * intermediate + inter_offset);
    return intermediate;
  };

  LogMapper.prototype.v_map_from_target = function(xprimes) {
    var idx, inter_offset, inter_scale, intermediate, j, len, offset, ref, result, scale, x;
    result = new Float64Array(xprimes.length);
    ref = this.get('mapper_state'), scale = ref[0], offset = ref[1], inter_scale = ref[2], inter_offset = ref[3];
    intermediate = xprimes.map(function(i) {
      return (i - offset) / scale;
    });
    for (idx = j = 0, len = xprimes.length; j < len; idx = ++j) {
      x = xprimes[idx];
      result[idx] = Math.exp(inter_scale * intermediate[idx] + inter_offset);
    }
    return result;
  };

  LogMapper.prototype._get_safe_scale = function(orig_start, orig_end) {
    var end, log_val, ref, start;
    if (orig_start < 0) {
      start = 0;
    } else {
      start = orig_start;
    }
    if (orig_end < 0) {
      end = 0;
    } else {
      end = orig_end;
    }
    if (start === end) {
      if (start === 0) {
        ref = [1, 10], start = ref[0], end = ref[1];
      } else {
        log_val = Math.log(start) / Math.log(10);
        start = Math.pow(10, Math.floor(log_val));
        if (Math.ceil(log_val) !== Math.floor(log_val)) {
          end = Math.pow(10, Math.ceil(log_val));
        } else {
          end = Math.pow(10, Math.ceil(log_val) + 1);
        }
      }
    }
    return [start, end];
  };

  LogMapper.prototype._mapper_state = function() {
    var end, inter_offset, inter_scale, offset, ref, scale, screen_range, source_end, source_start, start, target_end, target_start;
    source_start = this.get('source_range').get('start');
    source_end = this.get('source_range').get('end');
    target_start = this.get('target_range').get('start');
    target_end = this.get('target_range').get('end');
    screen_range = target_end - target_start;
    ref = this._get_safe_scale(source_start, source_end), start = ref[0], end = ref[1];
    if (start === 0) {
      inter_scale = Math.log(end);
      inter_offset = 0;
    } else {
      inter_scale = Math.log(end) - Math.log(start);
      inter_offset = Math.log(start);
    }
    scale = screen_range;
    offset = target_start;
    return [scale, offset, inter_scale, inter_offset];
  };

  return LogMapper;

})(HasProperties);

module.exports = {
  Model: LogMapper
};


},{"../common/has_properties":"common/has_properties"}],"palettes/palettes":[function(require,module,exports){
module.exports = {
  YlGn3: [0x31a354, 0xaddd8e, 0xf7fcb9],
  YlGn4: [0x238443, 0x78c679, 0xc2e699, 0xffffcc],
  YlGn5: [0x006837, 0x31a354, 0x78c679, 0xc2e699, 0xffffcc],
  YlGn6: [0x006837, 0x31a354, 0x78c679, 0xaddd8e, 0xd9f0a3, 0xffffcc],
  YlGn7: [0x005a32, 0x238443, 0x41ab5d, 0x78c679, 0xaddd8e, 0xd9f0a3, 0xffffcc],
  YlGn8: [0x005a32, 0x238443, 0x41ab5d, 0x78c679, 0xaddd8e, 0xd9f0a3, 0xf7fcb9, 0xffffe5],
  YlGn9: [0x004529, 0x006837, 0x238443, 0x41ab5d, 0x78c679, 0xaddd8e, 0xd9f0a3, 0xf7fcb9, 0xffffe5],
  YlGnBu3: [0x2c7fb8, 0x7fcdbb, 0xedf8b1],
  YlGnBu4: [0x225ea8, 0x41b6c4, 0xa1dab4, 0xffffcc],
  YlGnBu5: [0x253494, 0x2c7fb8, 0x41b6c4, 0xa1dab4, 0xffffcc],
  YlGnBu6: [0x253494, 0x2c7fb8, 0x41b6c4, 0x7fcdbb, 0xc7e9b4, 0xffffcc],
  YlGnBu7: [0x0c2c84, 0x225ea8, 0x1d91c0, 0x41b6c4, 0x7fcdbb, 0xc7e9b4, 0xffffcc],
  YlGnBu8: [0x0c2c84, 0x225ea8, 0x1d91c0, 0x41b6c4, 0x7fcdbb, 0xc7e9b4, 0xedf8b1, 0xffffd9],
  YlGnBu9: [0x081d58, 0x253494, 0x225ea8, 0x1d91c0, 0x41b6c4, 0x7fcdbb, 0xc7e9b4, 0xedf8b1, 0xffffd9],
  GnBu3: [0x43a2ca, 0xa8ddb5, 0xe0f3db],
  GnBu4: [0x2b8cbe, 0x7bccc4, 0xbae4bc, 0xf0f9e8],
  GnBu5: [0x0868ac, 0x43a2ca, 0x7bccc4, 0xbae4bc, 0xf0f9e8],
  GnBu6: [0x0868ac, 0x43a2ca, 0x7bccc4, 0xa8ddb5, 0xccebc5, 0xf0f9e8],
  GnBu7: [0x08589e, 0x2b8cbe, 0x4eb3d3, 0x7bccc4, 0xa8ddb5, 0xccebc5, 0xf0f9e8],
  GnBu8: [0x08589e, 0x2b8cbe, 0x4eb3d3, 0x7bccc4, 0xa8ddb5, 0xccebc5, 0xe0f3db, 0xf7fcf0],
  GnBu9: [0x084081, 0x0868ac, 0x2b8cbe, 0x4eb3d3, 0x7bccc4, 0xa8ddb5, 0xccebc5, 0xe0f3db, 0xf7fcf0],
  BuGn3: [0x2ca25f, 0x99d8c9, 0xe5f5f9],
  BuGn4: [0x238b45, 0x66c2a4, 0xb2e2e2, 0xedf8fb],
  BuGn5: [0x006d2c, 0x2ca25f, 0x66c2a4, 0xb2e2e2, 0xedf8fb],
  BuGn6: [0x006d2c, 0x2ca25f, 0x66c2a4, 0x99d8c9, 0xccece6, 0xedf8fb],
  BuGn7: [0x005824, 0x238b45, 0x41ae76, 0x66c2a4, 0x99d8c9, 0xccece6, 0xedf8fb],
  BuGn8: [0x005824, 0x238b45, 0x41ae76, 0x66c2a4, 0x99d8c9, 0xccece6, 0xe5f5f9, 0xf7fcfd],
  BuGn9: [0x00441b, 0x006d2c, 0x238b45, 0x41ae76, 0x66c2a4, 0x99d8c9, 0xccece6, 0xe5f5f9, 0xf7fcfd],
  PuBuGn3: [0x1c9099, 0xa6bddb, 0xece2f0],
  PuBuGn4: [0x02818a, 0x67a9cf, 0xbdc9e1, 0xf6eff7],
  PuBuGn5: [0x016c59, 0x1c9099, 0x67a9cf, 0xbdc9e1, 0xf6eff7],
  PuBuGn6: [0x016c59, 0x1c9099, 0x67a9cf, 0xa6bddb, 0xd0d1e6, 0xf6eff7],
  PuBuGn7: [0x016450, 0x02818a, 0x3690c0, 0x67a9cf, 0xa6bddb, 0xd0d1e6, 0xf6eff7],
  PuBuGn8: [0x016450, 0x02818a, 0x3690c0, 0x67a9cf, 0xa6bddb, 0xd0d1e6, 0xece2f0, 0xfff7fb],
  PuBuGn9: [0x014636, 0x016c59, 0x02818a, 0x3690c0, 0x67a9cf, 0xa6bddb, 0xd0d1e6, 0xece2f0, 0xfff7fb],
  PuBu3: [0x2b8cbe, 0xa6bddb, 0xece7f2],
  PuBu4: [0x0570b0, 0x74a9cf, 0xbdc9e1, 0xf1eef6],
  PuBu5: [0x045a8d, 0x2b8cbe, 0x74a9cf, 0xbdc9e1, 0xf1eef6],
  PuBu6: [0x045a8d, 0x2b8cbe, 0x74a9cf, 0xa6bddb, 0xd0d1e6, 0xf1eef6],
  PuBu7: [0x034e7b, 0x0570b0, 0x3690c0, 0x74a9cf, 0xa6bddb, 0xd0d1e6, 0xf1eef6],
  PuBu8: [0x034e7b, 0x0570b0, 0x3690c0, 0x74a9cf, 0xa6bddb, 0xd0d1e6, 0xece7f2, 0xfff7fb],
  PuBu9: [0x023858, 0x045a8d, 0x0570b0, 0x3690c0, 0x74a9cf, 0xa6bddb, 0xd0d1e6, 0xece7f2, 0xfff7fb],
  BuPu3: [0x8856a7, 0x9ebcda, 0xe0ecf4],
  BuPu4: [0x88419d, 0x8c96c6, 0xb3cde3, 0xedf8fb],
  BuPu5: [0x810f7c, 0x8856a7, 0x8c96c6, 0xb3cde3, 0xedf8fb],
  BuPu6: [0x810f7c, 0x8856a7, 0x8c96c6, 0x9ebcda, 0xbfd3e6, 0xedf8fb],
  BuPu7: [0x6e016b, 0x88419d, 0x8c6bb1, 0x8c96c6, 0x9ebcda, 0xbfd3e6, 0xedf8fb],
  BuPu8: [0x6e016b, 0x88419d, 0x8c6bb1, 0x8c96c6, 0x9ebcda, 0xbfd3e6, 0xe0ecf4, 0xf7fcfd],
  BuPu9: [0x4d004b, 0x810f7c, 0x88419d, 0x8c6bb1, 0x8c96c6, 0x9ebcda, 0xbfd3e6, 0xe0ecf4, 0xf7fcfd],
  RdPu3: [0xc51b8a, 0xfa9fb5, 0xfde0dd],
  RdPu4: [0xae017e, 0xf768a1, 0xfbb4b9, 0xfeebe2],
  RdPu5: [0x7a0177, 0xc51b8a, 0xf768a1, 0xfbb4b9, 0xfeebe2],
  RdPu6: [0x7a0177, 0xc51b8a, 0xf768a1, 0xfa9fb5, 0xfcc5c0, 0xfeebe2],
  RdPu7: [0x7a0177, 0xae017e, 0xdd3497, 0xf768a1, 0xfa9fb5, 0xfcc5c0, 0xfeebe2],
  RdPu8: [0x7a0177, 0xae017e, 0xdd3497, 0xf768a1, 0xfa9fb5, 0xfcc5c0, 0xfde0dd, 0xfff7f3],
  RdPu9: [0x49006a, 0x7a0177, 0xae017e, 0xdd3497, 0xf768a1, 0xfa9fb5, 0xfcc5c0, 0xfde0dd, 0xfff7f3],
  PuRd3: [0xdd1c77, 0xc994c7, 0xe7e1ef],
  PuRd4: [0xce1256, 0xdf65b0, 0xd7b5d8, 0xf1eef6],
  PuRd5: [0x980043, 0xdd1c77, 0xdf65b0, 0xd7b5d8, 0xf1eef6],
  PuRd6: [0x980043, 0xdd1c77, 0xdf65b0, 0xc994c7, 0xd4b9da, 0xf1eef6],
  PuRd7: [0x91003f, 0xce1256, 0xe7298a, 0xdf65b0, 0xc994c7, 0xd4b9da, 0xf1eef6],
  PuRd8: [0x91003f, 0xce1256, 0xe7298a, 0xdf65b0, 0xc994c7, 0xd4b9da, 0xe7e1ef, 0xf7f4f9],
  PuRd9: [0x67001f, 0x980043, 0xce1256, 0xe7298a, 0xdf65b0, 0xc994c7, 0xd4b9da, 0xe7e1ef, 0xf7f4f9],
  OrRd3: [0xe34a33, 0xfdbb84, 0xfee8c8],
  OrRd4: [0xd7301f, 0xfc8d59, 0xfdcc8a, 0xfef0d9],
  OrRd5: [0xb30000, 0xe34a33, 0xfc8d59, 0xfdcc8a, 0xfef0d9],
  OrRd6: [0xb30000, 0xe34a33, 0xfc8d59, 0xfdbb84, 0xfdd49e, 0xfef0d9],
  OrRd7: [0x990000, 0xd7301f, 0xef6548, 0xfc8d59, 0xfdbb84, 0xfdd49e, 0xfef0d9],
  OrRd8: [0x990000, 0xd7301f, 0xef6548, 0xfc8d59, 0xfdbb84, 0xfdd49e, 0xfee8c8, 0xfff7ec],
  OrRd9: [0x7f0000, 0xb30000, 0xd7301f, 0xef6548, 0xfc8d59, 0xfdbb84, 0xfdd49e, 0xfee8c8, 0xfff7ec],
  YlOrRd3: [0xf03b20, 0xfeb24c, 0xffeda0],
  YlOrRd4: [0xe31a1c, 0xfd8d3c, 0xfecc5c, 0xffffb2],
  YlOrRd5: [0xbd0026, 0xf03b20, 0xfd8d3c, 0xfecc5c, 0xffffb2],
  YlOrRd6: [0xbd0026, 0xf03b20, 0xfd8d3c, 0xfeb24c, 0xfed976, 0xffffb2],
  YlOrRd7: [0xb10026, 0xe31a1c, 0xfc4e2a, 0xfd8d3c, 0xfeb24c, 0xfed976, 0xffffb2],
  YlOrRd8: [0xb10026, 0xe31a1c, 0xfc4e2a, 0xfd8d3c, 0xfeb24c, 0xfed976, 0xffeda0, 0xffffcc],
  YlOrRd9: [0x800026, 0xbd0026, 0xe31a1c, 0xfc4e2a, 0xfd8d3c, 0xfeb24c, 0xfed976, 0xffeda0, 0xffffcc],
  YlOrBr3: [0xd95f0e, 0xfec44f, 0xfff7bc],
  YlOrBr4: [0xcc4c02, 0xfe9929, 0xfed98e, 0xffffd4],
  YlOrBr5: [0x993404, 0xd95f0e, 0xfe9929, 0xfed98e, 0xffffd4],
  YlOrBr6: [0x993404, 0xd95f0e, 0xfe9929, 0xfec44f, 0xfee391, 0xffffd4],
  YlOrBr7: [0x8c2d04, 0xcc4c02, 0xec7014, 0xfe9929, 0xfec44f, 0xfee391, 0xffffd4],
  YlOrBr8: [0x8c2d04, 0xcc4c02, 0xec7014, 0xfe9929, 0xfec44f, 0xfee391, 0xfff7bc, 0xffffe5],
  YlOrBr9: [0x662506, 0x993404, 0xcc4c02, 0xec7014, 0xfe9929, 0xfec44f, 0xfee391, 0xfff7bc, 0xffffe5],
  Purples3: [0x756bb1, 0xbcbddc, 0xefedf5],
  Purples4: [0x6a51a3, 0x9e9ac8, 0xcbc9e2, 0xf2f0f7],
  Purples5: [0x54278f, 0x756bb1, 0x9e9ac8, 0xcbc9e2, 0xf2f0f7],
  Purples6: [0x54278f, 0x756bb1, 0x9e9ac8, 0xbcbddc, 0xdadaeb, 0xf2f0f7],
  Purples7: [0x4a1486, 0x6a51a3, 0x807dba, 0x9e9ac8, 0xbcbddc, 0xdadaeb, 0xf2f0f7],
  Purples8: [0x4a1486, 0x6a51a3, 0x807dba, 0x9e9ac8, 0xbcbddc, 0xdadaeb, 0xefedf5, 0xfcfbfd],
  Purples9: [0x3f007d, 0x54278f, 0x6a51a3, 0x807dba, 0x9e9ac8, 0xbcbddc, 0xdadaeb, 0xefedf5, 0xfcfbfd],
  Blues3: [0x3182bd, 0x9ecae1, 0xdeebf7],
  Blues4: [0x2171b5, 0x6baed6, 0xbdd7e7, 0xeff3ff],
  Blues5: [0x08519c, 0x3182bd, 0x6baed6, 0xbdd7e7, 0xeff3ff],
  Blues6: [0x08519c, 0x3182bd, 0x6baed6, 0x9ecae1, 0xc6dbef, 0xeff3ff],
  Blues7: [0x084594, 0x2171b5, 0x4292c6, 0x6baed6, 0x9ecae1, 0xc6dbef, 0xeff3ff],
  Blues8: [0x084594, 0x2171b5, 0x4292c6, 0x6baed6, 0x9ecae1, 0xc6dbef, 0xdeebf7, 0xf7fbff],
  Blues9: [0x08306b, 0x08519c, 0x2171b5, 0x4292c6, 0x6baed6, 0x9ecae1, 0xc6dbef, 0xdeebf7, 0xf7fbff],
  Greens3: [0x31a354, 0xa1d99b, 0xe5f5e0],
  Greens4: [0x238b45, 0x74c476, 0xbae4b3, 0xedf8e9],
  Greens5: [0x006d2c, 0x31a354, 0x74c476, 0xbae4b3, 0xedf8e9],
  Greens6: [0x006d2c, 0x31a354, 0x74c476, 0xa1d99b, 0xc7e9c0, 0xedf8e9],
  Greens7: [0x005a32, 0x238b45, 0x41ab5d, 0x74c476, 0xa1d99b, 0xc7e9c0, 0xedf8e9],
  Greens8: [0x005a32, 0x238b45, 0x41ab5d, 0x74c476, 0xa1d99b, 0xc7e9c0, 0xe5f5e0, 0xf7fcf5],
  Greens9: [0x00441b, 0x006d2c, 0x238b45, 0x41ab5d, 0x74c476, 0xa1d99b, 0xc7e9c0, 0xe5f5e0, 0xf7fcf5],
  Oranges3: [0xe6550d, 0xfdae6b, 0xfee6ce],
  Oranges4: [0xd94701, 0xfd8d3c, 0xfdbe85, 0xfeedde],
  Oranges5: [0xa63603, 0xe6550d, 0xfd8d3c, 0xfdbe85, 0xfeedde],
  Oranges6: [0xa63603, 0xe6550d, 0xfd8d3c, 0xfdae6b, 0xfdd0a2, 0xfeedde],
  Oranges7: [0x8c2d04, 0xd94801, 0xf16913, 0xfd8d3c, 0xfdae6b, 0xfdd0a2, 0xfeedde],
  Oranges8: [0x8c2d04, 0xd94801, 0xf16913, 0xfd8d3c, 0xfdae6b, 0xfdd0a2, 0xfee6ce, 0xfff5eb],
  Oranges9: [0x7f2704, 0xa63603, 0xd94801, 0xf16913, 0xfd8d3c, 0xfdae6b, 0xfdd0a2, 0xfee6ce, 0xfff5eb],
  Reds3: [0xde2d26, 0xfc9272, 0xfee0d2],
  Reds4: [0xcb181d, 0xfb6a4a, 0xfcae91, 0xfee5d9],
  Reds5: [0xa50f15, 0xde2d26, 0xfb6a4a, 0xfcae91, 0xfee5d9],
  Reds6: [0xa50f15, 0xde2d26, 0xfb6a4a, 0xfc9272, 0xfcbba1, 0xfee5d9],
  Reds7: [0x99000d, 0xcb181d, 0xef3b2c, 0xfb6a4a, 0xfc9272, 0xfcbba1, 0xfee5d9],
  Reds8: [0x99000d, 0xcb181d, 0xef3b2c, 0xfb6a4a, 0xfc9272, 0xfcbba1, 0xfee0d2, 0xfff5f0],
  Reds9: [0x67000d, 0xa50f15, 0xcb181d, 0xef3b2c, 0xfb6a4a, 0xfc9272, 0xfcbba1, 0xfee0d2, 0xfff5f0],
  Greys3: [0x636363, 0xbdbdbd, 0xf0f0f0],
  Greys4: [0x525252, 0x969696, 0xcccccc, 0xf7f7f7],
  Greys5: [0x252525, 0x636363, 0x969696, 0xcccccc, 0xf7f7f7],
  Greys6: [0x252525, 0x636363, 0x969696, 0xbdbdbd, 0xd9d9d9, 0xf7f7f7],
  Greys7: [0x252525, 0x525252, 0x737373, 0x969696, 0xbdbdbd, 0xd9d9d9, 0xf7f7f7],
  Greys8: [0x252525, 0x525252, 0x737373, 0x969696, 0xbdbdbd, 0xd9d9d9, 0xf0f0f0, 0xffffff],
  Greys9: [0x000000, 0x252525, 0x525252, 0x737373, 0x969696, 0xbdbdbd, 0xd9d9d9, 0xf0f0f0, 0xffffff],
  PuOr3: [0x998ec3, 0xf7f7f7, 0xf1a340],
  PuOr4: [0x5e3c99, 0xb2abd2, 0xfdb863, 0xe66101],
  PuOr5: [0x5e3c99, 0xb2abd2, 0xf7f7f7, 0xfdb863, 0xe66101],
  PuOr6: [0x542788, 0x998ec3, 0xd8daeb, 0xfee0b6, 0xf1a340, 0xb35806],
  PuOr7: [0x542788, 0x998ec3, 0xd8daeb, 0xf7f7f7, 0xfee0b6, 0xf1a340, 0xb35806],
  PuOr8: [0x542788, 0x8073ac, 0xb2abd2, 0xd8daeb, 0xfee0b6, 0xfdb863, 0xe08214, 0xb35806],
  PuOr9: [0x542788, 0x8073ac, 0xb2abd2, 0xd8daeb, 0xf7f7f7, 0xfee0b6, 0xfdb863, 0xe08214, 0xb35806],
  PuOr10: [0x2d004b, 0x542788, 0x8073ac, 0xb2abd2, 0xd8daeb, 0xfee0b6, 0xfdb863, 0xe08214, 0xb35806, 0x7f3b08],
  PuOr11: [0x2d004b, 0x542788, 0x8073ac, 0xb2abd2, 0xd8daeb, 0xf7f7f7, 0xfee0b6, 0xfdb863, 0xe08214, 0xb35806, 0x7f3b08],
  BrBG3: [0x5ab4ac, 0xf5f5f5, 0xd8b365],
  BrBG4: [0x018571, 0x80cdc1, 0xdfc27d, 0xa6611a],
  BrBG5: [0x018571, 0x80cdc1, 0xf5f5f5, 0xdfc27d, 0xa6611a],
  BrBG6: [0x01665e, 0x5ab4ac, 0xc7eae5, 0xf6e8c3, 0xd8b365, 0x8c510a],
  BrBG7: [0x01665e, 0x5ab4ac, 0xc7eae5, 0xf5f5f5, 0xf6e8c3, 0xd8b365, 0x8c510a],
  BrBG8: [0x01665e, 0x35978f, 0x80cdc1, 0xc7eae5, 0xf6e8c3, 0xdfc27d, 0xbf812d, 0x8c510a],
  BrBG9: [0x01665e, 0x35978f, 0x80cdc1, 0xc7eae5, 0xf5f5f5, 0xf6e8c3, 0xdfc27d, 0xbf812d, 0x8c510a],
  BrBG10: [0x003c30, 0x01665e, 0x35978f, 0x80cdc1, 0xc7eae5, 0xf6e8c3, 0xdfc27d, 0xbf812d, 0x8c510a, 0x543005],
  BrBG11: [0x003c30, 0x01665e, 0x35978f, 0x80cdc1, 0xc7eae5, 0xf5f5f5, 0xf6e8c3, 0xdfc27d, 0xbf812d, 0x8c510a, 0x543005],
  PRGn3: [0x7fbf7b, 0xf7f7f7, 0xaf8dc3],
  PRGn4: [0x008837, 0xa6dba0, 0xc2a5cf, 0x7b3294],
  PRGn5: [0x008837, 0xa6dba0, 0xf7f7f7, 0xc2a5cf, 0x7b3294],
  PRGn6: [0x1b7837, 0x7fbf7b, 0xd9f0d3, 0xe7d4e8, 0xaf8dc3, 0x762a83],
  PRGn7: [0x1b7837, 0x7fbf7b, 0xd9f0d3, 0xf7f7f7, 0xe7d4e8, 0xaf8dc3, 0x762a83],
  PRGn8: [0x1b7837, 0x5aae61, 0xa6dba0, 0xd9f0d3, 0xe7d4e8, 0xc2a5cf, 0x9970ab, 0x762a83],
  PRGn9: [0x1b7837, 0x5aae61, 0xa6dba0, 0xd9f0d3, 0xf7f7f7, 0xe7d4e8, 0xc2a5cf, 0x9970ab, 0x762a83],
  PRGn10: [0x00441b, 0x1b7837, 0x5aae61, 0xa6dba0, 0xd9f0d3, 0xe7d4e8, 0xc2a5cf, 0x9970ab, 0x762a83, 0x40004b],
  PRGn11: [0x00441b, 0x1b7837, 0x5aae61, 0xa6dba0, 0xd9f0d3, 0xf7f7f7, 0xe7d4e8, 0xc2a5cf, 0x9970ab, 0x762a83, 0x40004b],
  PiYG3: [0xa1d76a, 0xf7f7f7, 0xe9a3c9],
  PiYG4: [0x4dac26, 0xb8e186, 0xf1b6da, 0xd01c8b],
  PiYG5: [0x4dac26, 0xb8e186, 0xf7f7f7, 0xf1b6da, 0xd01c8b],
  PiYG6: [0x4d9221, 0xa1d76a, 0xe6f5d0, 0xfde0ef, 0xe9a3c9, 0xc51b7d],
  PiYG7: [0x4d9221, 0xa1d76a, 0xe6f5d0, 0xf7f7f7, 0xfde0ef, 0xe9a3c9, 0xc51b7d],
  PiYG8: [0x4d9221, 0x7fbc41, 0xb8e186, 0xe6f5d0, 0xfde0ef, 0xf1b6da, 0xde77ae, 0xc51b7d],
  PiYG9: [0x4d9221, 0x7fbc41, 0xb8e186, 0xe6f5d0, 0xf7f7f7, 0xfde0ef, 0xf1b6da, 0xde77ae, 0xc51b7d],
  PiYG10: [0x276419, 0x4d9221, 0x7fbc41, 0xb8e186, 0xe6f5d0, 0xfde0ef, 0xf1b6da, 0xde77ae, 0xc51b7d, 0x8e0152],
  PiYG11: [0x276419, 0x4d9221, 0x7fbc41, 0xb8e186, 0xe6f5d0, 0xf7f7f7, 0xfde0ef, 0xf1b6da, 0xde77ae, 0xc51b7d, 0x8e0152],
  RdBu3: [0x67a9cf, 0xf7f7f7, 0xef8a62],
  RdBu4: [0x0571b0, 0x92c5de, 0xf4a582, 0xca0020],
  RdBu5: [0x0571b0, 0x92c5de, 0xf7f7f7, 0xf4a582, 0xca0020],
  RdBu6: [0x2166ac, 0x67a9cf, 0xd1e5f0, 0xfddbc7, 0xef8a62, 0xb2182b],
  RdBu7: [0x2166ac, 0x67a9cf, 0xd1e5f0, 0xf7f7f7, 0xfddbc7, 0xef8a62, 0xb2182b],
  RdBu8: [0x2166ac, 0x4393c3, 0x92c5de, 0xd1e5f0, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b],
  RdBu9: [0x2166ac, 0x4393c3, 0x92c5de, 0xd1e5f0, 0xf7f7f7, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b],
  RdBu10: [0x053061, 0x2166ac, 0x4393c3, 0x92c5de, 0xd1e5f0, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b, 0x67001f],
  RdBu11: [0x053061, 0x2166ac, 0x4393c3, 0x92c5de, 0xd1e5f0, 0xf7f7f7, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b, 0x67001f],
  RdGy3: [0x999999, 0xffffff, 0xef8a62],
  RdGy4: [0x404040, 0xbababa, 0xf4a582, 0xca0020],
  RdGy5: [0x404040, 0xbababa, 0xffffff, 0xf4a582, 0xca0020],
  RdGy6: [0x4d4d4d, 0x999999, 0xe0e0e0, 0xfddbc7, 0xef8a62, 0xb2182b],
  RdGy7: [0x4d4d4d, 0x999999, 0xe0e0e0, 0xffffff, 0xfddbc7, 0xef8a62, 0xb2182b],
  RdGy8: [0x4d4d4d, 0x878787, 0xbababa, 0xe0e0e0, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b],
  RdGy9: [0x4d4d4d, 0x878787, 0xbababa, 0xe0e0e0, 0xffffff, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b],
  RdGy10: [0x1a1a1a, 0x4d4d4d, 0x878787, 0xbababa, 0xe0e0e0, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b, 0x67001f],
  RdGy11: [0x1a1a1a, 0x4d4d4d, 0x878787, 0xbababa, 0xe0e0e0, 0xffffff, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b, 0x67001f],
  RdYlBu3: [0x91bfdb, 0xffffbf, 0xfc8d59],
  RdYlBu4: [0x2c7bb6, 0xabd9e9, 0xfdae61, 0xd7191c],
  RdYlBu5: [0x2c7bb6, 0xabd9e9, 0xffffbf, 0xfdae61, 0xd7191c],
  RdYlBu6: [0x4575b4, 0x91bfdb, 0xe0f3f8, 0xfee090, 0xfc8d59, 0xd73027],
  RdYlBu7: [0x4575b4, 0x91bfdb, 0xe0f3f8, 0xffffbf, 0xfee090, 0xfc8d59, 0xd73027],
  RdYlBu8: [0x4575b4, 0x74add1, 0xabd9e9, 0xe0f3f8, 0xfee090, 0xfdae61, 0xf46d43, 0xd73027],
  RdYlBu9: [0x4575b4, 0x74add1, 0xabd9e9, 0xe0f3f8, 0xffffbf, 0xfee090, 0xfdae61, 0xf46d43, 0xd73027],
  RdYlBu10: [0x313695, 0x4575b4, 0x74add1, 0xabd9e9, 0xe0f3f8, 0xfee090, 0xfdae61, 0xf46d43, 0xd73027, 0xa50026],
  RdYlBu11: [0x313695, 0x4575b4, 0x74add1, 0xabd9e9, 0xe0f3f8, 0xffffbf, 0xfee090, 0xfdae61, 0xf46d43, 0xd73027, 0xa50026],
  Spectral3: [0x99d594, 0xffffbf, 0xfc8d59],
  Spectral4: [0x2b83ba, 0xabdda4, 0xfdae61, 0xd7191c],
  Spectral5: [0x2b83ba, 0xabdda4, 0xffffbf, 0xfdae61, 0xd7191c],
  Spectral6: [0x3288bd, 0x99d594, 0xe6f598, 0xfee08b, 0xfc8d59, 0xd53e4f],
  Spectral7: [0x3288bd, 0x99d594, 0xe6f598, 0xffffbf, 0xfee08b, 0xfc8d59, 0xd53e4f],
  Spectral8: [0x3288bd, 0x66c2a5, 0xabdda4, 0xe6f598, 0xfee08b, 0xfdae61, 0xf46d43, 0xd53e4f],
  Spectral9: [0x3288bd, 0x66c2a5, 0xabdda4, 0xe6f598, 0xffffbf, 0xfee08b, 0xfdae61, 0xf46d43, 0xd53e4f],
  Spectral10: [0x5e4fa2, 0x3288bd, 0x66c2a5, 0xabdda4, 0xe6f598, 0xfee08b, 0xfdae61, 0xf46d43, 0xd53e4f, 0x9e0142],
  Spectral11: [0x5e4fa2, 0x3288bd, 0x66c2a5, 0xabdda4, 0xe6f598, 0xffffbf, 0xfee08b, 0xfdae61, 0xf46d43, 0xd53e4f, 0x9e0142],
  RdYlGn3: [0x91cf60, 0xffffbf, 0xfc8d59],
  RdYlGn4: [0x1a9641, 0xa6d96a, 0xfdae61, 0xd7191c],
  RdYlGn5: [0x1a9641, 0xa6d96a, 0xffffbf, 0xfdae61, 0xd7191c],
  RdYlGn6: [0x1a9850, 0x91cf60, 0xd9ef8b, 0xfee08b, 0xfc8d59, 0xd73027],
  RdYlGn7: [0x1a9850, 0x91cf60, 0xd9ef8b, 0xffffbf, 0xfee08b, 0xfc8d59, 0xd73027],
  RdYlGn8: [0x1a9850, 0x66bd63, 0xa6d96a, 0xd9ef8b, 0xfee08b, 0xfdae61, 0xf46d43, 0xd73027],
  RdYlGn9: [0x1a9850, 0x66bd63, 0xa6d96a, 0xd9ef8b, 0xffffbf, 0xfee08b, 0xfdae61, 0xf46d43, 0xd73027],
  RdYlGn10: [0x006837, 0x1a9850, 0x66bd63, 0xa6d96a, 0xd9ef8b, 0xfee08b, 0xfdae61, 0xf46d43, 0xd73027, 0xa50026],
  RdYlGn11: [0x006837, 0x1a9850, 0x66bd63, 0xa6d96a, 0xd9ef8b, 0xffffbf, 0xfee08b, 0xfdae61, 0xf46d43, 0xd73027, 0xa50026]
};


},{}],"range/data_range1d":[function(require,module,exports){
var DataRange1d, Range1d, _, bbox, 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");

bbox = require("../common/bbox");

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

Range1d = require("./range1d");

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

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

  DataRange1d.prototype.type = 'DataRange1d';

  DataRange1d.prototype._get_start = function() {
    var ref;
    return (ref = this.get('_start')) != null ? ref : this.get('_auto_start');
  };

  DataRange1d.prototype._set_start = function(start) {
    return this.set('_start', start);
  };

  DataRange1d.prototype._get_end = function() {
    var ref;
    return (ref = this.get('_end')) != null ? ref : this.get('_auto_end');
  };

  DataRange1d.prototype._set_end = function(end) {
    return this.set('_end', end);
  };

  DataRange1d.prototype.initialize = function(attrs, options) {
    this.register_property('start', this._get_start, true);
    this.register_setter('start', this._set_start);
    this.add_dependencies('start', this, ['_start', 'flipped', '_auto_start', 'range_padding', 'default_span']);
    this.register_property('end', this._get_end, true);
    this.register_setter('end', this._set_end);
    this.add_dependencies('end', this, ['_end', 'flipped', '_auto_end', 'range_padding', 'default_span']);
    if ((attrs != null ? attrs.start : void 0) != null) {
      this.set('start', attrs.start);
      delete attrs.start;
    }
    if ((attrs != null ? attrs.end : void 0) != null) {
      this.set('end', attrs.end);
      delete attrs.end;
    }
    DataRange1d.__super__.initialize.call(this, attrs, options);
    return this.plot_bounds = {};
  };

  DataRange1d.prototype.nonserializable_attribute_names = function() {
    return DataRange1d.__super__.nonserializable_attribute_names.call(this).concat(['_auto_end', '_auto_start', '_start', '_end', 'flipped', 'sources', 'default_span', 'plots']);
  };

  DataRange1d.prototype.update = function(bounds, dimension, plot_view) {
    var all_renderers, center, i, j, k, len, len1, max, min, overall, plot, r, ref, ref1, ref2, ref3, ref4, renderers, result, rs, sgn, span, v;
    renderers = (ref = this.get('renderers')) != null ? ref : [];
    all_renderers = [];
    if (renderers.length === 0) {
      ref1 = this.get('plots');
      for (i = 0, len = ref1.length; i < len; i++) {
        plot = ref1[i];
        rs = plot.get('renderers');
        rs = (function() {
          var j, len1, results;
          results = [];
          for (j = 0, len1 = rs.length; j < len1; j++) {
            r = rs[j];
            if (r.type === "GlyphRenderer") {
              results.push(r);
            }
          }
          return results;
        })();
        all_renderers = all_renderers.concat(rs);
      }
      renderers = all_renderers;
    }
    this.set('renderers', renderers);
    result = new bbox.empty();
    ref2 = this.get('renderers');
    for (j = 0, len1 = ref2.length; j < len1; j++) {
      r = ref2[j];
      if (bounds[r.id] != null) {
        result = bbox.extend(result, bounds[r.id]);
      }
    }
    this.plot_bounds[plot_view.model.id] = result;
    overall = new bbox.empty();
    ref3 = this.plot_bounds;
    for (k in ref3) {
      v = ref3[k];
      overall = bbox.extend(overall, v);
    }
    ref4 = overall[dimension], min = ref4[0], max = ref4[1];
    if (max !== min) {
      span = (max - min) * (1 + this.get('range_padding'));
    } else {
      span = this.get('default_span');
    }
    center = (max + min) / 2.0;
    sgn = 1;
    if (this.get('flipped')) {
      sgn = -1;
    }
    this.set('_auto_start', center - sgn * span / 2.0);
    return this.set('_auto_end', center + sgn * span / 2.0);
  };

  DataRange1d.prototype.defaults = function() {
    return _.extend({}, DataRange1d.__super__.defaults.call(this), {
      plots: [],
      sources: [],
      range_padding: 0.1,
      default_span: 2,
      flipped: false
    });
  };

  return DataRange1d;

})(Range1d.Model);

module.exports = {
  Model: DataRange1d
};


},{"../common/bbox":"common/bbox","../common/logging":"common/logging","./range1d":"range/range1d","underscore":"underscore"}],"range/factor_range":[function(require,module,exports){
var FactorRange, HasProperties, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

HasProperties = require("../common/has_properties");

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

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

  FactorRange.prototype.type = 'FactorRange';

  FactorRange.prototype.initialize = function(attrs, options) {
    FactorRange.__super__.initialize.call(this, attrs, options);
    this._init();
    this.register_property('min', function() {
      return this.get('start');
    }, false);
    this.add_dependencies('min', this, ['factors', 'offset']);
    this.register_property('max', function() {
      return this.get('end');
    }, false);
    this.add_dependencies('max', this, ['factors', 'offset']);
    this.listenTo(this, 'change:factors', this._init);
    return this.listenTo(this, 'change:offset', this._init);
  };

  FactorRange.prototype._init = function() {
    this.set('start', 0.5 + this.get('offset'));
    return this.set('end', this.get('factors').length + this.get('start'));
  };

  FactorRange.prototype.defaults = function() {
    return _.extend({}, FactorRange.__super__.defaults.call(this), {
      offset: 0,
      factors: []
    });
  };

  return FactorRange;

})(HasProperties);

module.exports = {
  Model: FactorRange
};


},{"../common/has_properties":"common/has_properties","underscore":"underscore"}],"range/range1d":[function(require,module,exports){
var HasProperties, Range1d, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

HasProperties = require("../common/has_properties");

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

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

  Range1d.prototype.type = 'Range1d';

  Range1d.prototype.initialize = function(attrs, options) {
    Range1d.__super__.initialize.call(this, attrs, options);
    this.register_property('min', function() {
      return Math.min(this.get('start'), this.get('end'));
    }, true);
    this.add_dependencies('min', this, ['start', 'end']);
    this.register_property('max', function() {
      return Math.max(this.get('start'), this.get('end'));
    }, true);
    return this.add_dependencies('max', this, ['start', 'end']);
  };

  Range1d.prototype.defaults = function() {
    return _.extend({}, Range1d.__super__.defaults.call(this), {
      start: 0,
      end: 1
    });
  };

  return Range1d;

})(HasProperties);

module.exports = {
  Model: Range1d
};


},{"../common/has_properties":"common/has_properties","underscore":"underscore"}],"renderer/annotation/box_annotation":[function(require,module,exports){
var BoxAnnotation, BoxAnnotationView, HasParent, PlotWidget, _, properties,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

HasParent = require("../../common/has_parent");

PlotWidget = require("../../common/plot_widget");

properties = require("../../common/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.fill_props = new properties.Fill({
      obj: this.model,
      prefix: ''
    });
    return this.line_props = new properties.Line({
      obj: this.model,
      prefix: ''
    });
  };

  BoxAnnotationView.prototype.render = function() {
    var ctx, sbottom, sleft, sright, stop;
    this.frame = this.plot_model.get('frame');
    this.canvas = this.plot_model.get('canvas');
    this.xmapper = this.plot_view.frame.get('x_mappers')[this.mget("x_range_name")];
    this.ymapper = this.plot_view.frame.get('y_mappers')[this.mget("y_range_name")];
    sleft = this.canvas.vx_to_sx(this._calc_dim('left', this.xmapper, this.frame.get('h_range').get('start')));
    sright = this.canvas.vx_to_sx(this._calc_dim('right', this.xmapper, this.frame.get('h_range').get('end')));
    sbottom = this.canvas.vy_to_sy(this._calc_dim('bottom', this.ymapper, this.frame.get('v_range').get('start')));
    stop = this.canvas.vy_to_sy(this._calc_dim('top', this.ymapper, this.frame.get('v_range').get('end')));
    ctx = this.plot_view.canvas_view.ctx;
    ctx.save();
    ctx.beginPath();
    ctx.rect(sleft, stop, sright - sleft, sbottom - stop);
    this.fill_props.set_value(ctx);
    ctx.fill();
    this.line_props.set_value(ctx);
    ctx.stroke();
    return ctx.restore();
  };

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

  return BoxAnnotationView;

})(PlotWidget);

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.prototype.defaults = function() {
    return _.extend({}, BoxAnnotation.__super__.defaults.call(this), {
      x_range_name: "default",
      y_range_name: "default"
    });
  };

  BoxAnnotation.prototype.display_defaults = function() {
    return _.extend({}, BoxAnnotation.__super__.display_defaults.call(this), {
      level: 'annotation',
      left_units: 'data',
      right_units: 'data',
      top_units: 'data',
      bottom_units: 'data',
      fill_color: '#fff9ba',
      fill_alpha: 0.4,
      line_color: '#cccccc',
      line_width: 1,
      line_alpha: 0.3,
      line_join: 'miter',
      line_cap: 'butt',
      line_dash: [],
      line_dash_offset: 0
    });
  };

  return BoxAnnotation;

})(HasParent);

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


},{"../../common/has_parent":"common/has_parent","../../common/plot_widget":"common/plot_widget","../../common/properties":"common/properties","underscore":"underscore"}],"renderer/annotation/legend":[function(require,module,exports){
var HasParent, Legend, LegendView, PlotWidget, _, properties, textutils,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

HasParent = require("../../common/has_parent");

PlotWidget = require("../../common/plot_widget");

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

textutils = require("../../common/textutils");

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

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

  LegendView.prototype.initialize = function(options) {
    LegendView.__super__.initialize.call(this, options);
    this.label_props = new properties.Text({
      obj: this.model,
      prefix: 'label_'
    });
    this.border_props = new properties.Line({
      obj: this.model,
      prefix: 'border_'
    });
    this.background_props = new properties.Fill({
      obj: this.model,
      prefix: 'background_'
    });
    this.need_calc_dims = true;
    return this.listenTo(this.plot_model.solver, 'layout_update', function() {
      return this.need_calc_dims = true;
    });
  };

  LegendView.prototype.calc_dims = function(options) {
    var ctx, glyphs, h_range, label_height, label_width, legend_name, legend_names, legend_padding, legend_spacing, orientation, ref, text_width, text_widths, v_range, x, y;
    legend_names = (function() {
      var i, len, ref, ref1, results;
      ref = this.mget("legends");
      results = [];
      for (i = 0, len = ref.length; i < len; i++) {
        ref1 = ref[i], legend_name = ref1[0], glyphs = ref1[1];
        results.push(legend_name);
      }
      return results;
    }).call(this);
    label_height = this.mget('label_height');
    this.glyph_height = this.mget('glyph_height');
    label_width = this.mget('label_width');
    this.glyph_width = this.mget('glyph_width');
    legend_spacing = this.mget('legend_spacing');
    this.label_height = _.max([textutils.getTextHeight(this.label_props.font_value()), label_height, this.glyph_height]);
    this.legend_height = this.label_height;
    this.legend_height = legend_names.length * this.legend_height + (1 + legend_names.length) * legend_spacing;
    ctx = this.plot_view.canvas_view.ctx;
    ctx.save();
    this.label_props.set_value(ctx);
    text_widths = _.map(legend_names, function(txt) {
      return ctx.measureText(txt).width;
    });
    ctx.restore();
    text_width = _.max(text_widths);
    this.label_width = _.max([text_width, label_width]);
    this.legend_width = this.label_width + this.glyph_width + 3 * legend_spacing;
    orientation = this.mget('orientation');
    legend_padding = this.mget('legend_padding');
    h_range = this.plot_view.frame.get('h_range');
    v_range = this.plot_view.frame.get('v_range');
    if (orientation === "top_right") {
      x = h_range.get('end') - legend_padding - this.legend_width;
      y = v_range.get('end') - legend_padding;
    } else if (orientation === "top_left") {
      x = h_range.get('start') + legend_padding;
      y = v_range.get('end') - legend_padding;
    } else if (orientation === "bottom_left") {
      x = h_range.get('start') + legend_padding;
      y = v_range.get('start') + legend_padding + this.legend_height;
    } else if (orientation === "bottom_right") {
      x = h_range.get('end') - legend_padding - this.legend_width;
      y = v_range.get('start') + legend_padding + this.legend_height;
    } else if (orientation === "absolute") {
      ref = this.absolute_coords, x = ref[0], y = ref[1];
    }
    x = this.plot_view.canvas.vx_to_sx(x);
    y = this.plot_view.canvas.vy_to_sy(y);
    return this.box_coords = [x, y];
  };

  LegendView.prototype.render = function() {
    var ctx, glyphs, i, idx, j, legend_name, legend_spacing, len, len1, ref, ref1, ref2, renderer, view, x, x1, x2, y, y1, y2, yoffset, yspacing;
    if (this.need_calc_dims) {
      this.calc_dims();
      this.need_calc_dims = false;
    }
    ctx = this.plot_view.canvas_view.ctx;
    ctx.save();
    ctx.beginPath();
    ctx.rect(this.box_coords[0], this.box_coords[1], this.legend_width, this.legend_height);
    this.background_props.set_value(ctx);
    ctx.fill();
    if (this.border_props.do_stroke) {
      this.border_props.set_value(ctx);
      ctx.stroke();
    }
    legend_spacing = this.mget('legend_spacing');
    ref = this.mget("legends");
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      ref1 = ref[idx], legend_name = ref1[0], glyphs = ref1[1];
      yoffset = idx * this.label_height;
      yspacing = (1 + idx) * legend_spacing;
      y = this.box_coords[1] + this.label_height / 2.0 + yoffset + yspacing;
      x = this.box_coords[0] + legend_spacing;
      x1 = this.box_coords[0] + 2 * legend_spacing + this.label_width;
      x2 = x1 + this.glyph_width;
      y1 = this.box_coords[1] + yoffset + yspacing;
      y2 = y1 + this.glyph_height;
      this.label_props.set_value(ctx);
      ctx.fillText(legend_name, x, y);
      ref2 = this.model.resolve_ref(glyphs);
      for (j = 0, len1 = ref2.length; j < len1; j++) {
        renderer = ref2[j];
        view = this.plot_view.renderers[renderer.id];
        view.draw_legend(ctx, x1, x2, y1, y2);
      }
    }
    return ctx.restore();
  };

  return LegendView;

})(PlotWidget);

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.defaults = function() {
    return _.extend({}, Legend.__super__.defaults.call(this), {
      legends: []
    });
  };

  Legend.prototype.display_defaults = function() {
    return _.extend({}, Legend.__super__.display_defaults.call(this), {
      level: 'overlay',
      border_line_color: 'black',
      border_line_width: 1,
      border_line_alpha: 1.0,
      border_line_join: 'miter',
      border_line_cap: 'butt',
      border_line_dash: [],
      border_line_dash_offset: 0,
      background_fill_color: '#fff',
      background_fill_alpha: 1.0,
      label_standoff: 15,
      label_text_font: "helvetica",
      label_text_font_size: "10pt",
      label_text_font_style: "normal",
      label_text_color: "#444444",
      label_text_alpha: 1.0,
      label_text_align: "left",
      label_text_baseline: "middle",
      glyph_height: 20,
      glyph_width: 20,
      label_height: 20,
      label_width: 50,
      legend_padding: 10,
      legend_spacing: 3,
      orientation: "top_right",
      datapoint: null
    });
  };

  return Legend;

})(HasParent);

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


},{"../../common/has_parent":"common/has_parent","../../common/plot_widget":"common/plot_widget","../../common/properties":"common/properties","../../common/textutils":"common/textutils","underscore":"underscore"}],"renderer/annotation/span":[function(require,module,exports){
var HasParent, PlotWidget, Span, SpanView, _, logger, properties,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

HasParent = require("../../common/has_parent");

PlotWidget = require("../../common/plot_widget");

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

properties = require("../../common/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.line_props = new properties.Line({
      obj: this.model,
      prefix: ''
    });
    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() {
    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, sleft, stop, width, xmapper, ymapper;
    if (this.mget('location') == null) {
      this.$el.hide();
      return;
    }
    frame = this.plot_model.get('frame');
    canvas = this.plot_model.get('canvas');
    xmapper = this.plot_view.frame.get('x_mappers')[this.mget("x_range_name")];
    ymapper = this.plot_view.frame.get('y_mappers')[this.mget("y_range_name")];
    if (this.mget('dimension') === 'width') {
      stop = canvas.vy_to_sy(this._calc_dim(this.mget('location'), ymapper));
      sleft = canvas.vx_to_sx(frame.get('left'));
      width = frame.get('width');
      height = this.mget('line_width');
    } else {
      stop = canvas.vy_to_sy(frame.get('top'));
      sleft = canvas.vx_to_sx(this._calc_dim(this.mget('location'), xmapper));
      width = this.mget('line_width');
      height = frame.get('height');
    }
    if (this.mget("render_mode") === "css") {
      this.$el.css({
        'top': stop,
        'left': sleft,
        'width': width + "px",
        'height': height + "px",
        'z-index': 1000,
        'background-color': this.mget('line_color'),
        'opacity': this.mget('line_alpha')
      });
      return this.$el.show();
    } else if (this.mget("render_mode") === "canvas") {
      ctx = this.plot_view.canvas_view.ctx;
      ctx.save();
      ctx.beginPath();
      this.line_props.set_value(ctx);
      ctx.moveTo(sleft, stop);
      if (this.mget('dimension') === "width") {
        ctx.lineTo(sleft + width, stop);
      } else {
        ctx.lineTo(sleft, stop + height);
      }
      ctx.stroke();
      return ctx.restore();
    }
  };

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

  return SpanView;

})(PlotWidget);

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.prototype.defaults = function() {
    return _.extend({}, Span.__super__.defaults.call(this), {
      x_range_name: "default",
      y_range_name: "default",
      render_mode: "canvas",
      location_units: "data"
    });
  };

  Span.prototype.display_defaults = function() {
    return _.extend({}, Span.__super__.display_defaults.call(this), {
      level: 'annotation',
      line_color: 'black',
      line_width: 1,
      line_alpha: 1.0,
      line_dash: [],
      line_dash_offset: 0
    });
  };

  return Span;

})(HasParent);

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


},{"../../common/has_parent":"common/has_parent","../../common/logging":"common/logging","../../common/plot_widget":"common/plot_widget","../../common/properties":"common/properties","underscore":"underscore"}],"renderer/annotation/tooltip":[function(require,module,exports){
var $, HasParent, PlotWidget, Tooltip, TooltipView, _, 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("jquery");

_ = require("underscore");

HasParent = require("../../common/has_parent");

PlotWidget = require("../../common/plot_widget");

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

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_width, content, i, left, len, ow, ref, side, sx, sy, tip, top, val, vx, vy;
    this.$el.empty();
    this.$el.hide();
    this.$el.toggleClass("bk-tooltip-custom", this.mget("custom"));
    if (_.isEmpty(this.mget('data'))) {
      return;
    }
    ref = this.mget('data');
    for (i = 0, len = ref.length; i < len; i++) {
      val = ref[i];
      vx = val[0], vy = val[1], content = val[2];
      if (this.mget('inner_only') && !this.plot_view.frame.contains(vx, vy)) {
        continue;
      }
      tip = $('<div />').appendTo(this.$el);
      tip.append(content);
    }
    sx = this.plot_view.mget('canvas').vx_to_sx(vx);
    sy = this.plot_view.mget('canvas').vy_to_sy(vy);
    side = this.mget('side');
    if (side === 'auto') {
      ow = this.plot_view.frame.get('width');
      if (vx - this.plot_view.frame.get('left') < ow / 2) {
        side = 'right';
      } else {
        side = 'left';
      }
    }
    this.$el.removeClass('bk-right');
    this.$el.removeClass('bk-left');
    arrow_width = 10;
    switch (side) {
      case "right":
        this.$el.addClass("bk-left");
        left = sx + (this.$el.outerWidth() - this.$el.innerWidth()) + arrow_width;
        break;
      case "left":
        this.$el.addClass("bk-right");
        left = sx - this.$el.outerWidth() - arrow_width;
    }
    top = sy - this.$el.outerHeight() / 2;
    if (this.$el.children().length > 0) {
      this.$el.css({
        top: top,
        left: left
      });
      return this.$el.show();
    }
  };

  return TooltipView;

})(PlotWidget);

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.prototype.clear = function() {
    return this.set('data', []);
  };

  Tooltip.prototype.add = function(vx, vy, content) {
    var data;
    data = this.get('data');
    data.push([vx, vy, content]);
    return this.set('data', data);
  };

  Tooltip.prototype.defaults = function() {
    return _.extend({}, Tooltip.__super__.defaults.call(this), {
      level: 'overlay',
      side: "auto",
      inner_only: true
    });
  };

  return Tooltip;

})(HasParent);

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


},{"../../common/has_parent":"common/has_parent","../../common/logging":"common/logging","../../common/plot_widget":"common/plot_widget","jquery":"jquery","underscore":"underscore"}],"renderer/glyph/annular_wedge":[function(require,module,exports){
var AnnularWedge, AnnularWedgeView, Glyph, _, hittest, mathutils,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

mathutils = require("../../common/mathutils");

Glyph = require("./glyph");

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

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.distances.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.distances.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, direction, i, j, len, results, sinner_radius, souter_radius, start_angle, 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 = arg.direction;
    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] + direction[i])) {
        continue;
      }
      ctx.translate(sx[i], sy[i]);
      ctx.rotate(this.start_angle[i]);
      ctx.moveTo(souter_radius[i], 0);
      ctx.beginPath();
      ctx.arc(0, 0, souter_radius[i], 0, angle[i], direction[i]);
      ctx.rotate(this.angle[i]);
      ctx.lineTo(sinner_radius[i], 0);
      ctx.arc(0, 0, sinner_radius[i], 0, -angle[i], !direction[i]);
      ctx.closePath();
      ctx.rotate(-angle[i] - start_angle[i]);
      ctx.translate(-sx[i], -sy[i]);
      if (this.visuals.fill.do_fill) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fill();
      }
      if (this.visuals.line.do_stroke) {
        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, candidates, 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.distances.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 = [];
    ref3 = (function() {
      var k, len, ref3, results;
      ref3 = this.index.search([x0, y0, x1, y1]);
      results = [];
      for (k = 0, len = ref3.length; k < len; k++) {
        pt = ref3[k];
        results.push(pt[4].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]);
      }
    }
    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 (mathutils.angle_between(-angle, -this.start_angle[i], -this.end_angle[i], this.direction[i])) {
        hits.push([i, dist]);
      }
    }
    result = hittest.create_hit_test_result();
    result['1d'].indices = _.chain(hits).sortBy(function(elt) {
      return elt[1];
    }).map(function(elt) {
      return elt[0];
    }).value();
    return result;
  };

  AnnularWedgeView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    return this._generic_area_legend(ctx, x0, x1, y0, y1);
  };

  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.prototype.distances = ['inner_radius', 'outer_radius'];

  AnnularWedge.prototype.angles = ['start_angle', 'end_angle'];

  AnnularWedge.prototype.fields = ['direction:direction'];

  AnnularWedge.prototype.display_defaults = function() {
    return _.extend({}, AnnularWedge.__super__.display_defaults.call(this), {
      direction: 'anticlock'
    });
  };

  return AnnularWedge;

})(Glyph.Model);

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


},{"../../common/hittest":"common/hittest","../../common/mathutils":"common/mathutils","./glyph":"renderer/glyph/glyph","underscore":"underscore"}],"renderer/glyph/annulus":[function(require,module,exports){
var Annulus, AnnulusView, Glyph, _, hittest,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Glyph = require("./glyph");

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

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.distances.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.distances.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 i, j, len, 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;
      }
      ctx.beginPath();
      ctx.arc(sx[i], sy[i], sinner_radius[i], 0, 2 * Math.PI * 2, false);
      ctx.moveTo(sx[i] + souter_radius[i], sy[i]);
      ctx.arc(sx[i], sy[i], souter_radius[i], 0, 2 * Math.PI * 2, true);
      if (this.visuals.fill.do_fill) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fill();
      }
      if (this.visuals.line.do_stroke) {
        this.visuals.line.set_vectorize(ctx, i);
        results.push(ctx.stroke());
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  AnnulusView.prototype._hit_point = function(geometry) {
    var 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 = [];
    ref1 = (function() {
      var k, len, ref1, results;
      ref1 = this.index.search([x0, y0, x1, y1]);
      results = [];
      for (k = 0, len = ref1.length; k < len; k++) {
        pt = ref1[k];
        results.push(pt[4].i);
      }
      return results;
    }).call(this);
    for (j = 0, len = ref1.length; j < len; j++) {
      i = ref1[j];
      or2 = Math.pow(this.souter_radius[i], 2);
      ir2 = Math.pow(this.sinner_radius[i], 2);
      sx0 = this.renderer.xmapper.map_to_target(x);
      sx1 = this.renderer.xmapper.map_to_target(this.x[i]);
      sy0 = this.renderer.ymapper.map_to_target(y);
      sy1 = this.renderer.ymapper.map_to_target(this.y[i]);
      dist = Math.pow(sx0 - sx1, 2) + Math.pow(sy0 - sy1, 2);
      if (dist <= or2 && dist >= ir2) {
        hits.push([i, dist]);
      }
    }
    result = hittest.create_hit_test_result();
    result['1d'].indices = _.chain(hits).sortBy(function(elt) {
      return elt[1];
    }).map(function(elt) {
      return elt[0];
    }).value();
    return result;
  };

  AnnulusView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    var data, indices, r, ref, reference_point, sinner_radius, souter_radius, sx, sy;
    reference_point = (ref = this.get_reference_point()) != null ? ref : 0;
    indices = [reference_point];
    sx = {};
    sx[reference_point] = (x0 + x1) / 2;
    sy = {};
    sy[reference_point] = (y0 + y1) / 2;
    r = Math.min(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 0.5;
    sinner_radius = {};
    sinner_radius[reference_point] = r * 0.4;
    souter_radius = {};
    souter_radius[reference_point] = r * 0.8;
    data = {
      sx: sx,
      sy: sy,
      sinner_radius: sinner_radius,
      souter_radius: souter_radius
    };
    return this._render(ctx, indices, data);
  };

  return AnnulusView;

})(Glyph.View);

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

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

  Annulus.prototype.default_view = AnnulusView;

  Annulus.prototype.type = 'Annulus';

  Annulus.prototype.distances = ['inner_radius', 'outer_radius'];

  return Annulus;

})(Glyph.Model);

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


},{"../../common/hittest":"common/hittest","./glyph":"renderer/glyph/glyph","underscore":"underscore"}],"renderer/glyph/arc":[function(require,module,exports){
var Arc, ArcView, Glyph, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

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.distances.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 direction, end_angle, i, j, len, results, sradius, start_angle, sx, sy;
    sx = arg.sx, sy = arg.sy, sradius = arg.sradius, start_angle = arg.start_angle, end_angle = arg.end_angle, direction = arg.direction;
    if (this.visuals.line.do_stroke) {
      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] + direction[i])) {
          continue;
        }
        ctx.beginPath();
        ctx.arc(sx[i], sy[i], sradius[i], start_angle[i], end_angle[i], direction[i]);
        this.visuals.line.set_vectorize(ctx, i);
        results.push(ctx.stroke());
      }
      return results;
    }
  };

  ArcView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    return this._generic_line_legend(ctx, x0, x1, y0, y1);
  };

  return ArcView;

})(Glyph.View);

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

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

  Arc.prototype.default_view = ArcView;

  Arc.prototype.type = 'Arc';

  Arc.prototype.visuals = ['line'];

  Arc.prototype.distances = ['radius'];

  Arc.prototype.angles = ['start_angle', 'end_angle'];

  Arc.prototype.fields = ['direction:direction'];

  Arc.prototype.display_defaults = function() {
    return _.extend({}, Arc.__super__.display_defaults.call(this), {
      direction: 'anticlock'
    });
  };

  return Arc;

})(Glyph.Model);

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


},{"./glyph":"renderer/glyph/glyph","underscore":"underscore"}],"renderer/glyph/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([
        x0, y0, x1, 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.do_stroke) {
      results = [];
      for (k = 0, len = indices.length; k < len; k++) {
        i = indices[k];
        if (isNaN(sx0[i] + sy0[i] + sx1[i] + sy1[i] + scx0[i] + scy0[i] + scx1[i] + scy1[i])) {
          continue;
        }
        ctx.beginPath();
        ctx.moveTo(sx0[i], sy0[i]);
        ctx.bezierCurveTo(scx0[i], scy0[i], scx1[i], scy1[i], sx1[i], sy1[i]);
        this.visuals.line.set_vectorize(ctx, i);
        results.push(ctx.stroke());
      }
      return results;
    }
  };

  BezierView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    return this._generic_line_legend(ctx, x0, x1, y0, y1);
  };

  return BezierView;

})(Glyph.View);

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

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

  Bezier.prototype.default_view = BezierView;

  Bezier.prototype.type = 'Bezier';

  Bezier.prototype.visuals = ['line'];

  Bezier.prototype.coords = [['x0', 'y0'], ['x1', 'y1'], ['cx0', 'cy0'], ['cx1', 'cy1']];

  return Bezier;

})(Glyph.Model);

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


},{"./glyph":"renderer/glyph/glyph","rbush":"rbush","underscore":"underscore"}],"renderer/glyph/bokehgl":[function(require,module,exports){
var BaseGLGlyph, CircleGLGlyph, DashAtlas, LineGLGlyph, MarkerGLGlyph, SquareGLGlyph, attach_color, attach_float, color, color2rgba, fill_array_with_float, fill_array_with_vec, gloo2, line_width,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

color = require("../../common/color");

color2rgba = color.color2rgba;

line_width = function(width) {
  if (width < 2) {
    width = Math.sqrt(width * 2);
  }
  return width;
};

fill_array_with_float = function(n, val) {
  var a, i, l, ref;
  a = new Float32Array(n);
  for (i = l = 0, ref = n; 0 <= ref ? l < ref : l > ref; i = 0 <= ref ? ++l : --l) {
    a[i] = val;
  }
  return a;
};

fill_array_with_vec = function(n, m, val) {
  var a, i, j, l, p, ref, ref1;
  a = new Float32Array(n * m);
  for (i = l = 0, ref = n; 0 <= ref ? l < ref : l > ref; i = 0 <= ref ? ++l : --l) {
    for (j = p = 0, ref1 = m; 0 <= ref1 ? p < ref1 : p > ref1; j = 0 <= ref1 ? ++p : --p) {
      a[i * m + j] = val[j];
    }
  }
  return a;
};

attach_float = function(prog, vbo, att_name, n, visual, name) {
  var a;
  vbo.used = true;
  if (visual[name].fixed_value != null) {
    prog.set_attribute(att_name, 'float', null, visual[name].fixed_value);
    vbo.used = false;
  } else {
    a = new Float32Array(visual.cache[name + '_array']);
    vbo.set_size(n * 4);
    vbo.set_data(0, a);
    prog.set_attribute(att_name, 'float', [vbo, 0, 0]);
  }
  return a;
};

attach_color = function(prog, vbo, att_name, n, visual) {
  var a, alphas, colors, i, j, l, m, p, ref, ref1, rgba;
  m = 4;
  vbo.used = true;
  if ((visual.color.fixed_value != null) && (visual.alpha.fixed_value != null)) {
    rgba = color2rgba(visual.color.fixed_value, visual.alpha.fixed_value);
    prog.set_attribute(att_name, 'vec4', null, rgba);
    vbo.used = false;
  } else {
    if (visual.color.fixed_value != null) {
      colors = (function() {
        var l, ref, results;
        results = [];
        for (i = l = 0, ref = n; 0 <= ref ? l < ref : l > ref; i = 0 <= ref ? ++l : --l) {
          results.push(visual.color.fixed_value);
        }
        return results;
      })();
    } else {
      colors = visual.cache.color_array;
    }
    if (visual.alpha.fixed_value != null) {
      alphas = fill_array_with_float(n, visual.alpha.fixed_value);
    } else {
      alphas = visual.cache.alpha_array;
    }
    a = new Float32Array(n * m);
    for (i = l = 0, ref = n; 0 <= ref ? l < ref : l > ref; i = 0 <= ref ? ++l : --l) {
      rgba = color2rgba(colors[i], alphas[i]);
      for (j = p = 0, ref1 = m; 0 <= ref1 ? p < ref1 : p > ref1; j = 0 <= ref1 ? ++p : --p) {
        a[i * m + j] = rgba[j];
      }
    }
    vbo.set_size(n * m * 4);
    vbo.set_data(0, a);
    prog.set_attribute(att_name, 'vec4', [vbo, 0, 0]);
  }
  return a;
};

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.get_atlas_data([1]);
  }

  DashAtlas.prototype.get_atlas_data = function(pattern) {
    var data, findex_period, key, period, ref, x;
    key = pattern.join('-');
    findex_period = this._atlas[key];
    if (findex_period === void 0) {
      ref = this.make_pattern(pattern), data = ref[0], period = ref[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, ref, ref1, ref2, 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, ref = pattern.length + 2; p < ref; 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, ref1 = n; 0 <= ref1 ? q < ref1 : q > ref1; i = 0 <= ref1 ? ++q : --q) {
      x = period * i / (n - 1);
      index = 0;
      val_at_index = 1e16;
      for (j = r = 0, ref2 = C.length; 0 <= ref2 ? r < ref2 : r > ref2; j = 0 <= ref2 ? ++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;

})();

BaseGLGlyph = (function() {
  BaseGLGlyph.prototype.GLYPH = '';

  BaseGLGlyph.prototype.VERT = '';

  BaseGLGlyph.prototype.FRAG = '';

  function BaseGLGlyph(gl, glyph) {
    this.gl = gl;
    this.glyph = glyph;
    this.nvertices = 0;
    this.size_changed = false;
    this.data_changed = false;
    this.visuals_changed = false;
    this.init();
  }

  BaseGLGlyph.prototype.set_data_changed = function(n) {
    if (n !== this.nvertices) {
      this.nvertices = n;
      this.size_changed = true;
    }
    return this.data_changed = true;
  };

  BaseGLGlyph.prototype.set_visuals_changed = function() {
    return this.visuals_changed = true;
  };

  return BaseGLGlyph;

})();

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 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(1.25*u_antialias+v_linewidth)/2.0;\n    \n    vec2 position = a_position * 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) + (u_offset - vec2(0.5, 0.5));\n    normpos /= u_canvas_size;  // 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 )\n{\n    float d = 0.0;\n    dx = abs(dx);\n    dy = abs(dy);\n    \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 miter_limit, in float linewidth )\n{\n    float dx = texcoord.x;\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    // Miter limit\n    if( (dx < segment.x) ||  (dx > segment.y) ) {\n        d = max(d, min(abs(miter.x),abs(miter.y)) - miter_limit*linewidth/2.0 );\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    // 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 );\n        }\n        else if( (!closed) &&  (dx > line_stop) ) {\n            d = cap( int(u_linecaps.y), abs(dx)-line_stop, abs(dy), t );\n        }\n        else {\n            d = join( int(u_linejoin), abs(dy), v_segment, v_texcoord, v_miter, u_miter_limit, 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, u_miter_limit, 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);\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);\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);\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);\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    }\n    else {\n        d /= u_antialias;\n        gl_FragColor = vec4(color.xyz, 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 chunk, chunks, chunksize, i, l, nvertices, offset, p, q, ref, ref1, ref2, results, scale_length, sx, sy, these_indices, uint16_index;
    if (this.data_changed) {
      this._set_data();
      this.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)) {
      this._update_scale(sx, sy);
      this._scale_aspect = sy / sx;
    }
    this.prog.set_attribute('a_position', 'vec2', [mainGlyph.glglyph.vbo_position, 0, 0]);
    this.prog.set_attribute('a_tangents', 'vec4', [mainGlyph.glglyph.vbo_tangents, 0, 0]);
    this.prog.set_attribute('a_segment', 'vec2', [mainGlyph.glglyph.vbo_segment, 0, 0]);
    this.prog.set_attribute('a_angles', 'vec2', [mainGlyph.glglyph.vbo_angles, 0, 0]);
    this.prog.set_attribute('a_texcoord', 'vec2', [mainGlyph.glglyph.vbo_texcoord, 0, 0]);
    this.prog.set_uniform('u_length', 'float', [mainGlyph.glglyph.cumsum]);
    this.prog.set_texture('u_dash_atlas', this.dash_atlas.tex);
    this.prog.set_uniform('u_canvas_size', 'vec2', [trans.width, trans.height]);
    this.prog.set_uniform('u_offset', 'vec2', [trans.dx[0], trans.dy[0]]);
    this.prog.set_uniform('u_scale_aspect', 'vec2', [sx, sy]);
    this.prog.set_uniform('u_scale_length', 'float', [scale_length]);
    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, ref = Math.ceil(nvertices / chunksize); 0 <= ref ? l < ref : l > ref; i = 0 <= ref ? ++l : --l) {
        chunks.push([]);
      }
      for (i = p = 0, ref1 = indices.length; 0 <= ref1 ? p < ref1 : p > ref1; i = 0 <= ref1 ? ++p : --p) {
        uint16_index = indices[i] % chunksize;
        chunk = Math.floor(indices[i] / chunksize);
        chunks[chunk].push(uint16_index);
      }
      results = [];
      for (chunk = q = 0, ref2 = chunks.length; 0 <= ref2 ? q < ref2 : q > ref2; chunk = 0 <= ref2 ? ++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', [mainGlyph.glglyph.vbo_position, 0, offset * 2]);
        this.prog.set_attribute('a_tangents', 'vec4', [mainGlyph.glglyph.vbo_tangents, 0, offset * 4]);
        this.prog.set_attribute('a_segment', 'vec2', [mainGlyph.glglyph.vbo_segment, 0, offset * 2]);
        this.prog.set_attribute('a_angles', 'vec2', [mainGlyph.glglyph.vbo_angles, 0, offset * 2]);
        this.prog.set_attribute('a_texcoord', 'vec2', [mainGlyph.glglyph.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, dash_index, dash_pattern, dash_period, join, ref;
    window.X = this;
    color = color2rgba(this.glyph.visuals.line.color.value(), this.glyph.visuals.line.alpha.value());
    cap = this.CAPS[this.glyph.visuals.line.cap.value()];
    join = this.JOINS[this.glyph.visuals.line.join.value()];
    this.prog.set_uniform('u_color', 'vec4', color);
    this.prog.set_uniform('u_linewidth', 'float', [this.glyph.visuals.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.dash.value();
    dash_index = 0;
    dash_period = 1;
    if (dash_pattern.length) {
      ref = this.dash_atlas.get_atlas_data(dash_pattern), dash_index = ref[0], dash_period = ref[1];
    }
    this.prog.set_uniform('u_dash_index', 'float', [dash_index]);
    this.prog.set_uniform('u_dash_phase', 'float', [this.glyph.visuals.line.dash_offset.value()]);
    this.prog.set_uniform('u_dash_period', 'float', [dash_period]);
    this.prog.set_uniform('u_dash_caps', 'vec2', [cap, cap]);
    return this.prog.set_uniform('u_closed', 'float', [0]);
  };

  LineGLGlyph.prototype._bake = function() {
    var A, I, T, V_angles, V_angles2, V_position, V_position2, V_tangents, V_tangents2, V_texcoord, V_texcoord2, Vp, Vt, _x, _y, aa, ab, i, j, k, l, m, n, ni, o, p, q, r, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, results, t, u, w, y, z;
    n = this.nvertices;
    _x = new Float32Array(this.glyph.x);
    _y = new Float32Array(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, ref = n; 0 <= ref ? l < ref : l > ref; i = 0 <= ref ? ++l : --l) {
      V_position[i * 2 + 0] = _x[i];
      V_position[i * 2 + 1] = _y[i];
    }
    this.tangents = T = new Float32Array(n * 2 - 2);
    for (i = p = 0, ref1 = n - 1; 0 <= ref1 ? p < ref1 : p > ref1; i = 0 <= ref1 ? ++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, ref2 = n - 1; 0 <= ref2 ? q < ref2 : q > ref2; i = 0 <= ref2 ? ++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, ref3 = n; 0 <= ref3 ? r < ref3 : r > ref3; i = 0 <= ref3 ? ++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 = t = 0, ref4 = n - 1; 0 <= ref4 ? t < ref4 : t > ref4; i = 0 <= ref4 ? ++t : --t) {
      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 = u = 0, ref5 = n; 0 <= ref5 ? u < ref5 : u > ref5; i = 0 <= ref5 ? ++u : --u) {
      for (j = w = 0; w < 4; j = ++w) {
        for (k = y = 0; y < 2; k = ++y) {
          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 = z = 0; z < 4; k = ++z) {
          V_tangents2[(i * 4 + j - o) * 4 + k] = V_tangents[i * 4 + k];
        }
      }
    }
    for (i = aa = 0, ref6 = n; 0 <= ref6 ? aa <= ref6 : aa >= ref6; i = 0 <= ref6 ? ++aa : --aa) {
      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 = ab = 0, ref7 = n; 0 <= ref7 ? ab < ref7 : ab > ref7; i = 0 <= ref7 ? ++ab : --ab) {
      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, ref, ref1, ref2, t;
    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, ref = n - 1; 0 <= ref ? l < ref : l > ref; i = 0 <= ref ? ++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, ref1 = n - 1; 0 <= ref1 ? p < ref1 : p > ref1; i = 0 <= ref1 ? ++p : --p) {
      cumsum += N[i];
      V_segment[(i + 1) * 2 + 0] = cumsum;
      V_segment[i * 2 + 1] = cumsum;
    }
    for (i = q = 0, ref2 = n; 0 <= ref2 ? q < ref2 : q > ref2; i = 0 <= ref2 ? ++q : --q) {
      for (j = r = 0; r < 4; j = ++r) {
        for (k = t = 0; t < 2; k = ++t) {
          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);

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 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;\n    v_linewidth = a_linewidth;\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_scale + u_offset - vec2(0.5, 0.5); // in pixels\n    pos /= u_canvas_size;  // 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 * (a_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, 0, 0]);
    this.vbo_y = new gloo2.VertexBuffer(gl);
    this.prog.set_attribute('a_y', 'float', [this.vbo_y, 0, 0]);
    this.vbo_s = new gloo2.VertexBuffer(gl);
    this.prog.set_attribute('a_size', 'float', [this.vbo_s, 0, 0]);
    this.vbo_a = new gloo2.VertexBuffer(gl);
    this.prog.set_attribute('a_angle', 'float', [this.vbo_a, 0, 0]);
    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 chunk, chunks, chunksize, i, l, nvertices, offset, p, q, ref, ref1, ref2, results, s, these_indices, uint16_index;
    nvertices = mainGlyph.glglyph.nvertices;
    if (this.data_changed) {
      this._set_data(nvertices);
      this.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 l, len, ref, results;
        ref = this.glyph.sradius;
        results = [];
        for (l = 0, len = ref.length; l < len; l++) {
          s = ref[l];
          results.push(s * 2);
        }
        return results;
      }).call(this)));
    }
    if (this.visuals_changed) {
      this._set_visuals(nvertices);
      this.visuals_changed = false;
    }
    this.prog.set_uniform('u_canvas_size', 'vec2', [trans.width, trans.height]);
    this.prog.set_uniform('u_offset', 'vec2', [trans.dx[0], trans.dy[0]]);
    this.prog.set_uniform('u_scale', 'vec2', [trans.sx, trans.sy]);
    this.prog.set_attribute('a_x', 'float', [mainGlyph.glglyph.vbo_x, 0, 0]);
    this.prog.set_attribute('a_y', 'float', [mainGlyph.glglyph.vbo_y, 0, 0]);
    this.prog.set_attribute('a_size', 'float', [mainGlyph.glglyph.vbo_s, 0, 0]);
    this.prog.set_attribute('a_angle', 'float', [mainGlyph.glglyph.vbo_a, 0, 0]);
    if (indices.length === 0) {

    } else if (indices.length === nvertices) {
      return this.prog.draw(this.gl.POINTS, [0, nvertices]);
    } else if (nvertices < 65535) {
      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 = l = 0, ref = Math.ceil(nvertices / chunksize); 0 <= ref ? l < ref : l > ref; i = 0 <= ref ? ++l : --l) {
        chunks.push([]);
      }
      for (i = p = 0, ref1 = indices.length; 0 <= ref1 ? p < ref1 : p > ref1; i = 0 <= ref1 ? ++p : --p) {
        uint16_index = indices[i] % chunksize;
        chunk = Math.floor(indices[i] / chunksize);
        chunks[chunk].push(uint16_index);
      }
      results = [];
      for (chunk = q = 0, ref2 = chunks.length; 0 <= ref2 ? q < ref2 : q > ref2; chunk = 0 <= ref2 ? ++q : --q) {
        these_indices = new Uint16Array(chunks[chunk]);
        offset = chunk * chunksize * 4;
        if (these_indices.length === 0) {
          continue;
        }
        this.prog.set_attribute('a_x', 'float', [mainGlyph.glglyph.vbo_x, 0, offset]);
        this.prog.set_attribute('a_y', 'float', [mainGlyph.glglyph.vbo_y, 0, offset]);
        this.prog.set_attribute('a_size', 'float', [mainGlyph.glglyph.vbo_s, 0, offset]);
        this.prog.set_attribute('a_angle', 'float', [mainGlyph.glglyph.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 n, s;
    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);
    this.vbo_x.set_data(0, new Float32Array(this.glyph.x));
    this.vbo_y.set_data(0, new Float32Array(this.glyph.y));
    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 l, len, ref, results;
        ref = this.glyph.sradius;
        results = [];
        for (l = 0, len = ref.length; l < len; l++) {
          s = ref[l];
          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, 'width');
    attach_color(this.prog, this.vbo_fg_color, 'a_fg_color', nvertices, this.glyph.visuals.line);
    attach_color(this.prog, this.vbo_bg_color, 'a_bg_color', nvertices, this.glyph.visuals.fill);
    return this.prog.set_uniform('u_antialias', 'float', [0.9]);
  };

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

module.exports = {
  CircleGLGlyph: CircleGLGlyph,
  SquareGLGlyph: SquareGLGlyph,
  LineGLGlyph: LineGLGlyph
};


},{"../../common/color":"common/color","gloo2":"gloo2"}],"renderer/glyph/circle":[function(require,module,exports){
var Circle, CircleView, Glyph, _, bokehgl, 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");

bokehgl = require("./bokehgl");

Glyph = require("./glyph");

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

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

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

  CircleView.prototype._init_gl = function(gl) {
    return this.glglyph = new bokehgl.CircleGLGlyph(gl, this);
  };

  CircleView.prototype._index_data = function() {
    return this._xy_index();
  };

  CircleView.prototype._map_data = function() {
    var rd, s;
    if (this.radius != null) {
      if (this.distances.radius.units === "data") {
        rd = this.fields.radius_dimension.fixed_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 hr, ref, ref1, ref2, ref3, ref4, ref5, sx0, sx1, sy0, sy1, vr, x, x0, x1, y0, y1;
    hr = this.renderer.plot_view.frame.get('h_range');
    vr = this.renderer.plot_view.frame.get('v_range');
    if ((this.radius != null) && this.distances.radius.units === "data") {
      sx0 = hr.get('start');
      sx1 = hr.get('end');
      ref = this.renderer.xmapper.v_map_from_target([sx0, sx1], true), x0 = ref[0], x1 = ref[1];
      x0 -= this.max_radius;
      x1 += this.max_radius;
      sy0 = vr.get('start');
      sy1 = vr.get('end');
      ref1 = this.renderer.ymapper.v_map_from_target([sy0, sy1], true), y0 = ref1[0], y1 = ref1[1];
      y0 -= this.max_radius;
      y1 += this.max_radius;
    } else {
      sx0 = hr.get('start') - this.max_size;
      sx1 = hr.get('end') + this.max_size;
      ref2 = this.renderer.xmapper.v_map_from_target([sx0, sx1], true), x0 = ref2[0], x1 = ref2[1];
      sy0 = vr.get('start') - this.max_size;
      sy1 = vr.get('end') + this.max_size;
      ref3 = this.renderer.ymapper.v_map_from_target([sy0, sy1], true), y0 = ref3[0], y1 = ref3[1];
    }
    if (x0 > x1) {
      ref4 = [x1, x0], x0 = ref4[0], x1 = ref4[1];
    }
    if (y0 > y1) {
      ref5 = [y1, y0], y0 = ref5[0], y1 = ref5[1];
    }
    return (function() {
      var j, len, ref6, results;
      ref6 = this.index.search([x0, y0, x1, y1]);
      results = [];
      for (j = 0, len = ref6.length; j < len; j++) {
        x = ref6[j];
        results.push(x[4].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.do_fill) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fill();
      }
      if (this.visuals.line.do_stroke) {
        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 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.distances.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];
    }
    candidates = (function() {
      var j, len, ref5, results;
      ref5 = this.index.search([x0, y0, x1, y1]);
      results = [];
      for (j = 0, len = ref5.length; j < len; j++) {
        pt = ref5[j];
        results.push(pt[4].i);
      }
      return results;
    }).call(this);
    hits = [];
    if ((this.radius != null) && this.distances.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 hits, ms, ref, ref1, ref2, ref3, ref4, ref5, result, vx, vx0, vx1, vy, vy0, vy1, x0, x1, xb, xx, y0, y1, yb;
    ref = [geometry.vx, geometry.vy], vx = ref[0], vy = ref[1];
    ref1 = this.bounds(), xb = ref1[0], yb = ref1[1];
    result = hittest.create_hit_test_result();
    if (geometry.direction === 'h') {
      y0 = yb[0];
      y1 = yb[1];
      if ((this.radius != null) && this.distances.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 = xb[0];
      x1 = xb[1];
      if ((this.radius != null) && this.distances.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];
      }
    }
    hits = (function() {
      var j, len, ref6, results;
      ref6 = this.index.search([x0, y0, x1, y1]);
      results = [];
      for (j = 0, len = ref6.length; j < len; j++) {
        xx = ref6[j];
        results.push(xx[4].i);
      }
      return results;
    }).call(this);
    result['1d'].indices = hits;
    return result;
  };

  CircleView.prototype._hit_rect = function(geometry) {
    var 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];
    result = hittest.create_hit_test_result();
    result['1d'].indices = (function() {
      var j, len, ref2, results;
      ref2 = this.index.search([x0, y0, x1, y1]);
      results = [];
      for (j = 0, len = ref2.length; j < len; j++) {
        x = ref2[j];
        results.push(x[4].i);
      }
      return results;
    }).call(this);
    return result;
  };

  CircleView.prototype._hit_poly = function(geometry) {
    var candidates, hits, i, idx, j, k, ref, ref1, ref2, result, results, sx, sy, vx, vy;
    ref = [_.clone(geometry.vx), _.clone(geometry.vy)], vx = ref[0], vy = ref[1];
    sx = this.renderer.plot_view.canvas.v_vx_to_sx(vx);
    sy = this.renderer.plot_view.canvas.v_vy_to_sy(vy);
    candidates = (function() {
      results = [];
      for (var j = 0, ref1 = this.sx.length; 0 <= ref1 ? j < ref1 : j > ref1; 0 <= ref1 ? j++ : j--){ results.push(j); }
      return results;
    }).apply(this);
    hits = [];
    for (i = k = 0, ref2 = candidates.length; 0 <= ref2 ? k < ref2 : k > ref2; i = 0 <= ref2 ? ++k : --k) {
      idx = candidates[i];
      if (hittest.point_in_poly(this.sx[i], this.sy[i], sx, sy)) {
        hits.push(idx);
      }
    }
    result = hittest.create_hit_test_result();
    result['1d'].indices = hits;
    return result;
  };

  CircleView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    var data, indices, ref, reference_point, sradius, sx, sy;
    reference_point = (ref = this.get_reference_point()) != null ? ref : 0;
    indices = [reference_point];
    sx = {};
    sx[reference_point] = (x0 + x1) / 2;
    sy = {};
    sy[reference_point] = (y0 + y1) / 2;
    sradius = {};
    sradius[reference_point] = Math.min(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 0.2;
    data = {
      sx: sx,
      sy: sy,
      sradius: sradius
    };
    return this._render(ctx, indices, data);
  };

  return CircleView;

})(Glyph.View);

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

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

  Circle.prototype.default_view = CircleView;

  Circle.prototype.type = 'Circle';

  Circle.prototype.distances = ['?radius', '?size'];

  Circle.prototype.fields = ['radius_dimension:string'];

  Circle.prototype.display_defaults = function() {
    return _.extend({}, Circle.__super__.display_defaults.call(this), {
      size: 4
    });
  };

  Circle.prototype.defaults = function() {
    return _.extend({}, Circle.__super__.defaults.call(this), {
      radius_dimension: 'x'
    });
  };

  return Circle;

})(Glyph.Model);

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


},{"../../common/hittest":"common/hittest","./bokehgl":"renderer/glyph/bokehgl","./glyph":"renderer/glyph/glyph","underscore":"underscore"}],"renderer/glyph/gear":[function(require,module,exports){
var Bezier, Gear, GearUtils, GearView, Glyph, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Glyph = require("./glyph");

GearUtils = require("gear_utils");

Bezier = require("../../util/bezier");

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

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

  GearView.prototype._index_data = function() {
    return this._xy_index();
  };

  GearView.prototype._map_data = function() {
    return this.smodule = this.sdist(this.renderer.xmapper, this.x, this.module, 'edge');
  };

  GearView.prototype._render = function(ctx, indices, arg) {
    var M, angle, fn, i, internal, j, k, l, len, pitch_radius, pressure_angle, ref, ref1, rim_radius, rot, seq, seq0, shaft_radius, shaft_size, smodule, sx, sy, teeth, x, y;
    sx = arg.sx, sy = arg.sy, smodule = arg.smodule, angle = arg.angle, teeth = arg.teeth, pressure_angle = arg.pressure_angle, shaft_size = arg.shaft_size, internal = arg.internal;
    for (k = 0, len = indices.length; k < len; k++) {
      i = indices[k];
      if (isNaN(sx[i] + sy[i] + angle[i] + smodule[i] + teeth[i] + pressure_angle[i] + shaft_size[i] + internal[i])) {
        continue;
      }
      pitch_radius = smodule[i] * teeth[i] / 2;
      if (internal[i]) {
        fn = GearUtils.create_internal_gear_tooth;
      } else {
        fn = GearUtils.create_gear_tooth;
      }
      seq0 = fn(smodule[i], teeth[i], pressure_angle[i]);
      ref = seq0.slice(0, 3), M = ref[0], x = ref[1], y = ref[2];
      seq = seq0.slice(3);
      ctx.save();
      ctx.translate(sx[i], sy[i]);
      ctx.rotate(angle[i]);
      ctx.beginPath();
      rot = 2 * Math.PI / teeth[i];
      ctx.moveTo(x, y);
      for (j = l = 0, ref1 = teeth[i]; 0 <= ref1 ? l < ref1 : l > ref1; j = 0 <= ref1 ? ++l : --l) {
        this._render_seq(ctx, seq);
        ctx.rotate(rot);
      }
      ctx.closePath();
      if (internal[i]) {
        rim_radius = pitch_radius + 2.75 * smodule[i];
        ctx.moveTo(rim_radius, 0);
        ctx.arc(0, 0, rim_radius, 0, 2 * Math.PI, true);
      } else if (shaft_size[i] > 0) {
        shaft_radius = pitch_radius * shaft_size[i];
        ctx.moveTo(shaft_radius, 0);
        ctx.arc(0, 0, shaft_radius, 0, 2 * Math.PI, true);
      }
      if (this.visuals.fill.do_fill) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fill();
      }
      if (this.visuals.line.do_stroke) {
        this.visuals.line.set_vectorize(ctx, i);
        ctx.stroke();
      }
      ctx.restore();
    }
  };

  GearView.prototype._render_seq = function(ctx, seq) {
    var c, cx0, cx1, cy0, cy1, i, k, large_arc, len, px, py, ref, ref1, ref10, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, rx, ry, segments, sweep, x, x_rotation, y;
    i = 0;
    while (i < seq.length) {
      if (_.isString(seq[i])) {
        c = seq[i];
        i += 1;
      }
      switch (c) {
        case "M":
          ref = seq.slice(i, i + 2), x = ref[0], y = ref[1];
          ctx.moveTo(x, y);
          ref1 = [x, y], px = ref1[0], py = ref1[1];
          i += 2;
          break;
        case "L":
          ref2 = seq.slice(i, i + 2), x = ref2[0], y = ref2[1];
          ctx.lineTo(x, y);
          ref3 = [x, y], px = ref3[0], py = ref3[1];
          i += 2;
          break;
        case "C":
          ref4 = seq.slice(i, i + 6), cx0 = ref4[0], cy0 = ref4[1], cx1 = ref4[2], cy1 = ref4[3], x = ref4[4], y = ref4[5];
          ctx.bezierCurveTo(cx0, cy0, cx1, cy1, x, y);
          ref5 = [x, y], px = ref5[0], py = ref5[1];
          i += 6;
          break;
        case "Q":
          ref6 = seq.slice(i, i + 4), cx0 = ref6[0], cy0 = ref6[1], x = ref6[2], y = ref6[3];
          ctx.quadraticCurveTo(cx0, cy0, x, y);
          ref7 = [x, y], px = ref7[0], py = ref7[1];
          i += 4;
          break;
        case "A":
          ref8 = seq.slice(i, i + 7), rx = ref8[0], ry = ref8[1], x_rotation = ref8[2], large_arc = ref8[3], sweep = ref8[4], x = ref8[5], y = ref8[6];
          segments = Bezier.arc_to_bezier(px, py, rx, ry, -x_rotation, large_arc, 1 - sweep, x, y);
          for (k = 0, len = segments.length; k < len; k++) {
            ref9 = segments[k], cx0 = ref9[0], cy0 = ref9[1], cx1 = ref9[2], cy1 = ref9[3], x = ref9[4], y = ref9[5];
            ctx.bezierCurveTo(cx0, cy0, cx1, cy1, x, y);
          }
          ref10 = [x, y], px = ref10[0], py = ref10[1];
          i += 7;
          break;
        default:
          throw new Error("unexpected command: " + c);
      }
    }
  };

  GearView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    return this._generic_area_legend(ctx, x0, x1, y0, y1);
  };

  return GearView;

})(Glyph.View);

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

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

  Gear.prototype.default_view = GearView;

  Gear.prototype.type = 'Gear';

  Gear.prototype.angles = ['angle'];

  Gear.prototype.fields = ['module', 'internal:bool', 'pressure_angle', 'shaft_size', 'teeth'];

  Gear.prototype.defaults = function() {
    return _.extend({}, Gear.__super__.defaults.call(this), {
      angle: 0,
      pressure_angle: 20,
      shaft_size: 0.3,
      internal: false
    });
  };

  return Gear;

})(Glyph.Model);

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


},{"../../util/bezier":"util/bezier","./glyph":"renderer/glyph/glyph","gear_utils":"gear_utils","underscore":"underscore"}],"renderer/glyph/glyph":[function(require,module,exports){
var CategoricalMapper, ContinuumView, Glyph, GlyphView, HasParent, _, arrayMax, bbox, logger, proj4, properties, rbush, toProjection,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

rbush = require("rbush");

bbox = require("../../common/bbox");

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

arrayMax = require("../../common/mathutils").arrayMax;

HasParent = require("../../common/has_parent");

ContinuumView = require("../../common/continuum_view");

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

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

proj4 = require("proj4");

toProjection = proj4.defs('GOOGLE');

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

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

  GlyphView.prototype.initialize = function(options) {
    var ctx, func, name, ref;
    GlyphView.__super__.initialize.call(this, options);
    this.renderer = options.renderer;
    ctx = this.renderer.plot_view.canvas_view.ctx;
    if (ctx.glcanvas != null) {
      this._init_gl(ctx.glcanvas.gl);
    }
    ref = properties.factories;
    for (name in ref) {
      func = ref[name];
      this[name] = {};
      this[name] = _.extend(this[name], func(this.model));
    }
    this.warned = {};
    return this;
  };

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

  GlyphView.prototype._render_gl = function(ctx, indices, mainglyph) {
    var dx, dy, ref, ref1, trans, wx, wy;
    wx = wy = 1;
    ref = this.renderer.map_to_screen([0 * wx, 1 * wx, 2 * wx], [0 * wy, 1 * wy, 2 * wy]), dx = ref[0], dy = ref[1];
    wx = 100 / Math.min(Math.max(Math.abs(dx[1] - dx[0]), 1e-12), 1e12);
    wy = 100 / Math.min(Math.max(Math.abs(dy[1] - dy[0]), 1e-12), 1e12);
    ref1 = this.renderer.map_to_screen([0 * wx, 1 * wx, 2 * wx], [0 * wy, 1 * wy, 2 * wy]), dx = ref1[0], dy = ref1[1];
    if (Math.abs((dx[1] - dx[0]) - (dx[2] - dx[1])) > 1e-6 || Math.abs((dy[1] - dy[0]) - (dy[2] - dy[1])) > 1e-6) {
      return false;
    }
    trans = {
      width: ctx.glcanvas.width,
      height: ctx.glcanvas.height,
      dx: dx,
      dy: dy,
      sx: (dx[1] - dx[0]) / wx,
      sy: (dy[1] - dy[0]) / wy
    };
    this.glglyph.draw(indices, mainglyph, trans);
    return true;
  };

  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;
      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.renderer.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.renderer.map_to_screen(this[xname], this[yname]), this[sxname] = ref6[0], this[syname] = ref6[1];
      }
    }
    return this._map_data();
  };

  GlyphView.prototype.project_xy = function(x, y) {
    var i, j, merc_x, merc_x_s, merc_y, merc_y_s, ref, ref1;
    merc_x_s = [];
    merc_y_s = [];
    for (i = j = 0, ref = x.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      ref1 = proj4(toProjection, [x[i], y[i]]), merc_x = ref1[0], merc_y = ref1[1];
      merc_x_s[i] = merc_x;
      merc_y_s[i] = merc_y;
    }
    return [merc_x_s, merc_y_s];
  };

  GlyphView.prototype.project_xsys = function(xs, ys) {
    var i, j, merc_x_s, merc_xs_s, merc_y_s, merc_ys_s, ref, ref1;
    merc_xs_s = [];
    merc_ys_s = [];
    for (i = j = 0, ref = xs.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      ref1 = this.project_xy(xs[i], ys[i]), merc_x_s = ref1[0], merc_y_s = ref1[1];
      merc_xs_s[i] = merc_x_s;
      merc_ys_s[i] = merc_y_s;
    }
    return [merc_xs_s, merc_ys_s];
  };

  GlyphView.prototype.set_data = function(source) {
    var name, prop, ref, ref1, ref2, ref3, ref4, ref5;
    ref = this.coords;
    for (name in ref) {
      prop = ref[name];
      this[name] = prop.array(source);
    }
    if (this.renderer.plot_model.use_map) {
      if (this.x != null) {
        ref1 = this.project_xy(this.x, this.y), this.x = ref1[0], this.y = ref1[1];
      }
      if (this.xs != null) {
        ref2 = this.project_xsys(this.xs, this.ys), this.xs = ref2[0], this.ys = ref2[1];
      }
    }
    ref3 = this.angles;
    for (name in ref3) {
      prop = ref3[name];
      this[name] = prop.array(source);
    }
    ref4 = this.distances;
    for (name in ref4) {
      prop = ref4[name];
      this[name] = prop.array(source);
      this["max_" + name] = arrayMax(this[name]);
    }
    ref5 = this.fields;
    for (name in ref5) {
      prop = ref5[name];
      this[name] = prop.array(source);
    }
    if (this.glglyph != null) {
      this.glglyph.set_data_changed(this.x.length);
    }
    this._set_data();
    return this.index = this._index_data();
  };

  GlyphView.prototype.set_visuals = function(source) {
    var name, prop, ref;
    ref = this.visuals;
    for (name in ref) {
      prop = ref[name];
      prop.warm_cache(source);
    }
    if (this.glglyph != null) {
      return this.glglyph.set_visuals_changed();
    }
  };

  GlyphView.prototype.bounds = function() {
    var bb;
    if (this.index == null) {
      return bbox.empty();
    }
    bb = this.index.data.bbox;
    return this._bounds([[bb[0], bb[2]], [bb[1], bb[3]]]);
  };

  GlyphView.prototype.scx = function(i) {
    return this.sx[i];
  };

  GlyphView.prototype.scy = function(i) {
    return this.sy[i];
  };

  GlyphView.prototype._init_gl = function() {
    return false;
  };

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

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

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

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

  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([
        x, y, x, 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.hit_test = function(geometry) {
    var func, result;
    result = null;
    func = "_hit_" + geometry.type;
    if (this[func] != null) {
      result = this[func](geometry);
    } else if (this.warned[geometry.type] == null) {
      logger.error("'" + geometry.type + "' selection not available for " + this.model.type);
      this.warned[geometry.type] = true;
    }
    return result;
  };

  GlyphView.prototype.get_reference_point = function() {
    var reference_point;
    reference_point = this.mget('reference_point');
    if (_.isNumber(reference_point)) {
      return this.data[reference_point];
    } else {
      return reference_point;
    }
  };

  GlyphView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    return null;
  };

  GlyphView.prototype._generic_line_legend = function(ctx, x0, x1, y0, y1) {
    var ref, reference_point;
    reference_point = (ref = this.get_reference_point()) != null ? ref : 0;
    ctx.save();
    ctx.beginPath();
    ctx.moveTo(x0, (y0 + y1) / 2);
    ctx.lineTo(x1, (y0 + y1) / 2);
    if (this.visuals.line.do_stroke) {
      this.visuals.line.set_vectorize(ctx, reference_point);
      ctx.stroke();
    }
    return ctx.restore();
  };

  GlyphView.prototype._generic_area_legend = function(ctx, x0, x1, y0, y1) {
    var dh, dw, h, indices, ref, reference_point, sx0, sx1, sy0, sy1, w;
    reference_point = (ref = this.get_reference_point()) != null ? ref : 0;
    indices = [reference_point];
    w = Math.abs(x1 - x0);
    dw = w * 0.1;
    h = Math.abs(y1 - y0);
    dh = h * 0.1;
    sx0 = x0 + dw;
    sx1 = x1 - dw;
    sy0 = y0 + dh;
    sy1 = y1 - dh;
    if (this.visuals.fill.do_fill) {
      this.visuals.fill.set_vectorize(ctx, reference_point);
      ctx.fillRect(sx0, sy0, sx1 - sx0, sy1 - sy0);
    }
    if (this.visuals.line.do_stroke) {
      ctx.beginPath();
      ctx.rect(sx0, sy0, sx1 - sx0, sy1 - sy0);
      this.visuals.line.set_vectorize(ctx, reference_point);
      return ctx.stroke();
    }
  };

  return GlyphView;

})(ContinuumView);

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

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

  Glyph.prototype.visuals = ['line', 'fill'];

  Glyph.prototype.coords = [['x', 'y']];

  Glyph.prototype.distances = [];

  Glyph.prototype.angles = [];

  Glyph.prototype.fields = [];

  Glyph.prototype.fill_defaults = {
    fill_color: 'gray',
    fill_alpha: 1.0
  };

  Glyph.prototype.line_defaults = {
    line_color: 'black',
    line_width: 1,
    line_alpha: 1.0,
    line_join: 'miter',
    line_cap: 'butt',
    line_dash: [],
    line_dash_offset: 0
  };

  Glyph.prototype.text_defaults = {
    text_font: "helvetica",
    text_font_size: "12pt",
    text_font_style: "normal",
    text_color: "#444444",
    text_alpha: 1.0,
    text_align: "left",
    text_baseline: "bottom"
  };

  Glyph.prototype.defaults = function() {
    return _.extend({
      visible: true
    });
  };

  Glyph.prototype.display_defaults = function() {
    var defaults, j, len, prop, ref, result;
    result = {};
    ref = this.visuals;
    for (j = 0, len = ref.length; j < len; j++) {
      prop = ref[j];
      switch (prop) {
        case 'line':
          defaults = this.line_defaults;
          break;
        case 'fill':
          defaults = this.fill_defaults;
          break;
        case 'text':
          defaults = this.text_defaults;
          break;
        default:
          logger.warn("unknown visual property type '" + prop + "'");
          continue;
      }
      result = _.extend(result, Glyph.__super__.display_defaults.call(this), defaults);
    }
    return result;
  };

  return Glyph;

})(HasParent);

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


},{"../../common/bbox":"common/bbox","../../common/continuum_view":"common/continuum_view","../../common/has_parent":"common/has_parent","../../common/logging":"common/logging","../../common/mathutils":"common/mathutils","../../common/properties":"common/properties","../../mapper/categorical_mapper":"mapper/categorical_mapper","proj4":"proj4","rbush":"rbush","underscore":"underscore"}],"renderer/glyph/glyph_renderer":[function(require,module,exports){
var FactorRange, GlyphRenderer, GlyphRendererView, HasParent, PlotWidget, RemoteDataSource, _, 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");

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

HasParent = require("../../common/has_parent");

PlotWidget = require("../../common/plot_widget");

FactorRange = require("../../range/factor_range");

RemoteDataSource = require("../../source/remote_data_source");

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

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

  GlyphRendererView.prototype.initialize = function(options) {
    var decimated_glyph, nonselection_glyph, selection_glyph;
    GlyphRendererView.__super__.initialize.call(this, options);
    this.glyph = this.build_glyph_view(this.mget("glyph"));
    selection_glyph = this.mget("selection_glyph");
    if (selection_glyph == null) {
      selection_glyph = this.mget("glyph").clone();
      selection_glyph.set(this.model.selection_defaults, {
        silent: true
      });
    }
    this.selection_glyph = this.build_glyph_view(selection_glyph);
    nonselection_glyph = this.mget("nonselection_glyph");
    if (nonselection_glyph == null) {
      nonselection_glyph = this.mget("glyph").clone();
      nonselection_glyph.set(this.model.nonselection_defaults, {
        silent: true
      });
    }
    this.nonselection_glyph = this.build_glyph_view(nonselection_glyph);
    decimated_glyph = this.mget("glyph").clone();
    decimated_glyph.set(this.model.decimated_defaults, {
      silent: true
    });
    this.decimated_glyph = this.build_glyph_view(decimated_glyph);
    this.xmapper = this.plot_view.frame.get('x_mappers')[this.mget("x_range_name")];
    this.ymapper = this.plot_view.frame.get('y_mappers')[this.mget("y_range_name")];
    this.set_data(false);
    if (this.mget('data_source') instanceof RemoteDataSource.RemoteDataSource) {
      return this.mget('data_source').setup(this.plot_view, this.glyph);
    }
  };

  GlyphRendererView.prototype.build_glyph_view = function(model) {
    return new model.default_view({
      model: model,
      renderer: this
    });
  };

  GlyphRendererView.prototype.bind_bokeh_events = function() {
    this.listenTo(this.model, 'change', this.request_render);
    this.listenTo(this.mget('data_source'), 'change', this.set_data);
    this.listenTo(this.mget('data_source'), 'select', this.request_render);
    return this.listenTo(this.mget('glyph'), 'propchange', function() {
      this.glyph.set_visuals(this.mget('data_source'));
      return this.request_render();
    });
  };

  GlyphRendererView.prototype.have_selection_glyphs = function() {
    return true;
  };

  GlyphRendererView.prototype.setup_server_data = function() {};

  GlyphRendererView.prototype.set_data = function(request_render, arg) {
    var dt, i, j, k, length, lod_factor, ref, results, source, t0;
    if (request_render == null) {
      request_render = true;
    }
    t0 = Date.now();
    source = this.mget('data_source');
    this.glyph.set_data(source, arg);
    this.glyph.set_visuals(source);
    this.decimated_glyph.set_visuals(source);
    this.selection_glyph.set_visuals(source);
    this.nonselection_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.get('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, j, k, len, len1, lod_threshold, nonselected, nonselection_glyph, selected, selected_mask, selection_glyph, t0, tmap, tmask, trender, tselect;
    t0 = Date.now();
    glsupport = this.glyph.glglyph;
    tmap = Date.now();
    this.glyph.map_data();
    dtmap = Date.now() - t0;
    tmask = Date.now();
    if (glsupport) {
      indices = this.all_indices;
    } else {
      indices = this.glyph._mask_data(this.all_indices);
    }
    dtmask = Date.now() - tmask;
    ctx = this.plot_view.canvas_view.ctx;
    ctx.save();
    selected = this.mget('data_source').get('selected');
    if (!selected || selected.length === 0) {
      selected = [];
    } else {
      if (selected['0d'].flag) {
        selected = indices;
      } else if (selected['1d'].indices.length > 0) {
        selected = selected['1d'].indices;
      } else if (selected['2d'].indices.length > 0) {
        selected = selected['2d'].indices;
      } else {
        selected = [];
      }
    }
    lod_threshold = this.plot_model.get('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 (!(selected.length && this.have_selection_glyphs())) {
      trender = Date.now();
      glyph.render(ctx, indices, 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);
      dtrender = Date.now() - trender;
    }
    this.last_dtrender = dtrender;
    dttot = Date.now() - t0;
    logger.debug(this.glyph.model.type + " GlyphRenderer (" + this.model.id + "): render finished in " + dttot + "ms");
    logger.trace(" - map_data finished in       : " + dtmap + "ms");
    if (dtmask != null) {
      logger.trace(" - mask_data finished in      : " + dtmask + "ms");
    }
    if (dtselect != null) {
      logger.trace(" - selection mask finished in : " + dtselect + "ms");
    }
    logger.trace(" - glyph renders finished in  : " + dtrender + "ms");
    return ctx.restore();
  };

  GlyphRendererView.prototype.map_to_screen = function(x, y) {
    return this.plot_view.map_to_screen(x, y, this.mget("x_range_name"), this.mget("y_range_name"));
  };

  GlyphRendererView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    return this.glyph.draw_legend(ctx, x0, x1, y0, y1);
  };

  GlyphRendererView.prototype.hit_test = function(geometry) {
    return this.glyph.hit_test(geometry);
  };

  return GlyphRendererView;

})(PlotWidget);

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

  GlyphRenderer.prototype.decimated_defaults = {
    fill_alpha: 0.3,
    line_alpha: 0.3,
    fill_color: "grey",
    line_color: "grey"
  };

  GlyphRenderer.prototype.nonselection_defaults = {
    fill_alpha: 0.2,
    line_alpha: 0.2
  };

  GlyphRenderer.prototype.defaults = function() {
    return _.extend({}, GlyphRenderer.__super__.defaults.call(this), {
      x_range_name: "default",
      y_range_name: "default",
      data_source: null
    });
  };

  GlyphRenderer.prototype.display_defaults = function() {
    return _.extend({}, GlyphRenderer.__super__.display_defaults.call(this), {
      level: 'glyph'
    });
  };

  return GlyphRenderer;

})(HasParent);

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


},{"../../common/has_parent":"common/has_parent","../../common/logging":"common/logging","../../common/plot_widget":"common/plot_widget","../../range/factor_range":"range/factor_range","../../source/remote_data_source":"source/remote_data_source","underscore":"underscore"}],"renderer/glyph/image":[function(require,module,exports){
var Glyph, Image, ImageView, LinearColorMapper, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

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

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

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

  ImageView.prototype._index_data = function() {
    return this._xy_index();
  };

  ImageView.prototype._set_data = function() {
    var buf, buf8, canvas, cmap, ctx, i, image_data, img, j, ref, results;
    if ((this.image_data == null) || this.image_data.length !== this.image.length) {
      this.image_data = new Array(this.image.length);
    }
    if ((this.width == null) || this.width.length !== this.image.length) {
      this.width = new Array(this.image.length);
    }
    if ((this.height == null) || this.height.length !== this.image.length) {
      this.height = new Array(this.image.length);
    }
    results = [];
    for (i = j = 0, ref = this.image.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      if (this.rows != null) {
        this.height[i] = this.rows[i];
        this.width[i] = this.cols[i];
      } else {
        this.height[i] = this.image[i].length;
        this.width[i] = this.image[i][0].length;
      }
      canvas = document.createElement('canvas');
      canvas.width = this.width[i];
      canvas.height = this.height[i];
      ctx = canvas.getContext('2d');
      image_data = ctx.getImageData(0, 0, this.width[i], this.height[i]);
      cmap = this.mget('color_mapper');
      if (this.rows != null) {
        img = this.image[i];
      } else {
        img = _.flatten(this.image[i]);
      }
      buf = cmap.v_map_screen(img);
      buf8 = new Uint8ClampedArray(buf);
      image_data.data.set(buf8);
      ctx.putImageData(image_data, 0, 0);
      this.image_data[i] = canvas;
      this.max_dw = 0;
      if (this.dw.units === "data") {
        this.max_dw = _.max(this.dw);
      }
      this.max_dh = 0;
      if (this.dh.units === "data") {
        this.max_dh = _.max(this.dh);
      }
      results.push(this._xy_index());
    }
    return results;
  };

  ImageView.prototype._map_data = function() {
    this.sw = this.sdist(this.renderer.xmapper, this.x, this.dw, 'edge', this.mget('dilate'));
    return this.sh = this.sdist(this.renderer.ymapper, this.y, this.dh, 'edge', this.mget('dilate'));
  };

  ImageView.prototype._render = function(ctx, indices, arg) {
    var i, image_data, j, len, old_smoothing, sh, sw, sx, sy, y_offset;
    image_data = arg.image_data, sx = arg.sx, sy = arg.sy, sw = arg.sw, sh = arg.sh;
    old_smoothing = ctx.getImageSmoothingEnabled();
    ctx.setImageSmoothingEnabled(false);
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (image_data[i] == null) {
        continue;
      }
      if (isNaN(sx[i] + sy[i] + sw[i] + sh[i])) {
        continue;
      }
      y_offset = sy[i];
      ctx.translate(0, y_offset);
      ctx.scale(1, -1);
      ctx.translate(0, -y_offset);
      ctx.drawImage(image_data[i], sx[i] | 0, sy[i] | 0, sw[i], sh[i]);
      ctx.translate(0, y_offset);
      ctx.scale(1, -1);
      ctx.translate(0, -y_offset);
    }
    return ctx.setImageSmoothingEnabled(old_smoothing);
  };

  ImageView.prototype.bounds = function() {
    var bb;
    bb = this.index.data.bbox;
    return [[bb[0], bb[2] + this.max_dw], [bb[1], bb[3] + this.max_dh]];
  };

  return ImageView;

})(Glyph.View);

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

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

  Image.prototype.default_view = ImageView;

  Image.prototype.type = 'Image';

  Image.prototype.visuals = [];

  Image.prototype.distances = ['dw', 'dh'];

  Image.prototype.fields = ['image:array', '?rows', '?cols', 'palette:string'];

  Image.prototype.display_defaults = function() {
    return _.extend({}, Image.__super__.display_defaults.call(this), {
      dilate: false
    });
  };

  return Image;

})(Glyph.Model);

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


},{"../../mapper/linear_color_mapper":"mapper/linear_color_mapper","./glyph":"renderer/glyph/glyph","underscore":"underscore"}],"renderer/glyph/image_rgba":[function(require,module,exports){
var Glyph, ImageRGBA, ImageRGBAView, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

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

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

  ImageRGBAView.prototype._index_data = function() {
    return this._xy_index();
  };

  ImageRGBAView.prototype._set_data = function(source, arg) {
    var buf, buf8, canvas, color, ctx, flat, i, image_data, j, k, l, ref, ref1, results;
    if ((this.image_data == null) || this.image_data.length !== this.image.length) {
      this.image_data = new Array(this.image.length);
    }
    if ((this.width == null) || this.width.length !== this.image.length) {
      this.width = new Array(this.image.length);
    }
    if ((this.height == null) || this.height.length !== this.image.length) {
      this.height = new Array(this.image.length);
    }
    results = [];
    for (i = k = 0, ref = this.image.length; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) {
      if (arg != null) {
        if (i !== arg) {
          continue;
        }
      }
      if (this.rows != null) {
        this.height[i] = this.rows[i];
        this.width[i] = this.cols[i];
      } else {
        this.height[i] = this.image[i].length;
        this.width[i] = this.image[i][0].length;
      }
      canvas = document.createElement('canvas');
      canvas.width = this.width[i];
      canvas.height = this.height[i];
      ctx = canvas.getContext('2d');
      image_data = ctx.getImageData(0, 0, this.width[i], this.height[i]);
      if (this.rows != null) {
        image_data.data.set(new Uint8ClampedArray(this.image[i]));
      } else {
        flat = _.flatten(this.image[i]);
        buf = new ArrayBuffer(flat.length * 4);
        color = new Uint32Array(buf);
        for (j = l = 0, ref1 = flat.length; 0 <= ref1 ? l < ref1 : l > ref1; j = 0 <= ref1 ? ++l : --l) {
          color[j] = flat[j];
        }
        buf8 = new Uint8ClampedArray(buf);
        image_data.data.set(buf8);
      }
      ctx.putImageData(image_data, 0, 0);
      this.image_data[i] = canvas;
      this.max_dw = 0;
      if (this.dw.units === "data") {
        this.max_dw = _.max(this.dw);
      }
      this.max_dh = 0;
      if (this.dh.units === "data") {
        results.push(this.max_dh = _.max(this.dh));
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  ImageRGBAView.prototype._map_data = function() {
    this.sw = this.sdist(this.renderer.xmapper, this.x, this.dw, 'edge', this.mget('dilate'));
    return this.sh = this.sdist(this.renderer.ymapper, this.y, this.dh, 'edge', this.mget('dilate'));
  };

  ImageRGBAView.prototype._render = function(ctx, indices, arg1) {
    var i, image_data, k, len, old_smoothing, sh, sw, sx, sy, y_offset;
    image_data = arg1.image_data, sx = arg1.sx, sy = arg1.sy, sw = arg1.sw, sh = arg1.sh;
    old_smoothing = ctx.getImageSmoothingEnabled();
    ctx.setImageSmoothingEnabled(false);
    for (k = 0, len = indices.length; k < len; k++) {
      i = indices[k];
      if (isNaN(sx[i] + sy[i] + sw[i] + sh[i])) {
        continue;
      }
      y_offset = sy[i];
      ctx.translate(0, y_offset);
      ctx.scale(1, -1);
      ctx.translate(0, -y_offset);
      ctx.drawImage(image_data[i], sx[i] | 0, sy[i] | 0, sw[i], sh[i]);
      ctx.translate(0, y_offset);
      ctx.scale(1, -1);
      ctx.translate(0, -y_offset);
    }
    return ctx.setImageSmoothingEnabled(old_smoothing);
  };

  ImageRGBAView.prototype.bounds = function() {
    var bb;
    bb = this.index.data.bbox;
    return [[bb[0], bb[2] + this.max_dw], [bb[1], bb[3] + 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.prototype.visuals = [];

  ImageRGBA.prototype.distances = ['dw', 'dh'];

  ImageRGBA.prototype.fields = ['image:array', '?rows', '?cols'];

  ImageRGBA.prototype.display_defaults = function() {
    return _.extend({}, ImageRGBA.__super__.display_defaults.call(this), {
      dilate: false
    });
  };

  return ImageRGBA;

})(Glyph.Model);

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


},{"./glyph":"renderer/glyph/glyph","underscore":"underscore"}],"renderer/glyph/image_url":[function(require,module,exports){
var Glyph, ImageURL, ImageURLView, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

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

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

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

  ImageURLView.prototype._set_data = function() {
    var i, img, j, ref, results;
    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);
    }
    results = [];
    for (i = j = 0, ref = this.url.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      img = new Image();
      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() {
    this.sw = this.sdist(this.renderer.xmapper, this.x, this.w, 'edge', this.mget('dilate'));
    return this.sh = this.sdist(this.renderer.ymapper, this.y, this.h, 'edge', this.mget('dilate'));
  };

  ImageURLView.prototype._render = function(ctx, indices, arg) {
    var angle, frame, i, image, j, len, results, sh, sw, sx, sy, url;
    url = arg.url, image = arg.image, sx = arg.sx, sy = arg.sy, sw = arg.sw, sh = arg.sh, angle = arg.angle;
    frame = this.renderer.plot_view.frame;
    ctx.rect(frame.get('left') + 1, frame.get('bottom') + 1, frame.get('width') - 2, frame.get('height') - 2);
    ctx.clip();
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + angle[i])) {
        continue;
      }
      if (image[i] == null) {
        continue;
      }
      results.push(this._render_image(ctx, i, image[i], sx, sy, sw, sh, angle));
    }
    return results;
  };

  ImageURLView.prototype._final_sx_sy = function(anchor, sx, sy, sw, sh) {
    switch (anchor) {
      case "top_left":
        return [sx, sy];
      case "top_center":
        return [sx - sw / 2, sy];
      case "top_right":
        return [sx - sw, sy];
      case "right_center":
        return [sx - sw, sy - sh / 2];
      case "bottom_right":
        return [sx - sw, sy - sh];
      case "bottom_center":
        return [sx - sw / 2, sy - sh];
      case "bottom_left":
        return [sx, sy - sh];
      case "left_center":
        return [sx, sy - sh / 2];
      case "center":
        return [sx - sw / 2, sy - sh / 2];
    }
  };

  ImageURLView.prototype._render_image = function(ctx, i, image, sx, sy, sw, sh, angle) {
    var anchor, ref;
    if (isNaN(sw[i])) {
      sw[i] = image.width;
    }
    if (isNaN(sh[i])) {
      sh[i] = image.height;
    }
    anchor = this.mget('anchor') || "top_left";
    ref = this._final_sx_sy(anchor, sx[i], sy[i], sw[i], sh[i]), sx = ref[0], sy = ref[1];
    ctx.save();
    ctx.globalAlpha = this.mget("global_alpha");
    if (angle[i]) {
      ctx.translate(sx, sy);
      ctx.rotate(angle[i]);
      ctx.drawImage(image, 0, 0, sw[i], sh[i]);
      ctx.rotate(-angle[i]);
      ctx.translate(-sx, -sy);
    } else {
      ctx.drawImage(image, sx, sy, sw[i], sh[i]);
    }
    return ctx.restore();
  };

  return ImageURLView;

})(Glyph.View);

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

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

  ImageURL.prototype.default_view = ImageURLView;

  ImageURL.prototype.type = 'ImageURL';

  ImageURL.prototype.visuals = [];

  ImageURL.prototype.distances = ['w', 'h'];

  ImageURL.prototype.angles = ['angle'];

  ImageURL.prototype.fields = ['url:string'];

  ImageURL.prototype.defaults = function() {
    return _.extend({}, ImageURL.__super__.defaults.call(this), {
      angle: 0,
      global_alpha: 1.0
    });
  };

  return ImageURL;

})(Glyph.Model);

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


},{"./glyph":"renderer/glyph/glyph","underscore":"underscore"}],"renderer/glyph/line":[function(require,module,exports){
var Glyph, Line, LineView, _, bokehgl, hittest,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Glyph = require("./glyph");

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

bokehgl = require("./bokehgl");

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

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

  LineView.prototype._init_gl = function(gl) {
    return this.glglyph = new bokehgl.LineGLGlyph(gl, this);
  };

  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, ref2, result, shortest, threshold, vx, vy, x, y;
    ref = [geometry.vx, geometry.vy], vx = ref[0], vy = ref[1];
    x = this.renderer.xmapper.map_from_target(vx);
    y = this.renderer.ymapper.map_from_target(vy);
    result = hittest.create_hit_test_result();
    point = {
      x: x,
      y: y
    };
    shortest = 100;
    threshold = 1;
    for (i = j = 0, ref1 = this.x.length - 1; 0 <= ref1 ? j < ref1 : j > ref1; i = 0 <= ref1 ? ++j : --j) {
      ref2 = [
        {
          x: this.x[i],
          y: this.y[i]
        }, {
          x: this.x[i + 1],
          y: this.y[i + 1]
        }
      ], p0 = ref2[0], p1 = ref2[1];
      dist = hittest.dist_to_segment(point, p0, p1);
      if (dist < threshold && dist < shortest) {
        shortest = dist;
        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'].flag = true;
        result['0d'].indices.push(i);
      }
    }
    return result;
  };

  LineView.prototype.get_interpolation_hit = function(i, geometry) {
    var ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, res, vx, vy, x0, x1, x2, x3, y0, y1, y2, y3;
    ref = [geometry.vx, geometry.vy], vx = ref[0], vy = ref[1];
    ref1 = [this.x[i], this.y[i], this.x[i + 1], this.y[i + 1]], x2 = ref1[0], y2 = ref1[1], x3 = ref1[2], y3 = ref1[3];
    if (geometry.type === 'point') {
      ref2 = this.renderer.ymapper.v_map_from_target([vy - 1, vy + 1]), y0 = ref2[0], y1 = ref2[1];
      ref3 = this.renderer.xmapper.v_map_from_target([vx - 1, vx + 1]), x0 = ref3[0], x1 = ref3[1];
    } else {
      if (geometry.direction === 'v') {
        ref4 = this.renderer.ymapper.v_map_from_target([vy, vy]), y0 = ref4[0], y1 = ref4[1];
        ref5 = [x2, x3], x0 = ref5[0], x1 = ref5[1];
      } else {
        ref6 = this.renderer.xmapper.v_map_from_target([vx, vx]), x0 = ref6[0], x1 = ref6[1];
        ref7 = [y2, y3], y0 = ref7[0], y1 = ref7[1];
      }
    }
    res = hittest.check_2_segments_intersect(x0, y0, x1, y1, x2, y2, x3, y3);
    return [res.x, res.y];
  };

  LineView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    return this._generic_line_legend(ctx, x0, x1, y0, y1);
  };

  return LineView;

})(Glyph.View);

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

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

  Line.prototype.default_view = LineView;

  Line.prototype.type = 'Line';

  Line.prototype.visuals = ['line'];

  return Line;

})(Glyph.Model);

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


},{"../../common/hittest":"common/hittest","./bokehgl":"renderer/glyph/bokehgl","./glyph":"renderer/glyph/glyph","underscore":"underscore"}],"renderer/glyph/marker/asterisk":[function(require,module,exports){
var Asterisk, AsteriskView, Marker, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Marker = require("./marker");

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

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

  AsteriskView.prototype._render = function(ctx, indices, arg) {
    var angle, i, j, len, r, r2, results, size, sx, sy;
    sx = arg.sx, sy = arg.sy, size = arg.size, angle = arg.angle;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + size[i] + angle[i])) {
        continue;
      }
      r = size[i] / 2;
      r2 = r * 0.65;
      ctx.beginPath();
      ctx.translate(sx[i], sy[i]);
      if (angle[i]) {
        ctx.rotate(angle[i]);
      }
      ctx.moveTo(0, r);
      ctx.lineTo(0, -r);
      ctx.moveTo(-r, 0);
      ctx.lineTo(r, 0);
      ctx.moveTo(-r2, r2);
      ctx.lineTo(r2, -r2);
      ctx.moveTo(-r2, -r2);
      ctx.lineTo(r2, r2);
      if (angle[i]) {
        ctx.rotate(-angle[i]);
      }
      if (this.visuals.line.do_stroke) {
        this.visuals.line.set_vectorize(ctx, i);
        ctx.stroke();
      }
      results.push(ctx.translate(-sx[i], -sy[i]));
    }
    return results;
  };

  return AsteriskView;

})(Marker.View);

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

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

  Asterisk.prototype.default_view = AsteriskView;

  Asterisk.prototype.type = 'Asterisk';

  Asterisk.prototype.props = ['line'];

  return Asterisk;

})(Marker.Model);

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


},{"./marker":"renderer/glyph/marker/marker","underscore":"underscore"}],"renderer/glyph/marker/circle_cross":[function(require,module,exports){
var CircleCross, CircleCrossView, Marker, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Marker = require("./marker");

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

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

  CircleCrossView.prototype._render = function(ctx, indices, arg) {
    var angle, i, j, len, r, results, size, sx, sy;
    sx = arg.sx, sy = arg.sy, size = arg.size, angle = arg.angle;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + size[i] + angle[i])) {
        continue;
      }
      r = size[i] / 2;
      ctx.beginPath();
      ctx.translate(sx[i], sy[i]);
      ctx.arc(0, 0, r, 0, 2 * Math.PI, false);
      if (this.visuals.fill.do_fill) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fill();
      }
      if (this.visuals.line.do_stroke) {
        this.visuals.line.set_vectorize(ctx, i);
        if (angle[i]) {
          ctx.rotate(angle[i]);
        }
        ctx.moveTo(0, r);
        ctx.lineTo(0, -r);
        ctx.moveTo(-r, 0);
        ctx.lineTo(r, 0);
        if (angle[i]) {
          ctx.rotate(-angle[i]);
        }
        ctx.stroke();
      }
      results.push(ctx.translate(-sx[i], -sy[i]));
    }
    return results;
  };

  return CircleCrossView;

})(Marker.View);

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

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

  CircleCross.prototype.default_view = CircleCrossView;

  CircleCross.prototype.type = 'CircleCross';

  return CircleCross;

})(Marker.Model);

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


},{"./marker":"renderer/glyph/marker/marker","underscore":"underscore"}],"renderer/glyph/marker/circle_x":[function(require,module,exports){
var CircleX, CircleXView, Marker, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Marker = require("./marker");

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

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

  CircleXView.prototype._render = function(ctx, indices, arg) {
    var angle, i, j, len, r, results, size, sx, sy;
    sx = arg.sx, sy = arg.sy, size = arg.size, angle = arg.angle;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + size[i] + angle[i])) {
        continue;
      }
      r = size[i] / 2;
      ctx.beginPath();
      ctx.translate(sx[i], sy[i]);
      ctx.arc(0, 0, r, 0, 2 * Math.PI, false);
      if (this.visuals.fill.do_fill) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fill();
      }
      if (this.visuals.line.do_stroke) {
        this.visuals.line.set_vectorize(ctx, i);
        if (angle[i]) {
          ctx.rotate(angle[i]);
        }
        ctx.moveTo(-r, r);
        ctx.lineTo(r, -r);
        ctx.moveTo(-r, -r);
        ctx.lineTo(r, r);
        if (angle[i]) {
          ctx.rotate(-angle[i]);
        }
        ctx.stroke();
      }
      results.push(ctx.translate(-sx[i], -sy[i]));
    }
    return results;
  };

  return CircleXView;

})(Marker.View);

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

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

  CircleX.prototype.default_view = CircleXView;

  CircleX.prototype.type = 'CircleX';

  return CircleX;

})(Marker.Model);

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


},{"./marker":"renderer/glyph/marker/marker","underscore":"underscore"}],"renderer/glyph/marker/cross":[function(require,module,exports){
var Cross, CrossView, Marker, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Marker = require("./marker");

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

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

  CrossView.prototype._render = function(ctx, indices, arg) {
    var angle, i, j, len, r, results, size, sx, sy;
    sx = arg.sx, sy = arg.sy, size = arg.size, angle = arg.angle;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + size[i] + angle[i])) {
        continue;
      }
      r = size[i] / 2;
      ctx.beginPath();
      ctx.translate(sx[i], sy[i]);
      if (angle[i]) {
        ctx.rotate(angle[i]);
      }
      ctx.moveTo(0, r);
      ctx.lineTo(0, -r);
      ctx.moveTo(-r, 0);
      ctx.lineTo(r, 0);
      if (angle[i]) {
        ctx.rotate(-angle[i]);
      }
      if (this.visuals.line.do_stroke) {
        this.visuals.line.set_vectorize(ctx, i);
        if (angle[i]) {
          ctx.rotate(angle[i]);
        }
        ctx.stroke();
        if (angle[i]) {
          ctx.rotate(-angle[i]);
        }
      }
      results.push(ctx.translate(-sx[i], -sy[i]));
    }
    return results;
  };

  return CrossView;

})(Marker.View);

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

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

  Cross.prototype.default_view = CrossView;

  Cross.prototype.type = 'Cross';

  Cross.prototype.props = ['line'];

  return Cross;

})(Marker.Model);

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


},{"./marker":"renderer/glyph/marker/marker","underscore":"underscore"}],"renderer/glyph/marker/diamond":[function(require,module,exports){
var Diamond, DiamondView, Marker, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Marker = require("./marker");

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

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

  DiamondView.prototype._render = function(ctx, indices, arg) {
    var angle, i, j, len, r, results, size, sx, sy;
    sx = arg.sx, sy = arg.sy, size = arg.size, angle = arg.angle;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + size[i] + angle[i])) {
        continue;
      }
      r = size[i] / 2;
      ctx.beginPath();
      ctx.translate(sx[i], sy[i]);
      if (angle[i]) {
        ctx.rotate(angle[i]);
      }
      ctx.moveTo(0, r);
      ctx.lineTo(r / 1.5, 0);
      ctx.lineTo(0, -r);
      ctx.lineTo(-r / 1.5, 0);
      if (angle[i]) {
        ctx.rotate(-angle[i]);
      }
      ctx.translate(-sx[i], -sy[i]);
      ctx.closePath();
      if (this.visuals.fill.do_fill) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fill();
      }
      if (this.visuals.line.do_stroke) {
        this.visuals.line.set_vectorize(ctx, i);
        results.push(ctx.stroke());
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  return DiamondView;

})(Marker.View);

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

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

  Diamond.prototype.default_view = DiamondView;

  Diamond.prototype.type = 'Diamond';

  return Diamond;

})(Marker.Model);

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


},{"./marker":"renderer/glyph/marker/marker","underscore":"underscore"}],"renderer/glyph/marker/diamond_cross":[function(require,module,exports){
var DiamondCross, DiamondCrossView, Marker, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Marker = require("./marker");

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

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

  DiamondCrossView.prototype._render = function(ctx, indices, arg) {
    var angle, i, j, len, r, results, size, sx, sy;
    sx = arg.sx, sy = arg.sy, size = arg.size, angle = arg.angle;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + size[i] + angle[i])) {
        continue;
      }
      r = size[i] / 2;
      ctx.beginPath();
      ctx.translate(sx[i], sy[i]);
      if (angle[i]) {
        ctx.rotate(angle[i]);
      }
      ctx.moveTo(0, r);
      ctx.lineTo(r / 1.5, 0);
      ctx.lineTo(0, -r);
      ctx.lineTo(-r / 1.5, 0);
      if (angle[i]) {
        ctx.rotate(-angle[i]);
      }
      ctx.closePath();
      if (this.visuals.fill.do_fill) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fill();
      }
      if (this.visuals.line.do_stroke) {
        this.visuals.line.set_vectorize(ctx, i);
        if (angle[i]) {
          ctx.rotate(angle[i]);
        }
        ctx.moveTo(0, r);
        ctx.lineTo(0, -r);
        ctx.moveTo(-r / 1.5, 0);
        ctx.lineTo(r / 1.5, 0);
        if (angle[i]) {
          ctx.rotate(-angle[i]);
        }
        ctx.stroke();
      }
      results.push(ctx.translate(-sx[i], -sy[i]));
    }
    return results;
  };

  return DiamondCrossView;

})(Marker.View);

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

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

  DiamondCross.prototype.default_view = DiamondCrossView;

  DiamondCross.prototype.type = 'DiamondCross';

  return DiamondCross;

})(Marker.Model);

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


},{"./marker":"renderer/glyph/marker/marker","underscore":"underscore"}],"renderer/glyph/marker/inverted_triangle":[function(require,module,exports){
var InvertedTriangle, InvertedTriangleView, Marker, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Marker = require("./marker");

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

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

  InvertedTriangleView.prototype._render = function(ctx, indices, arg) {
    var a, angle, h, i, j, len, r, results, size, sx, sy;
    sx = arg.sx, sy = arg.sy, size = arg.size, angle = arg.angle;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + size[i] + angle[i])) {
        continue;
      }
      a = size[i] * Math.sqrt(3) / 6;
      r = size[i] / 2;
      h = size[i] * Math.sqrt(3) / 2;
      ctx.beginPath();
      ctx.translate(sx[i], sy[i]);
      if (angle[i]) {
        ctx.rotate(angle[i]);
      }
      ctx.moveTo(-r, -a);
      ctx.lineTo(r, -a);
      ctx.lineTo(0, -a + h);
      if (angle[i]) {
        ctx.rotate(-angle[i]);
      }
      ctx.translate(-sx[i], -sy[i]);
      ctx.closePath();
      if (this.visuals.fill.do_fill) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fill();
      }
      if (this.visuals.line.do_stroke) {
        this.visuals.line.set_vectorize(ctx, i);
        results.push(ctx.stroke());
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  return InvertedTriangleView;

})(Marker.View);

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

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

  InvertedTriangle.prototype.default_view = InvertedTriangleView;

  InvertedTriangle.prototype.type = 'InvertedTriangle';

  return InvertedTriangle;

})(Marker.Model);

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


},{"./marker":"renderer/glyph/marker/marker","underscore":"underscore"}],"renderer/glyph/marker/marker":[function(require,module,exports){
var Glyph, Marker, MarkerView, _, hittest,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Glyph = require("../glyph");

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

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

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

  MarkerView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    var angle, data, indices, ref, reference_point, size, sx, sy;
    reference_point = (ref = this.get_reference_point()) != null ? ref : 0;
    indices = [reference_point];
    sx = {};
    sx[reference_point] = (x0 + x1) / 2;
    sy = {};
    sy[reference_point] = (y0 + y1) / 2;
    size = {};
    size[reference_point] = Math.min(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 0.4;
    angle = {};
    angle[reference_point] = 0;
    data = {
      sx: sx,
      sy: sy,
      size: size,
      angle: angle
    };
    return this._render(ctx, indices, data);
  };

  MarkerView.prototype._index_data = function() {
    return this._xy_index();
  };

  MarkerView.prototype._mask_data = function(all_indices) {
    var hr, ref, ref1, ref2, ref3, vr, vx0, vx1, vy0, vy1, x, x0, x1, y0, y1;
    hr = this.renderer.plot_view.frame.get('h_range');
    vx0 = hr.get('start') - this.max_size;
    vx1 = hr.get('end') + this.max_size;
    ref = this.renderer.xmapper.v_map_from_target([vx0, vx1], true), x0 = ref[0], x1 = ref[1];
    ref1 = [Math.min(x0, x1), Math.max(x0, x1)], x0 = ref1[0], x1 = ref1[1];
    vr = this.renderer.plot_view.frame.get('v_range');
    vy0 = vr.get('start') - this.max_size;
    vy1 = vr.get('end') + this.max_size;
    ref2 = this.renderer.ymapper.v_map_from_target([vy0, vy1], true), y0 = ref2[0], y1 = ref2[1];
    ref3 = [Math.min(y0, y1), Math.max(y0, y1)], y0 = ref3[0], y1 = ref3[1];
    return (function() {
      var j, len, ref4, results;
      ref4 = this.index.search([x0, y0, x1, y1]);
      results = [];
      for (j = 0, len = ref4.length; j < len; j++) {
        x = ref4[j];
        results.push(x[4].i);
      }
      return results;
    }).call(this);
  };

  MarkerView.prototype._hit_point = function(geometry) {
    var 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];
    candidates = (function() {
      var j, len, ref3, results;
      ref3 = this.index.search([x0, y0, x1, y1]);
      results = [];
      for (j = 0, len = ref3.length; j < len; j++) {
        x = ref3[j];
        results.push(x[4].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 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];
    result = hittest.create_hit_test_result();
    result['1d'].indices = (function() {
      var j, len, ref2, results;
      ref2 = this.index.search([x0, y0, x1, y1]);
      results = [];
      for (j = 0, len = ref2.length; j < len; j++) {
        x = ref2[j];
        results.push(x[4].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.prototype.distances = ['size'];

  Marker.prototype.angles = ['angle'];

  Marker.prototype.display_defaults = function() {
    return _.extend({}, Marker.__super__.display_defaults.call(this), {
      size: 4,
      angle: 0
    });
  };

  return Marker;

})(Glyph.Model);

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


},{"../../../common/hittest":"common/hittest","../glyph":"renderer/glyph/glyph","underscore":"underscore"}],"renderer/glyph/marker/square":[function(require,module,exports){
var Marker, Square, SquareView, _, bokehgl,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Marker = require("./marker");

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

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

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

  SquareView.prototype._init_gl = function(gl) {
    return this.glglyph = new bokehgl.SquareGLGlyph(gl, this);
  };

  SquareView.prototype._render = function(ctx, indices, arg) {
    var angle, i, j, len, results, size, sx, sy;
    sx = arg.sx, sy = arg.sy, size = arg.size, angle = arg.angle;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + size[i] + angle[i])) {
        continue;
      }
      ctx.beginPath();
      ctx.translate(sx[i], sy[i]);
      if (angle[i]) {
        ctx.rotate(angle[i]);
      }
      ctx.rect(-size[i] / 2, -size[i] / 2, size[i], size[i]);
      if (angle[i]) {
        ctx.rotate(-angle[i]);
      }
      if (this.visuals.fill.do_fill) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fill();
      }
      if (this.visuals.line.do_stroke) {
        this.visuals.line.set_vectorize(ctx, i);
        ctx.stroke();
      }
      results.push(ctx.translate(-sx[i], -sy[i]));
    }
    return results;
  };

  return SquareView;

})(Marker.View);

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

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

  Square.prototype.default_view = SquareView;

  Square.prototype.type = 'Square';

  return Square;

})(Marker.Model);

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


},{"../bokehgl":"renderer/glyph/bokehgl","./marker":"renderer/glyph/marker/marker","underscore":"underscore"}],"renderer/glyph/marker/square_cross":[function(require,module,exports){
var Marker, SquareCross, SquareCrossView, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Marker = require("./marker");

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

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

  SquareCrossView.prototype._render = function(ctx, indices, arg) {
    var angle, i, j, len, r, results, size, sx, sy;
    sx = arg.sx, sy = arg.sy, size = arg.size, angle = arg.angle;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + size[i] + angle[i])) {
        continue;
      }
      ctx.beginPath();
      ctx.translate(sx[i], sy[i]);
      if (angle[i]) {
        ctx.rotate(angle[i]);
      }
      ctx.rect(-size[i] / 2, -size[i] / 2, size[i], size[i]);
      if (angle[i]) {
        ctx.rotate(-angle[i]);
      }
      if (this.visuals.fill.do_fill) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fill();
      }
      if (this.visuals.line.do_stroke) {
        this.visuals.line.set_vectorize(ctx, i);
        r = size[i] / 2;
        if (angle[i]) {
          ctx.rotate(angle[i]);
        }
        ctx.moveTo(0, r);
        ctx.lineTo(0, -r);
        ctx.moveTo(-r, 0);
        ctx.lineTo(r, 0);
        if (angle[i]) {
          ctx.rotate(-angle[i]);
        }
        ctx.stroke();
      }
      results.push(ctx.translate(-sx[i], -sy[i]));
    }
    return results;
  };

  return SquareCrossView;

})(Marker.View);

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

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

  SquareCross.prototype.default_view = SquareCrossView;

  SquareCross.prototype.type = 'SquareCross';

  return SquareCross;

})(Marker.Model);

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


},{"./marker":"renderer/glyph/marker/marker","underscore":"underscore"}],"renderer/glyph/marker/square_x":[function(require,module,exports){
var Marker, SquareX, SquareXView, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Marker = require("./marker");

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

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

  SquareXView.prototype._render = function(ctx, indices, arg) {
    var angle, i, j, len, r, results, size, sx, sy;
    sx = arg.sx, sy = arg.sy, size = arg.size, angle = arg.angle;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + size[i] + angle[i])) {
        continue;
      }
      ctx.beginPath();
      ctx.translate(sx[i], sy[i]);
      if (angle[i]) {
        ctx.rotate(angle[i]);
      }
      ctx.rect(-size[i] / 2, -size[i] / 2, size[i], size[i]);
      if (angle[i]) {
        ctx.rotate(-angle[i]);
      }
      if (this.visuals.fill.do_fill) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fill();
      }
      if (this.visuals.line.do_stroke) {
        this.visuals.line.set_vectorize(ctx, i);
        ctx.stroke();
        r = size[i] / 2;
        if (angle[i]) {
          ctx.rotate(angle[i]);
        }
        ctx.moveTo(-r, r);
        ctx.lineTo(r, -r);
        ctx.moveTo(-r, -r);
        ctx.lineTo(r, r);
        if (angle[i]) {
          ctx.rotate(-angle[i]);
        }
        ctx.stroke();
      }
      results.push(ctx.translate(-sx[i], -sy[i]));
    }
    return results;
  };

  return SquareXView;

})(Marker.View);

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

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

  SquareX.prototype.default_view = SquareXView;

  SquareX.prototype.type = 'SquareX';

  return SquareX;

})(Marker.Model);

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


},{"./marker":"renderer/glyph/marker/marker","underscore":"underscore"}],"renderer/glyph/marker/triangle":[function(require,module,exports){
var Marker, Triangle, TriangleView, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Marker = require("./marker");

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

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

  TriangleView.prototype._render = function(ctx, indices, arg) {
    var a, angle, h, i, j, len, r, results, size, sx, sy;
    sx = arg.sx, sy = arg.sy, size = arg.size, angle = arg.angle;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + size[i] + angle[i])) {
        continue;
      }
      a = size[i] * Math.sqrt(3) / 6;
      r = size[i] / 2;
      h = size[i] * Math.sqrt(3) / 2;
      ctx.beginPath();
      ctx.translate(sx[i], sy[i]);
      if (angle[i]) {
        ctx.rotate(angle[i]);
      }
      ctx.moveTo(-r, a);
      ctx.lineTo(r, a);
      ctx.lineTo(0, a - h);
      if (angle[i]) {
        ctx.rotate(-angle[i]);
      }
      ctx.translate(-sx[i], -sy[i]);
      ctx.closePath();
      if (this.visuals.fill.do_fill) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fill();
      }
      if (this.visuals.line.do_stroke) {
        this.visuals.line.set_vectorize(ctx, i);
        results.push(ctx.stroke());
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  return TriangleView;

})(Marker.View);

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

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

  Triangle.prototype.default_view = TriangleView;

  Triangle.prototype.type = 'Triangle';

  return Triangle;

})(Marker.Model);

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


},{"./marker":"renderer/glyph/marker/marker","underscore":"underscore"}],"renderer/glyph/marker/x":[function(require,module,exports){
var Marker, X, XView, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Marker = require("./marker");

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

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

  XView.prototype._render = function(ctx, indices, arg) {
    var angle, i, j, len, r, results, size, sx, sy;
    sx = arg.sx, sy = arg.sy, size = arg.size, angle = arg.angle;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + size[i] + angle[i])) {
        continue;
      }
      r = size[i] / 2;
      ctx.beginPath();
      ctx.translate(sx[i], sy[i]);
      if (angle[i]) {
        ctx.rotate(angle[i]);
      }
      ctx.moveTo(-r, r);
      ctx.lineTo(r, -r);
      ctx.moveTo(-r, -r);
      ctx.lineTo(r, r);
      if (angle[i]) {
        ctx.rotate(-angle[i]);
      }
      if (this.visuals.line.do_stroke) {
        this.visuals.line.set_vectorize(ctx, i);
        ctx.stroke();
      }
      results.push(ctx.translate(-sx[i], -sy[i]));
    }
    return results;
  };

  return XView;

})(Marker.View);

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

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

  X.prototype.default_view = XView;

  X.prototype.type = 'X';

  X.prototype.props = ['line'];

  return X;

})(Marker.Model);

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


},{"./marker":"renderer/glyph/marker/marker","underscore":"underscore"}],"renderer/glyph/multi_line":[function(require,module,exports){
var Glyph, MultiLine, MultiLineView, _, rbush,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

rbush = require("rbush");

Glyph = require("./glyph");

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

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

  MultiLineView.prototype._index_data = function() {
    var i, index, k, pts, ref, x, xs, y, ys;
    index = rbush();
    pts = [];
    for (i = k = 0, ref = this.xs.length; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) {
      xs = (function() {
        var l, len, ref1, results;
        ref1 = this.xs[i];
        results = [];
        for (l = 0, len = ref1.length; l < len; l++) {
          x = ref1[l];
          if (!_.isNaN(x)) {
            results.push(x);
          }
        }
        return results;
      }).call(this);
      ys = (function() {
        var l, len, ref1, results;
        ref1 = this.ys[i];
        results = [];
        for (l = 0, len = ref1.length; l < len; l++) {
          y = ref1[l];
          if (!_.isNaN(y)) {
            results.push(y);
          }
        }
        return results;
      }).call(this);
      if (xs.length === 0) {
        continue;
      }
      pts.push([
        _.min(xs), _.min(ys), _.max(xs), _.max(ys), {
          'i': i
        }
      ]);
    }
    index.load(pts);
    return index;
  };

  MultiLineView.prototype._render = function(ctx, indices, arg) {
    var i, j, k, l, len, ref, ref1, results, sx, sxs, sy, sys;
    sxs = arg.sxs, sys = arg.sys;
    results = [];
    for (k = 0, len = indices.length; k < len; k++) {
      i = indices[k];
      ref = [sxs[i], sys[i]], sx = ref[0], sy = ref[1];
      this.visuals.line.set_vectorize(ctx, i);
      for (j = l = 0, ref1 = sx.length; 0 <= ref1 ? l < ref1 : l > ref1; j = 0 <= ref1 ? ++l : --l) {
        if (j === 0) {
          ctx.beginPath();
          ctx.moveTo(sx[j], sy[j]);
          continue;
        } else if (isNaN(sx[j]) || isNaN(sy[j])) {
          ctx.stroke();
          ctx.beginPath();
          continue;
        } else {
          ctx.lineTo(sx[j], sy[j]);
        }
      }
      results.push(ctx.stroke());
    }
    return results;
  };

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

  return MultiLineView;

})(Glyph.View);

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

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

  MultiLine.prototype.default_view = MultiLineView;

  MultiLine.prototype.type = 'MultiLine';

  MultiLine.prototype.visuals = ['line'];

  MultiLine.prototype.coords = [['xs', 'ys']];

  return MultiLine;

})(Glyph.Model);

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


},{"./glyph":"renderer/glyph/glyph","rbush":"rbush","underscore":"underscore"}],"renderer/glyph/oval":[function(require,module,exports){
var Glyph, Oval, OvalView, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

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.distances.width.units === "data") {
      this.max_w2 = this.max_width / 2;
    }
    this.max_h2 = 0;
    if (this.distances.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.distances.width.units === "data") {
      this.sw = this.sdist(this.renderer.xmapper, this.x, this.width, 'center');
    } else {
      this.sw = this.width;
    }
    if (this.distances.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.do_fill) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fill();
      }
      if (this.visuals.line.do_stroke) {
        this.visuals.line.set_vectorize(ctx, i);
        ctx.stroke();
      }
      ctx.rotate(-this.angle[i]);
      results.push(ctx.translate(-sx[i], -sy[i]));
    }
    return results;
  };

  OvalView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    var d, indices, ref, reference_point, scale, sh, sw, sx, sy;
    reference_point = (ref = this.get_reference_point()) != null ? ref : 0;
    indices = [reference_point];
    sx = {};
    sx[reference_point] = (x0 + x1) / 2;
    sy = {};
    sy[reference_point] = (y0 + y1) / 2;
    scale = this.sw[reference_point] / this.sh[reference_point];
    d = Math.min(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 0.8;
    sw = {};
    sh = {};
    if (scale > 1) {
      sw[reference_point] = d;
      sh[reference_point] = d / scale;
    } else {
      sw[reference_point] = d * scale;
      sh[reference_point] = d;
    }
    return this._render(ctx, indices, sx, sy, sw, sh);
  };

  OvalView.prototype._bounds = function(bds) {
    return [[bds[0][0] - this.max_w2, bds[0][1] + this.max_w2], [bds[1][0] - this.max_h2, bds[1][1] + this.max_h2]];
  };

  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.prototype.distances = ['width', 'height'];

  Oval.prototype.angles = ['angle'];

  Oval.prototype.display_defaults = function() {
    return _.extend({}, Oval.__super__.display_defaults.call(this), {
      angle: 0.0
    });
  };

  return Oval;

})(Glyph.Model);

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


},{"./glyph":"renderer/glyph/glyph","underscore":"underscore"}],"renderer/glyph/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.do_fill) {
      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.do_stroke) {
      this.visuals.line.set_value(ctx);
      for (k = 0, len1 = indices.length; k < len1; k++) {
        i = indices[k];
        if (i === 0) {
          ctx.beginPath();
          ctx.moveTo(sx[i], sy[i]);
          continue;
        } else if (isNaN(sx[i] + sy[i])) {
          ctx.closePath();
          ctx.stroke();
          ctx.beginPath();
          continue;
        } else {
          ctx.lineTo(sx[i], sy[i]);
        }
      }
      ctx.closePath();
      return ctx.stroke();
    }
  };

  PatchView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    return this._generic_area_legend(ctx, x0, x1, y0, y1);
  };

  return PatchView;

})(Glyph.View);

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

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

  Patch.prototype.default_view = PatchView;

  Patch.prototype.type = 'Patch';

  return Patch;

})(Glyph.Model);

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


},{"./glyph":"renderer/glyph/glyph","underscore":"underscore"}],"renderer/glyph/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");

Glyph = require("./glyph");

rbush = require("rbush");

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

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

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

  PatchesView.prototype._build_discontinuous_object = function(nanned_qs) {
    var denanned, ds, i, k, nan_index, q, qs, qs_part, ref;
    ds = {};
    for (i = k = 0, ref = nanned_qs.length; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) {
      ds[i] = [];
      qs = _.toArray(nanned_qs[i]);
      while (qs.length > 0) {
        nan_index = _.findLastIndex(qs, function(q) {
          return _.isNaN(q);
        });
        if (nan_index >= 0) {
          qs_part = qs.splice(nan_index);
        } else {
          qs_part = qs;
          qs = [];
        }
        denanned = (function() {
          var l, len, results;
          results = [];
          for (l = 0, len = qs_part.length; l < len; l++) {
            q = qs_part[l];
            if (!_.isNaN(q)) {
              results.push(q);
            }
          }
          return results;
        })();
        ds[i].push(denanned);
      }
    }
    return ds;
  };

  PatchesView.prototype._index_data = function() {
    var i, index, j, k, l, pts, ref, ref1, xs, xss, ys, yss;
    index = rbush();
    pts = [];
    xss = this._build_discontinuous_object(this.xs);
    yss = this._build_discontinuous_object(this.ys);
    for (i = k = 0, ref = this.xs.length; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) {
      for (j = l = 0, ref1 = xss[i].length; 0 <= ref1 ? l < ref1 : l > ref1; j = 0 <= ref1 ? ++l : --l) {
        xs = xss[i][j];
        ys = yss[i][j];
        if (xs.length === 0) {
          continue;
        }
        pts.push([
          _.min(xs), _.min(ys), _.max(xs), _.max(ys), {
            'i': i
          }
        ]);
      }
    }
    index.load(pts);
    return index;
  };

  PatchesView.prototype._mask_data = function(all_indices) {
    var ref, ref1, x, x0, x1, xr, y0, y1, yr;
    xr = this.renderer.plot_view.x_range;
    ref = [xr.get('min'), xr.get('max')], x0 = ref[0], x1 = ref[1];
    yr = this.renderer.plot_view.y_range;
    ref1 = [yr.get('min'), yr.get('max')], y0 = ref1[0], y1 = ref1[1];
    return (function() {
      var k, len, ref2, results;
      ref2 = this.index.search([x0, y0, x1, y1]);
      results = [];
      for (k = 0, len = ref2.length; k < len; k++) {
        x = ref2[k];
        results.push(x[4].i);
      }
      return results;
    }).call(this);
  };

  PatchesView.prototype._render = function(ctx, indices, arg) {
    var i, j, k, l, len, m, ref, ref1, ref2, results, sx, sxs, sy, sys;
    sxs = arg.sxs, sys = arg.sys;
    this.sxss = this._build_discontinuous_object(sxs);
    this.syss = this._build_discontinuous_object(sys);
    results = [];
    for (k = 0, len = indices.length; k < len; k++) {
      i = indices[k];
      ref = [sxs[i], sys[i]], sx = ref[0], sy = ref[1];
      if (this.visuals.fill.do_fill) {
        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.do_stroke) {
        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([x, y, x, y]);
      results = [];
      for (k = 0, len = ref1.length; k < len; k++) {
        x = ref1[k];
        results.push(x[4].i);
      }
      return results;
    }).call(this);
    hits = [];
    for (i = k = 0, ref1 = candidates.length; 0 <= ref1 ? k < ref1 : k > ref1; i = 0 <= ref1 ? ++k : --k) {
      idx = candidates[i];
      sxs = this.sxss[idx];
      sys = this.syss[idx];
      for (j = l = 0, ref2 = sxs.length; 0 <= ref2 ? l < ref2 : l > ref2; j = 0 <= ref2 ? ++l : --l) {
        if (hittest.point_in_poly(sx, sy, sxs[j], sys[j])) {
          hits.push(idx);
        }
      }
    }
    result = hittest.create_hit_test_result();
    result['1d'].indices = hits;
    return result;
  };

  PatchesView.prototype._get_snap_coord = function(array) {
    var k, len, s, sum;
    sum = 0;
    for (k = 0, len = array.length; k < len; k++) {
      s = array[k];
      sum += s;
    }
    return sum / array.length;
  };

  PatchesView.prototype.scx = function(i, sx, sy) {
    var j, k, ref, sxs, sys;
    if (this.sxss[i].length === 1) {
      return this._get_snap_coord(this.sxs[i]);
    } else {
      sxs = this.sxss[i];
      sys = this.syss[i];
      for (j = k = 0, ref = sxs.length; 0 <= ref ? k < ref : k > ref; j = 0 <= ref ? ++k : --k) {
        if (hittest.point_in_poly(sx, sy, sxs[j], sys[j])) {
          return this._get_snap_coord(sxs[j]);
        }
      }
    }
    return null;
  };

  PatchesView.prototype.scy = function(i, sx, sy) {
    var j, k, ref, sxs, sys;
    if (this.syss[i].length === 1) {
      return this._get_snap_coord(this.sys[i]);
    } else {
      sxs = this.sxss[i];
      sys = this.syss[i];
      for (j = k = 0, ref = sxs.length; 0 <= ref ? k < ref : k > ref; j = 0 <= ref ? ++k : --k) {
        if (hittest.point_in_poly(sx, sy, sxs[j], sys[j])) {
          return this._get_snap_coord(sys[j]);
        }
      }
    }
  };

  PatchesView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    return this._generic_area_legend(ctx, x0, x1, y0, y1);
  };

  return PatchesView;

})(Glyph.View);

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

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

  Patches.prototype.default_view = PatchesView;

  Patches.prototype.type = 'Patches';

  Patches.prototype.coords = [['xs', 'ys']];

  return Patches;

})(Glyph.Model);

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


},{"../../common/hittest":"common/hittest","./glyph":"renderer/glyph/glyph","rbush":"rbush","underscore":"underscore"}],"renderer/glyph/quad":[function(require,module,exports){
var 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");

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

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

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

  QuadView.prototype._index_data = function() {
    var i, index, j, pts, ref;
    index = rbush();
    pts = [];
    for (i = j = 0, ref = this.left.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      if (!isNaN(this.left[i] + this.right[i] + this.top[i] + this.bottom[i])) {
        pts.push([
          this.left[i], this.bottom[i], this.right[i], this.top[i], {
            '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.do_fill) {
        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.do_stroke) {
        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([x, y, x, y]);
      results = [];
      for (j = 0, len = ref1.length; j < len; j++) {
        x = ref1[j];
        results.push(x[4].i);
      }
      return results;
    }).call(this);
    result = hittest.create_hit_test_result();
    result['1d'].indices = hits;
    return result;
  };

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

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

  QuadView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    return this._generic_area_legend(ctx, x0, x1, y0, y1);
  };

  return QuadView;

})(Glyph.View);

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

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

  Quad.prototype.default_view = QuadView;

  Quad.prototype.type = 'Quad';

  Quad.prototype.coords = [['right', 'bottom'], ['left', 'top']];

  return Quad;

})(Glyph.Model);

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


},{"../../common/hittest":"common/hittest","./glyph":"renderer/glyph/glyph","rbush":"rbush","underscore":"underscore"}],"renderer/glyph/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([
        x0, y0, x1, 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.do_stroke) {
      results = [];
      for (j = 0, len = indices.length; j < len; j++) {
        i = indices[j];
        if (isNaN(sx0[i] + sy0[i] + sx1[i] + sy1[i] + scx[i] + scy[i])) {
          continue;
        }
        ctx.beginPath();
        ctx.moveTo(sx0[i], sy0[i]);
        ctx.quadraticCurveTo(scx[i], scy[i], sx1[i], sy1[i]);
        this.visuals.line.set_vectorize(ctx, i);
        results.push(ctx.stroke());
      }
      return results;
    }
  };

  QuadraticView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    return this._generic_line_legend(ctx, x0, x1, y0, y1);
  };

  return QuadraticView;

})(Glyph.View);

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

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

  Quadratic.prototype.default_view = QuadraticView;

  Quadratic.prototype.type = 'Quadratic';

  Quadratic.prototype.visuals = ['line'];

  Quadratic.prototype.coords = [['x0', 'y0'], ['x1', 'y1'], ['cx', 'cy']];

  return Quadratic;

})(Glyph.Model);

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


},{"./glyph":"renderer/glyph/glyph","rbush":"rbush","underscore":"underscore"}],"renderer/glyph/ray":[function(require,module,exports){
var Glyph, Ray, RayView, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

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.do_stroke) {
      width = this.renderer.plot_view.frame.get('width');
      height = this.renderer.plot_view.frame.get('height');
      inf_len = 2 * (width + height);
      for (i = j = 0, ref = slength.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
        if (slength[i] === 0) {
          slength[i] = inf_len;
        }
      }
      results = [];
      for (k = 0, len = indices.length; k < len; k++) {
        i = indices[k];
        if (isNaN(sx[i] + sy[i] + angle[i] + slength[i])) {
          continue;
        }
        ctx.translate(sx[i], sy[i]);
        ctx.rotate(angle[i]);
        ctx.beginPath();
        ctx.moveTo(0, 0);
        ctx.lineTo(slength[i], 0);
        this.visuals.line.set_vectorize(ctx, i);
        ctx.stroke();
        ctx.rotate(-angle[i]);
        results.push(ctx.translate(-sx[i], -sy[i]));
      }
      return results;
    }
  };

  RayView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    return this._generic_line_legend(ctx, x0, x1, y0, y1);
  };

  return RayView;

})(Glyph.View);

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

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

  Ray.prototype.default_view = RayView;

  Ray.prototype.type = 'Ray';

  Ray.prototype.visuals = ['line'];

  Ray.prototype.distances = ['length'];

  Ray.prototype.angles = ['angle'];

  return Ray;

})(Glyph.Model);

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


},{"./glyph":"renderer/glyph/glyph","underscore":"underscore"}],"renderer/glyph/rect":[function(require,module,exports){
var Glyph, Rect, RectView, _, hittest,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Glyph = require("./glyph");

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

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.distances.width.units === "data") {
      this.max_w2 = this.max_width / 2;
    }
    this.max_h2 = 0;
    if (this.distances.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.distances.width.units === "data") {
      this.sw = this.sdist(this.renderer.xmapper, this.x, this.width, 'center', this.mget('dilate'));
    } else {
      this.sw = this.width;
    }
    if (this.distances.height.units === "data") {
      return this.sh = this.sdist(this.renderer.ymapper, this.y, this.height, 'center', this.mget('dilate'));
    } else {
      return this.sh = this.height;
    }
  };

  RectView.prototype._render = function(ctx, indices, arg) {
    var angle, i, j, k, len, len1, sh, sw, sx, sy;
    sx = arg.sx, sy = arg.sy, sw = arg.sw, sh = arg.sh, angle = arg.angle;
    if (this.visuals.fill.do_fill) {
      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.do_stroke) {
      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 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];
    result = hittest.create_hit_test_result();
    result['1d'].indices = (function() {
      var j, len, ref2, results;
      ref2 = this.index.search([x0, y0, x1, y1]);
      results = [];
      for (j = 0, len = ref2.length; j < len; j++) {
        x = ref2[j];
        results.push(x[4].i);
      }
      return results;
    }).call(this);
    return result;
  };

  RectView.prototype._hit_point = function(geometry) {
    var 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.distances.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.distances.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 = [];
    ref3 = (function() {
      var k, len, ref3, results;
      ref3 = this.index.search([x0, y0, x1, y1]);
      results = [];
      for (k = 0, len = ref3.length; k < len; k++) {
        pt = ref3[k];
        results.push(pt[4].i);
      }
      return results;
    }).call(this);
    for (j = 0, len = ref3.length; j < len; j++) {
      i = ref3[j];
      sx = this.renderer.plot_view.canvas.vx_to_sx(vx);
      sy = this.renderer.plot_view.canvas.vy_to_sy(vy);
      if (this.angle[i]) {
        d = Math.sqrt(Math.pow(sx - this.sx[i], 2) + Math.pow(sy - this.sy[i], 2));
        s = Math.sin(-this.angle[i]);
        c = Math.cos(-this.angle[i]);
        px = c * (sx - this.sx[i]) - s * (sy - this.sy[i]) + this.sx[i];
        py = s * (sx - this.sx[i]) + c * (sy - this.sy[i]) + this.sy[i];
        sx = px;
        sy = py;
      }
      width_in = Math.abs(this.sx[i] - sx) <= this.sw[i] / 2;
      height_in = Math.abs(this.sy[i] - sy) <= this.sh[i] / 2;
      if (height_in && width_in) {
        hits.push(i);
      }
    }
    result = hittest.create_hit_test_result();
    result['1d'].indices = hits;
    return result;
  };

  RectView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    return this._generic_area_legend(ctx, x0, x1, y0, y1);
  };

  RectView.prototype._bounds = function(bds) {
    return [[bds[0][0] - this.max_w2, bds[0][1] + this.max_w2], [bds[1][0] - this.max_h2, bds[1][1] + this.max_h2]];
  };

  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.prototype.distances = ['width', 'height'];

  Rect.prototype.angles = ['angle'];

  Rect.prototype.display_defaults = function() {
    return _.extend({}, Rect.__super__.display_defaults.call(this), {
      angle: 0.0,
      dilate: false
    });
  };

  return Rect;

})(Glyph.Model);

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


},{"../../common/hittest":"common/hittest","./glyph":"renderer/glyph/glyph","underscore":"underscore"}],"renderer/glyph/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([
          this.x0[i], this.y0[i], this.x1[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.do_stroke) {
      results = [];
      for (j = 0, len = indices.length; j < len; j++) {
        i = indices[j];
        if (isNaN(sx0[i] + sy0[i] + sx1[i] + sy1[i])) {
          continue;
        }
        ctx.beginPath();
        ctx.moveTo(sx0[i], sy0[i]);
        ctx.lineTo(sx1[i], sy1[i]);
        this.visuals.line.set_vectorize(ctx, i);
        results.push(ctx.stroke());
      }
      return results;
    }
  };

  SegmentView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    return this._generic_line_legend(ctx, x0, x1, y0, y1);
  };

  return SegmentView;

})(Glyph.View);

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

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

  Segment.prototype.default_view = SegmentView;

  Segment.prototype.type = 'Segment';

  Segment.prototype.visuals = ['line'];

  Segment.prototype.coords = [['x0', 'y0'], ['x1', 'y1']];

  return Segment;

})(Glyph.Model);

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


},{"./glyph":"renderer/glyph/glyph","rbush":"rbush","underscore":"underscore"}],"renderer/glyph/text":[function(require,module,exports){
var Glyph, Text, TextView, _, properties,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

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

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

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

  TextView.prototype.initialize = function(options) {
    TextView.__super__.initialize.call(this, options);
    return this.text_props = new properties.Text({
      obj: this.model,
      prefix: ''
    });
  };

  TextView.prototype._index_data = function() {
    return this._xy_index();
  };

  TextView.prototype._render = function(ctx, indices, arg) {
    var angle, i, j, len, results, sx, sy, text, x_offset, y_offset;
    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;
      }
      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());
    }
    return results;
  };

  TextView.prototype.draw_legend = function(ctx, x1, x2, y1, y2) {
    ctx.save();
    this.text_props.set_value(ctx);
    ctx.font = this.text_props.font_value();
    ctx.font = ctx.font.replace(/\b[\d\.]+[\w]+\b/, '10pt');
    ctx.textAlign = "right";
    ctx.textBaseline = "middle";
    ctx.fillText("text", x2, (y1 + y2) / 2);
    return ctx.restore();
  };

  return TextView;

})(Glyph.View);

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

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

  Text.prototype.default_view = TextView;

  Text.prototype.type = 'Text';

  Text.prototype.visuals = ['text'];

  Text.prototype.distances = ['x_offset', 'y_offset'];

  Text.prototype.angles = ['angle'];

  Text.prototype.fields = ['text:string'];

  Text.prototype.defaults = function() {
    return _.extend({}, Text.__super__.defaults.call(this), {
      angle: 0,
      x_offset: 0,
      y_offset: 0
    });
  };

  return Text;

})(Glyph.Model);

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


},{"../../common/properties":"common/properties","./glyph":"renderer/glyph/glyph","underscore":"underscore"}],"renderer/glyph/wedge":[function(require,module,exports){
var Glyph, Wedge, WedgeView, _, hittest, mathutils,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

mathutils = require("../../common/mathutils");

Glyph = require("./glyph");

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

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.distances.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 direction, end_angle, i, j, len, results, sradius, start_angle, sx, sy;
    sx = arg.sx, sy = arg.sy, sradius = arg.sradius, start_angle = arg.start_angle, end_angle = arg.end_angle, direction = arg.direction;
    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] + direction[i])) {
        continue;
      }
      ctx.beginPath();
      ctx.arc(sx[i], sy[i], sradius[i], start_angle[i], end_angle[i], direction[i]);
      ctx.lineTo(sx[i], sy[i]);
      ctx.closePath();
      if (this.visuals.fill.do_fill) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fill();
      }
      if (this.visuals.line.do_stroke) {
        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, 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.distances.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 = [];
    ref3 = (function() {
      var k, len, ref3, results;
      ref3 = this.index.search([x0, y0, x1, y1]);
      results = [];
      for (k = 0, len = ref3.length; k < len; k++) {
        pt = ref3[k];
        results.push(pt[4].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]);
      }
    }
    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 (mathutils.angle_between(-angle, -this.start_angle[i], -this.end_angle[i], this.direction[i])) {
        hits.push([i, dist]);
      }
    }
    result = hittest.create_hit_test_result();
    result['1d'].indices = _.chain(hits).sortBy(function(elt) {
      return elt[1];
    }).map(function(elt) {
      return elt[0];
    }).value();
    return result;
  };

  WedgeView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    return this._generic_area_legend(ctx, x0, x1, y0, y1);
  };

  return WedgeView;

})(Glyph.View);

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

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

  Wedge.prototype.default_view = WedgeView;

  Wedge.prototype.type = 'Wedge';

  Wedge.prototype.distances = ['radius'];

  Wedge.prototype.angles = ['start_angle', 'end_angle'];

  Wedge.prototype.fields = ['direction:direction'];

  Wedge.prototype.display_defaults = function() {
    return _.extend({}, Wedge.__super__.display_defaults.call(this), {
      direction: 'anticlock'
    });
  };

  return Wedge;

})(Glyph.Model);

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


},{"../../common/hittest":"common/hittest","../../common/mathutils":"common/mathutils","./glyph":"renderer/glyph/glyph","underscore":"underscore"}],"renderer/guide/axis":[function(require,module,exports){
var ALPHABETIC, Axis, AxisView, CENTER, HANGING, HasParent, LEFT, LayoutBox, MIDDLE, PlotWidget, RIGHT, _, _align_lookup, _align_lookup_negative, _align_lookup_positive, _angle_lookup, _apply_location_heuristics, _baseline_lookup, kiwi, logger, pi2, properties,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

kiwi = require("kiwi");

HasParent = require("../../common/has_parent");

LayoutBox = require("../../common/layout_box");

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

PlotWidget = require("../../common/plot_widget");

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

pi2 = Math.PI / 2;

ALPHABETIC = 'alphabetic';

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: {
    parallel: ALPHABETIC,
    normal: MIDDLE,
    horizontal: ALPHABETIC,
    vertical: MIDDLE
  },
  below: {
    parallel: HANGING,
    normal: MIDDLE,
    horizontal: HANGING,
    vertical: MIDDLE
  },
  left: {
    parallel: ALPHABETIC,
    normal: MIDDLE,
    horizontal: MIDDLE,
    vertical: ALPHABETIC
  },
  right: {
    parallel: ALPHABETIC,
    normal: MIDDLE,
    horizontal: MIDDLE,
    vertical: ALPHABETIC
  }
};

_align_lookup = {
  above: {
    parallel: CENTER,
    normal: LEFT,
    horizontal: CENTER,
    vertical: LEFT
  },
  below: {
    parallel: CENTER,
    normal: LEFT,
    horizontal: CENTER,
    vertical: RIGHT
  },
  left: {
    parallel: CENTER,
    normal: RIGHT,
    horizontal: RIGHT,
    vertical: CENTER
  },
  right: {
    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
};

_apply_location_heuristics = function(ctx, side, orient) {
  var align, baseline;
  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;
  return ctx.textAlign = align;
};

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.rule_props = new properties.Line({
      obj: this.model,
      prefix: 'axis_'
    });
    this.major_tick_props = new properties.Line({
      obj: this.model,
      prefix: 'major_tick_'
    });
    this.minor_tick_props = new properties.Line({
      obj: this.model,
      prefix: 'minor_tick_'
    });
    this.major_label_props = new properties.Text({
      obj: this.model,
      prefix: 'major_label_'
    });
    this.axis_label_props = new properties.Text({
      obj: this.model,
      prefix: 'axis_label_'
    });
    this.x_range_name = this.mget('x_range_name');
    return this.y_range_name = this.mget('y_range_name');
  };

  AxisView.prototype.render = function() {
    var ctx;
    if (!this.mget('visible')) {
      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._draw_rule = function(ctx) {
    var coords, i, k, nx, ny, ref, ref1, ref2, ref3, ref4, sx, sy, x, xoff, y, yoff;
    if (!this.rule_props.do_stroke) {
      return;
    }
    ref = coords = this.mget('rule_coords'), x = ref[0], y = ref[1];
    ref1 = this.plot_view.map_to_screen(x, y, this.x_range_name, this.y_range_name), sx = ref1[0], sy = ref1[1];
    ref2 = this.mget('normals'), nx = ref2[0], ny = ref2[1];
    ref3 = this.mget('offsets'), xoff = ref3[0], yoff = ref3[1];
    this.rule_props.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.major_tick_props.do_stroke) {
      return;
    }
    coords = this.mget('tick_coords');
    ref = coords.major, x = ref[0], y = ref[1];
    ref1 = this.plot_view.map_to_screen(x, y, this.x_range_name, this.y_range_name), sx = ref1[0], sy = ref1[1];
    ref2 = this.mget('normals'), nx = ref2[0], ny = ref2[1];
    ref3 = this.mget('offsets'), xoff = ref3[0], yoff = ref3[1];
    tin = this.mget('major_tick_in');
    tout = this.mget('major_tick_out');
    this.major_tick_props.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.minor_tick_props.do_stroke) {
      return;
    }
    coords = this.mget('tick_coords');
    ref = coords.minor, x = ref[0], y = ref[1];
    ref1 = this.plot_view.map_to_screen(x, y, this.x_range_name, this.y_range_name), sx = ref1[0], sy = ref1[1];
    ref2 = this.mget('normals'), nx = ref2[0], ny = ref2[1];
    ref3 = this.mget('offsets'), xoff = ref3[0], yoff = ref3[1];
    tin = this.mget('minor_tick_in');
    tout = this.mget('minor_tick_out');
    this.minor_tick_props.set_value(ctx);
    results = [];
    for (i = k = 0, ref4 = sx.length; 0 <= ref4 ? k < ref4 : k > ref4; i = 0 <= ref4 ? ++k : --k) {
      ctx.beginPath();
      ctx.moveTo(Math.round(sx[i] + nx * tout + nx * xoff), Math.round(sy[i] + ny * tout + ny * yoff));
      ctx.lineTo(Math.round(sx[i] - nx * tin + nx * xoff), Math.round(sy[i] - ny * tin + ny * yoff));
      results.push(ctx.stroke());
    }
    return results;
  };

  AxisView.prototype._draw_major_labels = function(ctx) {
    var angle, coords, dim, i, k, labels, nx, ny, orient, ref, ref1, ref2, ref3, ref4, results, side, standoff, sx, sy, x, xoff, y, yoff;
    coords = this.mget('tick_coords');
    ref = coords.major, x = ref[0], y = ref[1];
    ref1 = this.plot_view.map_to_screen(x, y, this.x_range_name, this.y_range_name), sx = ref1[0], sy = ref1[1];
    ref2 = this.mget('normals'), nx = ref2[0], ny = ref2[1];
    ref3 = this.mget('offsets'), xoff = ref3[0], yoff = ref3[1];
    dim = this.mget('dimension');
    side = this.mget('layout_location');
    orient = this.mget('major_label_orientation');
    if (_.isString(orient)) {
      angle = _angle_lookup[side][orient];
    } else {
      angle = -orient;
    }
    standoff = this.model._tick_extent(this) + this.mget('major_label_standoff');
    labels = this.mget('formatter').format(coords.major[dim]);
    this.major_label_props.set_value(ctx);
    _apply_location_heuristics(ctx, side, orient);
    results = [];
    for (i = k = 0, ref4 = sx.length; 0 <= ref4 ? k < ref4 : k > ref4; i = 0 <= ref4 ? ++k : --k) {
      if (angle) {
        ctx.translate(sx[i] + nx * standoff + nx * xoff, sy[i] + ny * standoff + ny * yoff);
        ctx.rotate(angle);
        ctx.fillText(labels[i], 0, 0);
        ctx.rotate(-angle);
        results.push(ctx.translate(-sx[i] - nx * standoff + nx * xoff, -sy[i] - ny * standoff + ny * yoff));
      } else {
        results.push(ctx.fillText(labels[i], Math.round(sx[i] + nx * standoff + nx * xoff), Math.round(sy[i] + ny * standoff + ny * yoff)));
      }
    }
    return results;
  };

  AxisView.prototype._draw_axis_label = function(ctx) {
    var angle, label, nx, ny, orient, ref, ref1, ref2, ref3, side, standoff, sx, sy, x, xoff, y, yoff;
    label = this.mget('axis_label');
    if (label == null) {
      return;
    }
    ref = this.mget('rule_coords'), x = ref[0], y = ref[1];
    ref1 = this.plot_view.map_to_screen(x, y, this.x_range_name, this.y_range_name), sx = ref1[0], sy = ref1[1];
    ref2 = this.mget('normals'), nx = ref2[0], ny = ref2[1];
    ref3 = this.mget('offsets'), xoff = ref3[0], yoff = ref3[1];
    side = this.mget('layout_location');
    orient = 'parallel';
    angle = _angle_lookup[side][orient];
    standoff = this.model._tick_extent(this) + this.model._tick_label_extent(this) + this.mget('axis_label_standoff');
    sx = (sx[0] + sx[sx.length - 1]) / 2;
    sy = (sy[0] + sy[sy.length - 1]) / 2;
    this.axis_label_props.set_value(ctx);
    _apply_location_heuristics(ctx, side, orient);
    if (angle) {
      ctx.translate(sx + nx * standoff + nx * xoff, sy + ny * standoff + ny * yoff);
      ctx.rotate(angle);
      ctx.fillText(label, 0, 0);
      ctx.rotate(-angle);
      return ctx.translate(-sx - nx * standoff + nx * xoff, -sy - ny * standoff + ny * yoff);
    } else {
      return ctx.fillText(label, sx + nx * standoff + nx * xoff, sy + ny * standoff + ny * yoff);
    }
  };

  return AxisView;

})(PlotWidget);

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.prototype.initialize = function(attrs, options) {
    Axis.__super__.initialize.call(this, attrs, options);
    this.register_property('computed_bounds', this._computed_bounds, false);
    this.add_dependencies('computed_bounds', this, ['bounds']);
    this.add_dependencies('computed_bounds', this.get('plot'), ['x_range', 'y_range']);
    this.register_property('rule_coords', this._rule_coords, false);
    this.add_dependencies('rule_coords', this, ['computed_bounds', 'side']);
    this.register_property('tick_coords', this._tick_coords, false);
    this.add_dependencies('tick_coords', this, ['computed_bounds', 'layout_location']);
    this.register_property('ranges', this._ranges, true);
    this.register_property('normals', (function() {
      return this._normals;
    }), true);
    this.register_property('dimension', (function() {
      return this._dim;
    }), true);
    return this.register_property('offsets', this._offsets, true);
  };

  Axis.prototype.nonserializable_attribute_names = function() {
    return Axis.__super__.nonserializable_attribute_names.call(this).concat(['layout_location']);
  };

  Axis.prototype.initialize_layout = function(solver) {
    var panel, side;
    panel = new LayoutBox.Model({
      solver: solver
    });
    this.panel = panel;
    this._top = panel._top;
    this._bottom = panel._bottom;
    this._left = panel._left;
    this._right = panel._right;
    this._width = panel._width;
    this._height = panel._height;
    side = this.get('layout_location');
    if (side === "above") {
      this._dim = 0;
      this._normals = [0, -1];
      this._size = panel._height;
      return this._anchor = panel._bottom;
    } else if (side === "below") {
      this._dim = 0;
      this._normals = [0, 1];
      this._size = panel._height;
      return this._anchor = panel._top;
    } else if (side === "left") {
      this._dim = 1;
      this._normals = [-1, 0];
      this._size = panel._width;
      return this._anchor = panel._right;
    } else if (side === "right") {
      this._dim = 1;
      this._normals = [1, 0];
      this._size = panel._width;
      return this._anchor = panel._left;
    } else {
      return logger.error("unrecognized side: '" + side + "'");
    }
  };

  Axis.prototype.update_layout = function(view, solver) {
    var size;
    if (!this.get('visible')) {
      size = 0;
    } else {
      size = this._tick_extent(view) + this._tick_label_extent(view) + this._axis_label_extent(view);
    }
    if (this._last_size == null) {
      this._last_size = -1;
    }
    if (size === this._last_size) {
      return;
    }
    this._last_size = size;
    if (this._size_constraint != null) {
      solver.remove_constraint(this._size_constraint);
    }
    this._size_constraint = new kiwi.Constraint(new kiwi.Expression(this._size, -size), kiwi.Operator.Eq);
    return solver.add_constraint(this._size_constraint);
  };

  Axis.prototype._offsets = function() {
    var frame, ref, side, xoff, yoff;
    side = this.get('layout_location');
    ref = [0, 0], xoff = ref[0], yoff = ref[1];
    frame = this.get('plot').get('frame');
    if (side === "below") {
      yoff = Math.abs(this.panel.get("top") - frame.get("bottom"));
    } else if (side === "above") {
      yoff = Math.abs(this.panel.get("bottom") - frame.get("top"));
    } else if (side === "right") {
      xoff = Math.abs(this.panel.get("left") - frame.get("right"));
    } else if (side === "left") {
      xoff = Math.abs(this.panel.get("right") - frame.get("left"));
    }
    return [xoff, yoff];
  };

  Axis.prototype._ranges = function() {
    var frame, i, j, ranges;
    i = this.get('dimension');
    j = (i + 1) % 2;
    frame = this.get('plot').get('frame');
    ranges = [frame.get('x_ranges')[this.get('x_range_name')], frame.get('y_ranges')[this.get('y_range_name')]];
    return [ranges[i], ranges[j]];
  };

  Axis.prototype._computed_bounds = function() {
    var cross_range, end, range, range_bounds, ref, ref1, start, user_bounds;
    ref = this.get('ranges'), range = ref[0], cross_range = ref[1];
    user_bounds = (ref1 = this.get('bounds')) != null ? ref1 : 'auto';
    range_bounds = [range.get('min'), range.get('max')];
    if (user_bounds === 'auto') {
      return range_bounds;
    }
    if (_.isArray(user_bounds)) {
      if (Math.abs(user_bounds[0] - user_bounds[1]) > Math.abs(range_bounds[0] - range_bounds[1])) {
        start = Math.max(Math.min(user_bounds[0], user_bounds[1]), range_bounds[0]);
        end = Math.min(Math.max(user_bounds[0], user_bounds[1]), range_bounds[1]);
      } else {
        start = Math.min(user_bounds[0], user_bounds[1]);
        end = Math.max(user_bounds[0], user_bounds[1]);
      }
      return [start, end];
    }
    logger.error("user bounds '" + user_bounds + "' not understood");
    return null;
  };

  Axis.prototype._rule_coords = function() {
    var coords, cross_range, end, i, j, loc, range, ref, ref1, start, xs, ys;
    i = this.get('dimension');
    j = (i + 1) % 2;
    ref = this.get('ranges'), range = ref[0], cross_range = ref[1];
    ref1 = this.get('computed_bounds'), start = ref1[0], end = ref1[1];
    xs = new Array(2);
    ys = new Array(2);
    coords = [xs, ys];
    loc = this._get_loc(cross_range);
    coords[i][0] = Math.max(start, range.get('min'));
    coords[i][1] = Math.min(end, range.get('max'));
    if (coords[i][0] > coords[i][1]) {
      coords[i][0] = coords[i][1] = NaN;
    }
    coords[j][0] = loc;
    coords[j][1] = loc;
    return coords;
  };

  Axis.prototype._tick_coords = function() {
    var coords, cross_range, end, i, ii, j, k, l, loc, m, majors, minor_coords, minor_xs, minor_ys, minors, range, range_max, range_min, ref, ref1, ref2, ref3, ref4, ref5, start, ticks, xs, ys;
    i = this.get('dimension');
    j = (i + 1) % 2;
    ref = this.get('ranges'), range = ref[0], cross_range = ref[1];
    ref1 = this.get('computed_bounds'), start = ref1[0], end = ref1[1];
    ticks = this.get('ticker').get_ticks(start, end, range, {});
    majors = ticks.major;
    minors = ticks.minor;
    loc = this._get_loc(cross_range);
    xs = [];
    ys = [];
    coords = [xs, ys];
    minor_xs = [];
    minor_ys = [];
    minor_coords = [minor_xs, minor_ys];
    if (range.type === "FactorRange") {
      for (ii = k = 0, ref2 = majors.length; 0 <= ref2 ? k < ref2 : k > ref2; ii = 0 <= ref2 ? ++k : --k) {
        coords[i].push(majors[ii]);
        coords[j].push(loc);
      }
    } else {
      ref3 = [range.get('min'), range.get('max')], range_min = ref3[0], range_max = ref3[1];
      for (ii = l = 0, ref4 = majors.length; 0 <= ref4 ? l < ref4 : l > ref4; ii = 0 <= ref4 ? ++l : --l) {
        if (majors[ii] < range_min || majors[ii] > range_max) {
          continue;
        }
        coords[i].push(majors[ii]);
        coords[j].push(loc);
      }
      for (ii = m = 0, ref5 = minors.length; 0 <= ref5 ? m < ref5 : m > ref5; ii = 0 <= ref5 ? ++m : --m) {
        if (minors[ii] < range_min || minors[ii] > range_max) {
          continue;
        }
        minor_coords[i].push(minors[ii]);
        minor_coords[j].push(loc);
      }
    }
    return {
      "major": coords,
      "minor": minor_coords
    };
  };

  Axis.prototype._get_loc = function(cross_range) {
    var cend, cstart, loc, side;
    cstart = cross_range.get('start');
    cend = cross_range.get('end');
    side = this.get('layout_location');
    if (side === 'left' || side === 'below') {
      loc = 'start';
    } else if (side === 'right' || side === 'above') {
      loc = 'end';
    }
    return cross_range.get(loc);
  };

  Axis.prototype._tick_extent = function(view) {
    return this.get('major_tick_out');
  };

  Axis.prototype._tick_label_extent = function(view) {
    var angle, c, coords, ctx, dim, extent, h, hfactor, hscale, i, k, labels, orient, ref, s, side, val, w, wfactor;
    extent = 0;
    dim = this.get('dimension');
    ctx = view.plot_view.canvas_view.ctx;
    coords = this.get('tick_coords').major;
    side = this.get('layout_location');
    orient = this.get('major_label_orientation');
    labels = this.get('formatter').format(coords[dim]);
    view.major_label_props.set_value(ctx);
    if (_.isString(orient)) {
      hscale = 1;
      angle = _angle_lookup[side][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.get('major_label_standoff');
    }
    return extent;
  };

  Axis.prototype._axis_label_extent = function(view) {
    var angle, c, ctx, extent, h, orient, s, side, w;
    extent = 0;
    side = this.get('layout_location');
    orient = 'parallel';
    ctx = view.plot_view.canvas_view.ctx;
    view.axis_label_props.set_value(ctx);
    angle = Math.abs(_angle_lookup[side][orient]);
    c = Math.cos(angle);
    s = Math.sin(angle);
    if (this.get('axis_label')) {
      extent += this.get('axis_label_standoff');
      view.axis_label_props.set_value(ctx);
      w = ctx.measureText(this.get('axis_label')).width * 1.1;
      h = ctx.measureText(this.get('axis_label')).ascent * 0.9;
      if (side === "above" || side === "below") {
        extent += w * s + h * c;
      } else {
        extent += w * c + h * s;
      }
    }
    return extent;
  };

  Axis.prototype.defaults = function() {
    return _.extend({}, Axis.__super__.defaults.call(this), {
      location: "auto",
      x_range_name: "default",
      y_range_name: "default"
    });
  };

  Axis.prototype.display_defaults = function() {
    return _.extend({}, Axis.__super__.display_defaults.call(this), {
      level: 'overlay',
      visible: true,
      axis_line_color: 'black',
      axis_line_width: 1,
      axis_line_alpha: 1.0,
      axis_line_join: 'miter',
      axis_line_cap: 'butt',
      axis_line_dash: [],
      axis_line_dash_offset: 0,
      major_tick_in: 2,
      major_tick_out: 6,
      major_tick_line_color: 'black',
      major_tick_line_width: 1,
      major_tick_line_alpha: 1.0,
      major_tick_line_join: 'miter',
      major_tick_line_cap: 'butt',
      major_tick_line_dash: [],
      major_tick_line_dash_offset: 0,
      minor_tick_in: 0,
      minor_tick_out: 4,
      minor_tick_line_color: 'black',
      minor_tick_line_width: 1,
      minor_tick_line_alpha: 1.0,
      minor_tick_line_join: 'miter',
      minor_tick_line_cap: 'butt',
      minor_tick_line_dash: [],
      minor_tick_line_dash_offset: 0,
      major_label_standoff: 5,
      major_label_orientation: "horizontal",
      major_label_text_font: "helvetica",
      major_label_text_font_size: "10pt",
      major_label_text_font_style: "normal",
      major_label_text_color: "#444444",
      major_label_text_alpha: 1.0,
      major_label_text_align: "center",
      major_label_text_baseline: "alphabetic",
      axis_label: "",
      axis_label_standoff: 5,
      axis_label_text_font: "helvetica",
      axis_label_text_font_size: "16pt",
      axis_label_text_font_style: "normal",
      axis_label_text_color: "#444444",
      axis_label_text_alpha: 1.0,
      axis_label_text_align: "center",
      axis_label_text_baseline: "alphabetic"
    });
  };

  return Axis;

})(HasParent);

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


},{"../../common/has_parent":"common/has_parent","../../common/layout_box":"common/layout_box","../../common/logging":"common/logging","../../common/plot_widget":"common/plot_widget","../../common/properties":"common/properties","kiwi":"kiwi","underscore":"underscore"}],"renderer/guide/categorical_axis":[function(require,module,exports){
var Axis, CategoricalAxis, CategoricalAxisView, 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;

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

Axis = require("./axis");

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.prototype.initialize = function(attrs, objects) {
    var Collections;
    CategoricalAxis.__super__.initialize.call(this, attrs, objects);
    Collections = require("../../common/base").Collections;
    if (this.get('ticker') == null) {
      this.set_obj('ticker', Collections('CategoricalTicker').create());
    }
    if (this.get('formatter') == null) {
      return this.set_obj('formatter', Collections('CategoricalTickFormatter').create());
    }
  };

  CategoricalAxis.prototype._computed_bounds = function() {
    var cross_range, range, range_bounds, ref, ref1, user_bounds;
    ref = this.get('ranges'), range = ref[0], cross_range = ref[1];
    user_bounds = (ref1 = this.get('bounds')) != null ? ref1 : 'auto';
    range_bounds = [range.get('min'), range.get('max')];
    if (user_bounds !== 'auto') {
      logger.warn("Categorical Axes only support user_bounds='auto', ignoring");
    }
    return range_bounds;
  };

  return CategoricalAxis;

})(Axis.Model);

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


},{"../../common/base":"common/base","../../common/logging":"common/logging","./axis":"renderer/guide/axis"}],"renderer/guide/datetime_axis":[function(require,module,exports){
var Axis, Collections, DatetimeAxis, DatetimeAxisView, DatetimeTickFormatter, DatetimeTicker,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

Collections = require("../../common/base").Collections;

DatetimeTicker = require("../../ticking/datetime_ticker");

DatetimeTickFormatter = require("../../ticking/datetime_tick_formatter");

Axis = require("./axis");

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

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

  return DatetimeAxisView;

})(Axis.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.prototype.initialize = function(attrs, objects) {
    DatetimeAxis.__super__.initialize.call(this, attrs, objects);
    if (this.get('ticker') == null) {
      this.set_obj('ticker', Collections('DatetimeTicker').create());
    }
    if (this.get('formatter') == null) {
      return this.set_obj('formatter', Collections('DatetimeTickFormatter').create());
    }
  };

  return DatetimeAxis;

})(Axis.Model);

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


},{"../../common/base":"common/base","../../ticking/datetime_tick_formatter":"ticking/datetime_tick_formatter","../../ticking/datetime_ticker":"ticking/datetime_ticker","./axis":"renderer/guide/axis"}],"renderer/guide/grid":[function(require,module,exports){
var Grid, GridView, HasParent, PlotWidget, _, properties,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

HasParent = require("../../common/has_parent");

PlotWidget = require("../../common/plot_widget");

properties = require("../../common/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.grid_props = new properties.Line({
      obj: this.model,
      prefix: 'grid_'
    });
    this.minor_grid_props = new properties.Line({
      obj: this.model,
      prefix: 'minor_grid_'
    });
    this.band_props = new properties.Fill({
      obj: this.model,
      prefix: 'band_'
    });
    this.x_range_name = this.mget('x_range_name');
    return this.y_range_name = this.mget('y_range_name');
  };

  GridView.prototype.render = function() {
    var ctx;
    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.band_props.do_fill) {
      return;
    }
    ref = this.mget('grid_coords'), xs = ref[0], ys = ref[1];
    this.band_props.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.grid_props.do_stroke) {
      return;
    }
    ref = this.mget('grid_coords'), xs = ref[0], ys = ref[1];
    return this._draw_grid_helper(ctx, this.grid_props, xs, ys);
  };

  GridView.prototype._draw_minor_grids = function(ctx) {
    var ref, xs, ys;
    if (!this.minor_grid_props.do_stroke) {
      return;
    }
    ref = this.mget('minor_grid_coords'), xs = ref[0], ys = ref[1];
    return this._draw_grid_helper(ctx, this.minor_grid_props, 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;

})(PlotWidget);

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.prototype.initialize = function(attrs, options) {
    Grid.__super__.initialize.call(this, attrs, options);
    this.register_property('computed_bounds', this._bounds, false);
    this.add_dependencies('computed_bounds', this, ['bounds']);
    this.register_property('grid_coords', this._grid_coords, false);
    this.add_dependencies('grid_coords', this, ['computed_bounds', 'dimension', 'ticker']);
    this.register_property('minor_grid_coords', this._minor_grid_coords, false);
    this.add_dependencies('minor_grid_coords', this, ['computed_bounds', 'dimension', 'ticker']);
    return this.register_property('ranges', this._ranges, true);
  };

  Grid.prototype._ranges = function() {
    var frame, i, j, ranges;
    i = this.get('dimension');
    j = (i + 1) % 2;
    frame = this.get('plot').get('frame');
    ranges = [frame.get('x_ranges')[this.get('x_range_name')], frame.get('y_ranges')[this.get('y_range_name')]];
    return [ranges[i], ranges[j]];
  };

  Grid.prototype._bounds = function() {
    var cross_range, end, range, range_bounds, ref, ref1, start, user_bounds;
    ref = this.get('ranges'), range = ref[0], cross_range = ref[1];
    user_bounds = (ref1 = this.get('bounds')) != null ? ref1 : 'auto';
    range_bounds = [range.get('min'), range.get('max')];
    if (_.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() {
    return this._grid_coords_helper('major');
  };

  Grid.prototype._minor_grid_coords = function() {
    return this._grid_coords_helper('minor');
  };

  Grid.prototype._grid_coords_helper = function(location) {
    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;
    i = this.get('dimension');
    j = (i + 1) % 2;
    ref = this.get('ranges'), range = ref[0], cross_range = ref[1];
    ref1 = this.get('computed_bounds'), start = ref1[0], end = ref1[1];
    tmp = Math.min(start, end);
    end = Math.max(start, end);
    start = tmp;
    ticks = this.get('ticker').get_ticks(start, end, range, {})[location];
    min = range.get('min');
    max = range.get('max');
    cmin = cross_range.get('min');
    cmax = cross_range.get('max');
    coords = [[], []];
    for (ii = k = 0, ref2 = ticks.length; 0 <= ref2 ? k < ref2 : k > ref2; ii = 0 <= ref2 ? ++k : --k) {
      if (ticks[ii] === min || ticks[ii] === max) {
        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;
  };

  Grid.prototype.defaults = function() {
    return _.extend({}, Grid.__super__.defaults.call(this), {
      x_range_name: "default",
      y_range_name: "default"
    });
  };

  Grid.prototype.display_defaults = function() {
    return _.extend({}, Grid.__super__.display_defaults.call(this), {
      level: 'underlay',
      band_fill_color: null,
      band_fill_alpha: 0,
      grid_line_color: '#cccccc',
      grid_line_width: 1,
      grid_line_alpha: 1.0,
      grid_line_join: 'miter',
      grid_line_cap: 'butt',
      grid_line_dash: [],
      grid_line_dash_offset: 0,
      minor_grid_line_color: null,
      minor_grid_line_width: 1,
      minor_grid_line_alpha: 1.0,
      minor_grid_line_join: 'miter',
      minor_grid_line_cap: 'butt',
      minor_grid_line_dash: [],
      minor_grid_line_dash_offset: 0
    });
  };

  return Grid;

})(HasParent);

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


},{"../../common/has_parent":"common/has_parent","../../common/plot_widget":"common/plot_widget","../../common/properties":"common/properties","underscore":"underscore"}],"renderer/guide/linear_axis":[function(require,module,exports){
var Axis, 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;

Axis = require("./axis");

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.prototype.initialize = function(attrs, objects) {
    var Collections;
    LinearAxis.__super__.initialize.call(this, attrs, objects);
    Collections = require("../../common/base").Collections;
    if (this.get('ticker') == null) {
      this.set_obj('ticker', Collections('BasicTicker').create());
    }
    if (this.get('formatter') == null) {
      return this.set_obj('formatter', Collections('BasicTickFormatter').create());
    }
  };

  return LinearAxis;

})(Axis.Model);

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


},{"../../common/base":"common/base","./axis":"renderer/guide/axis"}],"renderer/guide/log_axis":[function(require,module,exports){
var Axis, LogAxis, LogAxisView,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

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.prototype.initialize = function(attrs, objects) {
    var Collections;
    LogAxis.__super__.initialize.call(this, attrs, objects);
    Collections = require("../../common/base").Collections;
    if (this.get('ticker') == null) {
      this.set_obj('ticker', Collections('LogTicker').create());
    }
    if (this.get('formatter') == null) {
      return this.set_obj('formatter', Collections('LogTickFormatter').create());
    }
  };

  return LogAxis;

})(Axis.Model);

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


},{"../../common/base":"common/base","./axis":"renderer/guide/axis"}],"renderer/overlay/box_selection":[function(require,module,exports){
var BoxSelection, BoxSelectionView, HasParent, PlotWidget, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

HasParent = require("../../common/has_parent");

PlotWidget = require("../../common/plot_widget");

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

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

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

  BoxSelectionView.prototype.bind_bokeh_events = function() {
    return this.listenTo(this.model, 'change:data', this._draw_box);
  };

  BoxSelectionView.prototype.render = function() {
    this._draw_box();
    return this;
  };

  BoxSelectionView.prototype._draw_box = function() {
    var canvas, data, sh, style, sw, sx, sy, vxlim, vylim;
    data = this.mget('data');
    if (_.isEmpty(data)) {
      this.$el.hide();
      return;
    }
    vxlim = data.vxlim;
    vylim = data.vylim;
    canvas = this.plot_view.canvas;
    sx = Math.min(canvas.vx_to_sx(vxlim[0]), canvas.vx_to_sx(vxlim[1]));
    sy = Math.min(canvas.vy_to_sy(vylim[0]), canvas.vy_to_sy(vylim[1]));
    sw = Math.abs(vxlim[1] - vxlim[0]);
    sh = Math.abs(vylim[1] - vylim[0]);
    style = "left:" + sx + "px; width:" + sw + "px; top:" + sy + "px; height:" + sh + "px";
    this.$el.attr('style', style);
    return this.$el.show();
  };

  return BoxSelectionView;

})(PlotWidget);

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

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

  BoxSelection.prototype.default_view = BoxSelectionView;

  BoxSelection.prototype.type = "BoxSelection";

  BoxSelection.prototype.serializable_in_document = function() {
    return false;
  };

  BoxSelection.prototype.defaults = function() {
    return _.extend({}, BoxSelection.__super__.defaults.call(this), {
      level: 'overlay',
      data: {}
    });
  };

  return BoxSelection;

})(HasParent);

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


},{"../../common/has_parent":"common/has_parent","../../common/plot_widget":"common/plot_widget","underscore":"underscore"}],"renderer/overlay/poly_selection":[function(require,module,exports){
var HasParent, PlotWidget, PolySelection, PolySelectionView, _, properties,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

HasParent = require("../../common/has_parent");

PlotWidget = require("../../common/plot_widget");

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

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

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

  PolySelectionView.prototype.initialize = function(options) {
    PolySelectionView.__super__.initialize.call(this, options);
    this.line = new properties.Line({
      obj: this.model,
      prefix: ""
    });
    return this.fill = new properties.Fill({
      obj: this.model,
      prefix: ""
    });
  };

  PolySelectionView.prototype.bind_bokeh_events = function() {
    return this.listenTo(this.model, 'change:data', this.plot_view.request_render);
  };

  PolySelectionView.prototype.render = function(ctx) {
    var canvas, data, i, j, ref, sx, sy;
    data = _.clone(this.mget('data'));
    if (_.isEmpty(data) || (data == null)) {
      return null;
    }
    canvas = this.plot_view.canvas;
    ctx = this.plot_view.canvas_view.ctx;
    for (i = j = 0, ref = data.vx.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      sx = canvas.vx_to_sx(data.vx[i]);
      sy = canvas.vy_to_sy(data.vy[i]);
      if (i === 0) {
        ctx.beginPath();
        ctx.moveTo(sx, sy);
      } else {
        ctx.lineTo(sx, sy);
      }
    }
    if (this.mget('auto_close')) {
      ctx.closePath();
    }
    if (this.line.do_stroke) {
      this.line.set_value(ctx);
      ctx.stroke();
    }
    if (this.fill.do_fill && this.mget('auto_close')) {
      this.fill.set_value(ctx);
      return ctx.fill();
    }
  };

  return PolySelectionView;

})(PlotWidget);

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

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

  PolySelection.prototype.default_view = PolySelectionView;

  PolySelection.prototype.type = "PolySelection";

  PolySelection.prototype.serializable_in_document = function() {
    return false;
  };

  PolySelection.prototype.display_defaults = function() {
    return _.extend({}, PolySelection.__super__.display_defaults.call(this), {
      fill_color: null,
      fill_alpha: 0.2,
      line_color: 'grey',
      line_width: 3,
      line_alpha: 0.8,
      line_join: 'miter',
      line_cap: 'butt',
      line_dash: [4],
      line_dash_offset: 0
    });
  };

  PolySelection.prototype.defaults = function() {
    return _.extend({}, PolySelection.__super__.defaults.call(this), {
      level: 'overlay',
      auto_close: true,
      data: {}
    });
  };

  return PolySelection;

})(HasParent);

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


},{"../../common/has_parent":"common/has_parent","../../common/plot_widget":"common/plot_widget","../../common/properties":"common/properties","underscore":"underscore"}],"renderer/tile/bbox_tile_source":[function(require,module,exports){
var BBoxTileSource, MercatorTileSource,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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');

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

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

  BBoxTileSource.prototype.type = 'BBoxTileSource';

  BBoxTileSource.prototype.get_image_url = function(x, y, z) {
    var image_url, ref, xmax, xmin, ymax, ymin;
    image_url = this.string_lookup_replace(this.get('url'), this.get('extra_url_vars'));
    ref = this.get_tile_meter_bounds(x, y, z), xmin = ref[0], ymin = ref[1], xmax = ref[2], ymax = ref[3];
    return image_url.replace("{XMIN}", xmin).replace("{YMIN}", ymin).replace("{XMAX}", xmax).replace("{YMAX}", ymax);
  };

  return BBoxTileSource;

})(MercatorTileSource);

module.exports = {
  Model: BBoxTileSource
};


},{"./mercator_tile_source":"renderer/tile/mercator_tile_source"}],"renderer/tile/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;


},{}],"renderer/tile/mercator_tile_source":[function(require,module,exports){
var MercatorTileSource, TileSource, _,
  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");

TileSource = require("./tile_source");

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

  MercatorTileSource.prototype.type = 'MercatorTileSource';

  MercatorTileSource.prototype.defaults = function() {
    return _.extend({}, MercatorTileSource.__super__.defaults.call(this), {
      tile_size: 256,
      max_zoom: 30,
      min_zoom: 0,
      extra_url_vars: {},
      full_extent: [-20037508.34, -20037508.34, 20037508.34, 20037508.34],
      x_origin_offset: 20037508.34,
      y_origin_offset: 20037508.34,
      initial_resolution: void 0,
      resolutions: void 0
    });
  };

  function MercatorTileSource() {
    this.defaults = bind(this.defaults, this);
    var z;
    MercatorTileSource.__super__.constructor.apply(this, arguments);
    if (this.get('initial_resolution') == null) {
      this.set('initial_resolution', 2 * Math.PI * 6378137 / this.get('tile_size'));
    }
    if (this.get('resolutions') == null) {
      this.set('resolutions', (function() {
        var j, results;
        results = [];
        for (z = j = 0; j <= 50; z = ++j) {
          results.push(this.get_resolution(z));
        }
        return results;
      }).call(this));
    }
  }

  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;
    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_resolution = function(level) {
    return this.get('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.get('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.get('resolutions');
    closest = this.get('resolutions').reduce(function(previous, current) {
      if (Math.abs(current - resolution) < Math.abs(previous - resolution)) {
        return current;
      }
      return previous;
    });
    return this.get('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.get('resolutions')[level];
    desired_x_delta = width * desired_res;
    desired_y_delta = height * desired_res;
    xmin = extent[0], ymin = extent[1], xmax = extent[2], ymax = extent[3];
    x_adjust = (desired_x_delta - (xmax - xmin)) / 2;
    y_adjust = (desired_y_delta - (ymax - ymin)) / 2;
    return [xmin - x_adjust, ymin - y_adjust, xmax + x_adjust, ymax + y_adjust];
  };

  MercatorTileSource.prototype.tms_to_wmts = function(x, y, z) {
    'Note this works both ways';
    return [x, Math.pow(2, z) - 1 - y, z];
  };

  MercatorTileSource.prototype.wmts_to_tms = function(x, y, z) {
    'Note this works both ways';
    return [x, Math.pow(2, z) - 1 - y, z];
  };

  MercatorTileSource.prototype.pixels_to_meters = function(px, py, level) {
    var mx, my, res;
    res = this.get_resolution(level);
    mx = px * res - this.get('x_origin_offset');
    my = py * res - this.get('y_origin_offset');
    return [mx, my];
  };

  MercatorTileSource.prototype.meters_to_pixels = function(mx, my, level) {
    var px, py, res;
    res = this.get_resolution(level);
    px = (mx + this.get('x_origin_offset')) / res;
    py = (my + this.get('y_origin_offset')) / res;
    return [px, py];
  };

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

  MercatorTileSource.prototype.pixels_to_raster = function(px, py, level) {
    var mapSize;
    mapSize = this.get('tile_size') << level;
    return [px, mapSize - py];
  };

  MercatorTileSource.prototype.meters_to_tile = function(mx, my, level) {
    var px, py, ref;
    ref = this.meters_to_pixels(mx, my, level), px = ref[0], py = ref[1];
    return this.pixels_to_tile(px, py);
  };

  MercatorTileSource.prototype.get_tile_meter_bounds = function(tx, ty, level) {
    var ref, ref1, xmax, xmin, ymax, ymin;
    ref = this.pixels_to_meters(tx * this.get('tile_size'), ty * this.get('tile_size'), level), xmin = ref[0], ymin = ref[1];
    ref1 = this.pixels_to_meters((tx + 1) * this.get('tile_size'), (ty + 1) * this.get('tile_size'), level), xmax = ref1[0], ymax = ref1[1];
    if ((xmin != null) && (ymin != null) && (xmax != null) && (ymax != null)) {
      return [xmin, ymin, xmax, ymax];
    } else {
      return void 0;
    }
  };

  MercatorTileSource.prototype.get_tile_geographic_bounds = function(tx, ty, level) {
    var bounds, maxLat, maxLon, minLat, minLon, ref;
    bounds = this.get_tile_meter_bounds(tx, ty, level);
    ref = this.utils.meters_extent_to_geographic(bounds), minLon = ref[0], minLat = ref[1], maxLon = ref[2], maxLat = ref[3];
    return [minLon, minLat, maxLon, maxLat];
  };

  MercatorTileSource.prototype.get_tiles_by_extent = function(extent, level, tile_border) {
    var j, k, ref, ref1, ref2, ref3, ref4, ref5, tiles, tx, txmax, txmin, ty, tymax, tymin, xmax, xmin, ymax, ymin;
    if (tile_border == null) {
      tile_border = 1;
    }
    xmin = extent[0], ymin = extent[1], xmax = extent[2], ymax = extent[3];
    ref = this.meters_to_tile(xmin, ymin, level), txmin = ref[0], tymin = ref[1];
    ref1 = this.meters_to_tile(xmax, ymax, level), txmax = ref1[0], tymax = ref1[1];
    txmin -= tile_border;
    tymin -= tile_border;
    txmax += tile_border;
    tymax += tile_border;
    tiles = [];
    for (ty = j = ref2 = tymax, ref3 = tymin; j >= ref3; ty = j += -1) {
      for (tx = k = ref4 = txmin, ref5 = txmax; k <= ref5; tx = k += 1) {
        tiles.push([tx, ty, level, this.get_tile_meter_bounds(tx, ty, level)]);
        tiles = this.sort_tiles_from_center(tiles, [txmin, tymin, txmax, tymax]);
      }
    }
    return tiles;
  };

  MercatorTileSource.prototype.quadkey_to_tile_xyz = function(quadKey) {
    'Computes tile x, y and z values based on quadKey.';
    var i, j, mask, ref, tileX, tileY, tileZ, value;
    tileX = 0;
    tileY = 0;
    tileZ = quadKey.length;
    for (i = j = ref = tileZ; j > 0; i = j += -1) {
      value = quadKey.charAt(tileZ - i);
      mask = 1 << (i - 1);
      if (value === '0') {
        continue;
      } else if (value === '1') {
        tileX |= mask;
      } else if (value === '2') {
        tileY |= mask;
      } else if (value === '3') {
        tileX |= mask;
        tileY |= mask;
      } else {
        throw new TypeError("Invalid Quadkey: " + quadKey);
      }
    }
    return [tileX, tileY, tileZ];
  };

  MercatorTileSource.prototype.tile_xyz_to_quadkey = function(x, y, z) {
    'Computes quadkey value based on tile x, y and z values.';
    var digit, i, j, mask, quadKey, ref;
    quadKey = '';
    for (i = j = ref = z; j > 0; i = j += -1) {
      digit = 0;
      mask = 1 << (i - 1);
      if ((x & mask) !== 0) {
        digit += 1;
      }
      if ((y & mask) !== 0) {
        digit += 2;
      }
      quadKey += digit.toString();
    }
    return quadKey;
  };

  MercatorTileSource.prototype.children_by_tile_xyz = function(x, y, z) {
    var b, child_tile_xyz, i, j, quad_key, ref;
    quad_key = this.tile_xyz_to_quadkey(x, y, z);
    child_tile_xyz = [];
    for (i = j = 0; j <= 3; i = j += 1) {
      ref = this.quadkey_to_tile_xyz(quad_key + i.toString()), x = ref[0], y = ref[1], z = ref[2];
      b = this.get_tile_meter_bounds(x, y, z);
      if (b != null) {
        child_tile_xyz.push([x, y, z, b]);
      }
    }
    return child_tile_xyz;
  };

  MercatorTileSource.prototype.parent_by_tile_xyz = function(x, y, z) {
    var parent_quad_key, quad_key;
    quad_key = this.tile_xyz_to_quadkey(x, y, z);
    parent_quad_key = quad_key.substring(0, quad_key.length - 1);
    return this.quadkey_to_tile_xyz(parent_quad_key);
  };

  MercatorTileSource.prototype.get_closest_parent_by_tile_xyz = function(x, y, z) {
    var quad_key, ref;
    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);
      ref = this.quadkey_to_tile_xyz(quad_key), x = ref[0], y = ref[1], z = ref[2];
      if (this.tile_xyz_to_key(x, y, z) in this.tiles) {
        return [x, y, z];
      }
    }
    return [0, 0, 0];
  };

  return MercatorTileSource;

})(TileSource);

module.exports = MercatorTileSource;


},{"./tile_source":"renderer/tile/tile_source","underscore":"underscore"}],"renderer/tile/quadkey_tile_source":[function(require,module,exports){
var MercatorTileSource, QUADKEYTileSource,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

MercatorTileSource = require('./mercator_tile_source');

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

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

  QUADKEYTileSource.prototype.type = 'QUADKEYTileSource';

  QUADKEYTileSource.prototype.get_image_url = function(x, y, z) {
    var image_url, quadKey, ref;
    image_url = this.string_lookup_replace(this.get('url'), this.get('extra_url_vars'));
    ref = this.tms_to_wmts(x, y, z), x = ref[0], y = ref[1], z = ref[2];
    quadKey = this.tile_xyz_to_quadkey(x, y, z);
    return image_url.replace("{Q}", quadKey);
  };

  return QUADKEYTileSource;

})(MercatorTileSource);

module.exports = {
  Model: QUADKEYTileSource
};


},{"./mercator_tile_source":"renderer/tile/mercator_tile_source"}],"renderer/tile/tile_renderer":[function(require,module,exports){
var HasParent, ImagePool, PlotWidget, TileRenderer, TileRendererView, _, logger, properties, 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");

HasParent = require("../../common/has_parent");

PlotWidget = require("../../common/plot_widget");

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

wmts = require("./wmts_tile_source");

ImagePool = require("./image_pool");

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

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);
    return TileRendererView.__super__.constructor.apply(this, arguments);
  }

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

  TileRendererView.prototype.get_extent = function() {
    return [this.x_range.get('start'), this.y_range.get('start'), this.x_range.get('end'), this.y_range.get('end')];
  };

  TileRendererView.prototype._set_data = function() {
    this.pool = new ImagePool();
    this.map_plot = this.plot_view.model;
    this.map_canvas = this.plot_view.canvas_view.ctx;
    this.map_frame = this.plot_view.frame;
    this.x_range = this.map_plot.get('x_range');
    this.x_mapper = this.map_frame.get('x_mappers')['default'];
    this.y_range = this.map_plot.get('y_range');
    this.y_mapper = this.map_frame.get('y_mappers')['default'];
    return this.extent = this.get_extent();
  };

  TileRendererView.prototype._map_data = function() {
    var new_extent, zoom_level;
    this.initial_extent = this.get_extent();
    zoom_level = this.mget('tile_source').get_level_by_extent(this.initial_extent, this.map_frame.get('height'), this.map_frame.get('width'));
    new_extent = this.mget('tile_source').snap_to_zoom(this.initial_extent, this.map_frame.get('height'), this.map_frame.get('width'), zoom_level);
    this.x_range.set('start', new_extent[0]);
    this.y_range.set('start', new_extent[1]);
    this.x_range.set('end', new_extent[2]);
    return this.y_range.set('end', new_extent[3]);
  };

  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;
    this.mget('tile_source').tiles[tile_data.cache_key] = tile_data;
    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 this.mget('tile_source').tiles[tile_data.cache_key] = tile_data;
  };

  TileRendererView.prototype._on_tile_error = function(e) {
    return '';
  };

  TileRendererView.prototype._is_valid_tile = function(x, y, z) {
    if (y < 0 || y > 1 << z || x < 0 || x > 1 << z) {
      return false;
    }
    return true;
  };

  TileRendererView.prototype._create_tile = function(x, y, z, bounds, cache_only) {
    var tile;
    if (cache_only == null) {
      cache_only = false;
    }
    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],
      quadkey: this.mget('tile_source').tile_xyz_to_quadkey(x, y, z),
      cache_key: this.mget('tile_source').tile_xyz_to_key(x, y, z),
      bounds: bounds,
      x_coord: bounds[0],
      y_coord: bounds[3]
    };
    tile.src = this.mget('tile_source').get_image_url(x, y, z);
    return tile;
  };

  TileRendererView.prototype.render = function(ctx, indices, args) {
    if (this.map_initialized == null) {
      this._set_data();
      this._map_data();
      this.map_initialized = true;
    }
    this._update();
    if (this.prefetch_timer != null) {
      clearTimeout(this.prefetch_timer);
    }
    return this.prefetch_timer = setTimeout(this._prefetch_tiles, 500);
  };

  TileRendererView.prototype._draw_tile = function(tile_key) {
    var ref, ref1, sh, sw, sx, sxmax, sxmin, sy, symax, symin, tile_obj;
    tile_obj = this.mget('tile_source').tiles[tile_key];
    if (tile_obj != null) {
      ref = this.plot_view.frame.map_to_screen([tile_obj.bounds[0]], [tile_obj.bounds[3]], this.plot_view.canvas), sxmin = ref[0], symin = ref[1];
      ref1 = this.plot_view.frame.map_to_screen([tile_obj.bounds[2]], [tile_obj.bounds[1]], this.plot_view.canvas), sxmax = ref1[0], symax = ref1[1];
      sxmin = sxmin[0];
      symin = symin[0];
      sxmax = sxmax[0];
      symax = symax[0];
      sw = sxmax - sxmin;
      sh = symax - symin;
      sx = sxmin;
      sy = symin;
      return this.map_canvas.drawImage(tile_obj.img, sx, sy, sw, sh);
    }
  };

  TileRendererView.prototype._set_rect = function() {
    var h, l, outline_width, t, w;
    outline_width = this.plot_view.outline_props.width.value();
    l = this.plot_view.canvas.vx_to_sx(this.map_frame.get('left')) + (outline_width / 2);
    t = this.plot_view.canvas.vy_to_sy(this.map_frame.get('top')) + (outline_width / 2);
    w = this.map_frame.get('width') - outline_width;
    h = this.map_frame.get('height') - outline_width;
    this.map_canvas.rect(l, t, w, h);
    return this.map_canvas.clip();
  };

  TileRendererView.prototype._render_tiles = function(tile_keys) {
    var i, len, tile_key;
    this.map_canvas.save();
    this._set_rect();
    this.map_canvas.globalAlpha = this.mget('alpha');
    for (i = 0, len = tile_keys.length; i < len; i++) {
      tile_key = tile_keys[i];
      this._draw_tile(tile_key);
    }
    return this.map_canvas.restore();
  };

  TileRendererView.prototype._prefetch_tiles = function() {
    var bounds, c, cbounds, children, cx, cy, cz, extent, i, ref, results, t, tiles, x, y, z, zoom_level;
    extent = this.get_extent();
    zoom_level = this.mget('tile_source').get_level_by_extent(extent, this.map_frame.get('height'), this.map_frame.get('width'));
    tiles = this.mget('tile_source').get_tiles_by_extent(extent, zoom_level);
    results = [];
    for (t = i = 0, ref = Math.min(10, tiles.length); i <= ref; t = i += 1) {
      x = t[0], y = t[1], z = t[2], bounds = t[3];
      children = this.mget('tile_source').children_by_tile_xyz(x, y, z);
      results.push((function() {
        var j, len, results1;
        results1 = [];
        for (j = 0, len = children.length; j < len; j++) {
          c = children[j];
          cx = c[0], cy = c[1], cz = c[2], cbounds = c[3];
          if (this.mget('tile_source').tile_xyz_to_key(cx, cy, cz) in this.mget('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, i, j, key, len, len1, len2, m, max_zoom, min_zoom, need_load, parent_key, parents, px, py, pz, ref, snap_back, t, tiles, x, y, z, zoom_level, zooming_out;
    min_zoom = this.mget('tile_source').get('min_zoom');
    max_zoom = this.mget('tile_source').get('max_zoom');
    this.mget('tile_source').update();
    extent = this.get_extent();
    zooming_out = this.extent[2] - this.extent[0] < extent[2] - extent[0];
    zoom_level = this.mget('tile_source').get_level_by_extent(extent, this.map_frame.get('height'), this.map_frame.get('width'));
    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.plot_model.set({
        x_range: k
      });
      this.x_range.set({
        x_range: {
          start: extent[0],
          end: extent[2]
        }
      });
      this.y_range.set({
        start: extent[1],
        end: extent[3]
      });
      this.extent = extent;
    }
    this.extent = extent;
    tiles = this.mget('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];
      if (this._is_valid_tile(x, y, z)) {
        key = this.mget('tile_source').tile_xyz_to_key(x, y, z);
        if (key in this.mget('tile_source').tiles) {
          cached.push(key);
        } else {
          ref = this.mget('tile_source').get_closest_parent_by_tile_xyz(x, y, z), px = ref[0], py = ref[1], pz = ref[2];
          parent_key = this.mget('tile_source').tile_xyz_to_key(px, py, pz);
          if (parent_key in this.mget('tile_source').tiles && indexOf.call(parents, parent_key) < 0) {
            parents.push(parent_key);
          }
          if (zooming_out) {
            children = this.mget('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 = this.mget('tile_source').tile_xyz_to_key(cx, cy, cz);
              if (child_key in this.mget('tile_source').tiles) {
                children.push(child_key);
              }
            }
          }
          need_load.push(t);
        }
      }
    }
    this._render_tiles(parents);
    this._render_tiles(children);
    this._render_tiles(cached);
    for (m = 0, len2 = cached.length; m < len2; m++) {
      t = cached[m];
      this.mget('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;

})(PlotWidget);

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.prototype.visuals = [];

  TileRenderer.prototype.angles = ['angle'];

  TileRenderer.prototype.defaults = function() {
    return _.extend({}, TileRenderer.__super__.defaults.call(this), {
      angle: 0,
      alpha: 1.0,
      x_range_name: "default",
      y_range_name: "default",
      tile_source: new wmts.Model()
    });
  };

  TileRenderer.prototype.display_defaults = function() {
    return _.extend({}, TileRenderer.__super__.display_defaults.call(this), {
      level: 'underlay'
    });
  };

  return TileRenderer;

})(HasParent);

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


},{"../../common/has_parent":"common/has_parent","../../common/logging":"common/logging","../../common/plot_widget":"common/plot_widget","../../common/properties":"common/properties","./image_pool":"renderer/tile/image_pool","./wmts_tile_source":"renderer/tile/wmts_tile_source","underscore":"underscore"}],"renderer/tile/tile_source":[function(require,module,exports){
var HasProperties, ImagePool, TileSource, _, logger, tile_utils,
  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");

HasProperties = require("../../common/has_properties");

ImagePool = require("./image_pool");

tile_utils = require("./tile_utils");

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

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

  TileSource.prototype.type = 'TileSource';

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

  TileSource.prototype.defaults = function() {
    return _.extend({}, TileSource.__super__.defaults.call(this), {
      url: '',
      tile_size: 256,
      max_zoom: 30,
      min_zoom: 0,
      extra_url_vars: {},
      full_extent: null,
      x_origin_offset: null,
      y_origin_offset: null,
      initial_resolution: null,
      resolutions: null
    });
  };

  function TileSource(options) {
    if (options == null) {
      options = {};
    }
    this.defaults = bind(this.defaults, this);
    TileSource.__super__.constructor.apply(this, arguments);
    this.utils = new tile_utils.ProjectionUtils();
    this.pool = new ImagePool();
    this.tiles = {};
    this.normalize_case();
  }

  TileSource.prototype.string_lookup_replace = function(str, lookup) {
    var key, result_str, value;
    result_str = str;
    for (key in lookup) {
      value = lookup[key];
      result_str = result_str.replace('{' + key + '}', value.toString());
    }
    return result_str;
  };

  TileSource.prototype.normalize_case = function() {
    'Note: should probably be refactored into subclasses.';
    var url;
    url = this.get('url');
    url = url.replace('{x}', '{X}');
    url = url.replace('{y}', '{Y}');
    url = url.replace('{z}', '{Z}');
    url = url.replace('{q}', '{Q}');
    url = url.replace('{xmin}', '{XMIN}');
    url = url.replace('{ymin}', '{YMIN}');
    url = url.replace('{xmax}', '{XMAX}');
    url = url.replace('{ymax}', '{YMAX}');
    return this.set('url', url);
  };

  TileSource.prototype.update = function() {
    var key, ref, results, tile;
    logger.info("Tile Cache Count: " + Object.keys(this.tiles).length.toString());
    logger.info("X_ORIGIN_OFFSET: " + this.get('x_origin_offset').toString());
    logger.info("Y_ORIGIN_OFFSET: " + this.get('y_origin_offset').toString());
    ref = this.tiles;
    results = [];
    for (key in ref) {
      tile = ref[key];
      tile.current = false;
      results.push(tile.retain = false);
    }
    return results;
  };

  TileSource.prototype.tile_xyz_to_key = function(x, y, z) {
    var key;
    key = x + ":" + y + ":" + z;
    return key;
  };

  TileSource.prototype.key_to_tile_xyz = function(key) {
    var c;
    return (function() {
      var i, len, ref, results;
      ref = key.split(':');
      results = [];
      for (i = 0, len = ref.length; i < len; i++) {
        c = ref[i];
        results.push(parseInt(c));
      }
      return results;
    })();
  };

  TileSource.prototype.sort_tiles_from_center = function(tiles, tile_extent) {
    var center_x, center_y, txmax, txmin, tymax, tymin;
    txmin = tile_extent[0], tymin = tile_extent[1], txmax = tile_extent[2], tymax = tile_extent[3];
    center_x = (txmax - txmin) / 2 + txmin;
    center_y = (tymax - tymin) / 2 + tymin;
    tiles.sort(function(a, b) {
      var a_distance, b_distance;
      a_distance = Math.sqrt(Math.pow(center_x - a[0], 2) + Math.pow(center_y - a[1], 2));
      b_distance = Math.sqrt(Math.pow(center_x - b[0], 2) + Math.pow(center_y - b[1], 2));
      return a_distance - b_distance;
    });
    return tiles;
  };

  TileSource.prototype.prune_tiles = function() {
    var key, ref, ref1, results, tile;
    ref = this.tiles;
    for (key in ref) {
      tile = ref[key];
      tile.retain = tile.current || tile.tile_coords[2] < 3;
      if (tile.current) {
        this.retain_neighbors(tile);
        this.retain_children(tile);
        this.retain_parents(tile);
      }
    }
    ref1 = this.tiles;
    results = [];
    for (key in ref1) {
      tile = ref1[key];
      if (!tile.retain) {
        results.push(this.remove_tile(key));
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  TileSource.prototype.remove_tile = function(key) {
    var tile;
    tile = this.tiles[key];
    if (tile != null) {
      this.pool.push(tile.img);
      return delete this.tiles[key];
    }
  };

  TileSource.prototype.get_image_url = function(x, y, z) {
    var image_url;
    image_url = this.string_lookup_replace(this.get('url'), this.get('extra_url_vars'));
    return image_url.replace("{X}", x).replace('{Y}', y).replace("{Z}", z);
  };

  TileSource.prototype.retain_neighbors = function(reference_tile) {
    throw Error("Not Implemented");
  };

  TileSource.prototype.retain_parents = function(reference_tile) {
    throw Error("Not Implemented");
  };

  TileSource.prototype.retain_children = function(reference_tile) {
    throw Error("Not Implemented");
  };

  TileSource.prototype.tile_xyz_to_quadkey = function(x, y, z) {
    throw Error("Not Implemented");
  };

  TileSource.prototype.quadkey_to_tile_xyz = function(quadkey) {
    throw Error("Not Implemented");
  };

  return TileSource;

})(HasProperties);

module.exports = TileSource;


},{"../../common/has_properties":"common/has_properties","../../common/logging":"common/logging","./image_pool":"renderer/tile/image_pool","./tile_utils":"renderer/tile/tile_utils","underscore":"underscore"}],"renderer/tile/tile_utils":[function(require,module,exports){
var ProjectionUtils, mercator, proj4, wgs84;

proj4 = require("proj4");

mercator = proj4.defs('GOOGLE');

wgs84 = proj4.defs('WGS84');

ProjectionUtils = (function() {
  function ProjectionUtils() {
    this.origin_shift = 2 * Math.PI * 6378137 / 2.0;
  }

  ProjectionUtils.prototype.geographic_to_meters = function(xLon, yLat) {
    return proj4(wgs84, mercator, [xLon, yLat]);
  };

  ProjectionUtils.prototype.meters_to_geographic = function(mx, my) {
    return proj4(mercator, wgs84, [mx, my]);
  };

  ProjectionUtils.prototype.geographic_extent_to_meters = function(extent) {
    var ref, ref1, xmax, xmin, ymax, ymin;
    xmin = extent[0], ymin = extent[1], xmax = extent[2], ymax = extent[3];
    ref = this.geographic_to_meters(xmin, ymin), xmin = ref[0], ymin = ref[1];
    ref1 = this.geographic_to_meters(xmax, ymax), xmax = ref1[0], ymax = ref1[1];
    return [xmin, ymin, xmax, ymax];
  };

  ProjectionUtils.prototype.meters_extent_to_geographic = function(extent) {
    var ref, ref1, xmax, xmin, ymax, ymin;
    xmin = extent[0], ymin = extent[1], xmax = extent[2], ymax = extent[3];
    ref = this.meters_to_geographic(xmin, ymin), xmin = ref[0], ymin = ref[1];
    ref1 = this.meters_to_geographic(xmax, ymax), xmax = ref1[0], ymax = ref1[1];
    return [xmin, ymin, xmax, ymax];
  };

  return ProjectionUtils;

})();

module.exports = {
  ProjectionUtils: ProjectionUtils
};


},{"proj4":"proj4"}],"renderer/tile/tms_tile_source":[function(require,module,exports){
var MercatorTileSource, TMSTileSource,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

MercatorTileSource = require('./mercator_tile_source');

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

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

  TMSTileSource.prototype.type = 'TMSTileSource';

  TMSTileSource.prototype.get_image_url = function(x, y, z) {
    var image_url;
    image_url = this.string_lookup_replace(this.get('url'), this.get('extra_url_vars'));
    return image_url.replace("{X}", x).replace('{Y}', y).replace("{Z}", z);
  };

  return TMSTileSource;

})(MercatorTileSource);

module.exports = {
  Model: TMSTileSource
};


},{"./mercator_tile_source":"renderer/tile/mercator_tile_source"}],"renderer/tile/wmts_tile_source":[function(require,module,exports){
var MercatorTileSource, WMTSTileSource,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

MercatorTileSource = require('./mercator_tile_source');

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

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

  WMTSTileSource.prototype.type = 'WMTSTileSource';

  WMTSTileSource.prototype.get_image_url = function(x, y, z) {
    var image_url, ref;
    image_url = this.string_lookup_replace(this.get('url'), this.get('extra_url_vars'));
    ref = this.tms_to_wmts(x, y, z), x = ref[0], y = ref[1], z = ref[2];
    return image_url.replace("{X}", x).replace('{Y}', y).replace("{Z}", z);
  };

  return WMTSTileSource;

})(MercatorTileSource);

module.exports = {
  Model: WMTSTileSource
};


},{"./mercator_tile_source":"renderer/tile/mercator_tile_source"}],"source/ajax_data_source":[function(require,module,exports){
var $, AjaxDataSource, AjaxDataSources, Backbone, RemoteDataSource, _, logger,
  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");

Backbone = require("backbone");

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

RemoteDataSource = require("./remote_data_source");

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

  function AjaxDataSource() {
    this.defaults = bind(this.defaults, this);
    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.prototype.destroy = function() {
    if (this.interval != null) {
      return clearInterval(this.interval);
    }
  };

  AjaxDataSource.prototype.setup = function(plot_view, glyph) {
    this.pv = plot_view;
    this.get_data(this.get('mode'));
    if (this.get('polling_interval')) {
      return this.interval = setInterval(this.get_data, this.get('polling_interval'), this.get('mode'), this.get('max_size'), this.get('if_modified'));
    }
  };

  AjaxDataSource.prototype.get_data = function(mode, max_size, if_modified) {
    if (max_size == null) {
      max_size = 0;
    }
    if (if_modified == null) {
      if_modified = false;
    }
    $.ajax({
      dataType: 'json',
      ifModified: if_modified,
      url: this.get('data_url'),
      xhrField: {
        withCredentials: true
      },
      method: this.get('method'),
      contentType: 'application/json'
    }).done((function(_this) {
      return function(data) {
        var column, i, len, original_data, ref;
        if (mode === 'replace') {
          _this.set('data', data);
        } else if (mode === 'append') {
          original_data = _this.get('data');
          ref = _this.columns();
          for (i = 0, len = ref.length; i < len; i++) {
            column = ref[i];
            data[column] = original_data[column].concat(data[column]).slice(-max_size);
          }
          _this.set('data', data);
        } else {
          logger.error("unsupported mode: " + mode);
        }
        logger.trace(data);
        return null;
      };
    })(this)).error(function() {
      return logger.error(arguments);
    });
    return null;
  };

  AjaxDataSource.prototype.defaults = function() {
    return _.extend({}, AjaxDataSource.__super__.defaults.call(this), {
      mode: 'replace'
    });
  };

  return AjaxDataSource;

})(RemoteDataSource.RemoteDataSource);

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

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

  AjaxDataSources.prototype.model = AjaxDataSource;

  AjaxDataSources.prototype.defaults = {
    url: "",
    expr: null
  };

  return AjaxDataSources;

})(Backbone.Collection);

module.exports = {
  Model: AjaxDataSource,
  Collection: new AjaxDataSources()
};


},{"../common/logging":"common/logging","./remote_data_source":"source/remote_data_source","backbone":"backbone","jquery":"jquery","underscore":"underscore"}],"source/blaze_data_source":[function(require,module,exports){
var $, Backbone, BlazeDataSource, BlazeDataSources, RemoteDataSource, _, logger,
  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");

Backbone = require("backbone");

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

RemoteDataSource = require("./remote_data_source");

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

  function BlazeDataSource() {
    this.update = bind(this.update, this);
    this.setup = bind(this.setup, this);
    this.destroy = bind(this.destroy, this);
    return BlazeDataSource.__super__.constructor.apply(this, arguments);
  }

  BlazeDataSource.prototype.type = 'BlazeDataSource';

  BlazeDataSource.prototype.destroy = function() {
    if (this.interval != null) {
      return clearInterval(this.interval);
    }
  };

  BlazeDataSource.prototype.setup = function(plot_view, glyph) {
    this.pv = plot_view;
    this.update();
    if (this.get('polling_interval')) {
      return this.interval = setInterval(this.update, this.get('polling_interval'));
    }
  };

  BlazeDataSource.prototype.update = function() {
    var data;
    data = JSON.stringify({
      expr: this.get('expr'),
      namespace: this.get('namespace')
    });
    return $.ajax({
      dataType: 'json',
      url: this.get('data_url'),
      data: data,
      xhrField: {
        withCredentials: true
      },
      method: 'POST',
      contentType: 'application/json'
    }).done((function(_this) {
      return function(data) {
        var colname, columns_of_data, data_dict, i, idx, len, orig_data, ref;
        columns_of_data = _.zip.apply(_, data.data);
        data_dict = {};
        ref = data.names;
        for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
          colname = ref[idx];
          data_dict[colname] = columns_of_data[idx];
        }
        orig_data = _.clone(_this.get('data'));
        _.extend(orig_data, data_dict);
        _this.set('data', orig_data);
        return null;
      };
    })(this));
  };

  return BlazeDataSource;

})(RemoteDataSource.RemoteDataSource);

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

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

  BlazeDataSources.prototype.model = BlazeDataSource;

  BlazeDataSources.prototype.defaults = {
    url: "",
    expr: null
  };

  return BlazeDataSources;

})(Backbone.Collection);

module.exports = {
  Model: BlazeDataSource,
  Collection: new BlazeDataSources()
};


},{"../common/logging":"common/logging","./remote_data_source":"source/remote_data_source","backbone":"backbone","jquery":"jquery","underscore":"underscore"}],"source/column_data_source":[function(require,module,exports){
var ColumnDataSource, HasProperties, SelectionManager, _, hittest,
  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");

HasProperties = require("../common/has_properties");

SelectionManager = require("../common/selection_manager");

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

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

  function ColumnDataSource() {
    this.defaults = bind(this.defaults, this);
    return ColumnDataSource.__super__.constructor.apply(this, arguments);
  }

  ColumnDataSource.prototype.type = 'ColumnDataSource';

  ColumnDataSource.prototype.initialize = function(options) {
    ColumnDataSource.__super__.initialize.call(this, options);
    return this.listenTo(this, 'change:selected', (function(_this) {
      return function() {
        var ref;
        return (ref = _this.get('callback')) != null ? ref.execute(_this) : void 0;
      };
    })(this));
  };

  ColumnDataSource.prototype.nonserializable_attribute_names = function() {
    return ColumnDataSource.__super__.nonserializable_attribute_names.call(this).concat(['selection_manager']);
  };

  ColumnDataSource.prototype.get_column = function(colname) {
    var ref;
    return (ref = this.get('data')[colname]) != null ? ref : null;
  };

  ColumnDataSource.prototype.get_length = function() {
    var data, key, lengths, val;
    data = this.get('data');
    if (_.keys(data).length === 0) {
      return null;
    } else {
      lengths = _.uniq((function() {
        var results;
        results = [];
        for (key in data) {
          val = data[key];
          results.push(val.length);
        }
        return results;
      })());
      return lengths[0];
    }
  };

  ColumnDataSource.prototype.columns = function() {
    return _.keys(this.get('data'));
  };

  ColumnDataSource.prototype.defaults = function() {
    return _.extend({}, ColumnDataSource.__super__.defaults.call(this), {
      data: {},
      selection_manager: new SelectionManager({
        'source': this
      }),
      selected: hittest.create_hit_test_result()
    });
  };

  return ColumnDataSource;

})(HasProperties);

module.exports = {
  Model: ColumnDataSource
};


},{"../common/has_properties":"common/has_properties","../common/hittest":"common/hittest","../common/selection_manager":"common/selection_manager","underscore":"underscore"}],"source/remote_data_source":[function(require,module,exports){
var Backbone, ColumnDataSource, RemoteDataSource, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

ColumnDataSource = require("./column_data_source");

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

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

  return RemoteDataSource;

})(ColumnDataSource.Model);

module.exports = {
  RemoteDataSource: RemoteDataSource
};


},{"./column_data_source":"source/column_data_source","backbone":"backbone","underscore":"underscore"}],"source/server_data_source":[function(require,module,exports){
var $, AbstractRenderingSource, Backbone, DataRange1d, HasProperties, HeatmapSource, Line1dSource, Range1d, RemoteDataSource, ServerDataSource, ServerSourceUpdater, _, ajax_throttle, 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,
  bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

$ = require("jquery");

_ = require("underscore");

Backbone = require("backbone");

HasProperties = require("../common/has_properties");

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

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

DataRange1d = require("../range/data_range1d");

RemoteDataSource = require("./remote_data_source");

ajax_throttle = function(func) {
  var busy, callback, has_callback, resp;
  busy = false;
  resp = null;
  has_callback = false;
  callback = function() {
    if (busy) {
      if (has_callback) {
        return logger.debug('already bound, ignoring');
      } else {
        logger.debug('busy, so doing it later');
        has_callback = true;
        return resp.done(function() {
          has_callback = false;
          return callback();
        });
      }
    } else {
      logger.debug('executing');
      busy = true;
      resp = func();
      return resp.done(function() {
        logger.debug('done, setting to false');
        busy = false;
        return resp = null;
      });
    }
  };
  return callback;
};

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

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

  ServerSourceUpdater.prototype.initialize = function(attrs, options) {
    ServerSourceUpdater.__super__.initialize.call(this, attrs, options);
    this.callbacks = [];
    this.plot_state = {
      data_x: options.data_x,
      data_y: options.data_y,
      screen_x: options.screen_x,
      screen_y: options.screen_y
    };
    this.glyph = options.glyph;
    this.data_source = options.data_source;
    this.render_state = options.render_state;
    return this.auto_bounds = options.data_source.get('transform')['auto_bounds'];
  };

  ServerSourceUpdater.prototype.stoplistening_for_updates = function() {
    var entry, i, len, ref, results;
    ref = this.callbacks;
    results = [];
    for (i = 0, len = ref.length; i < len; i++) {
      entry = ref[i];
      results.push(this.stopListening.apply(this, entry));
    }
    return results;
  };

  ServerSourceUpdater.prototype.listen_for_updates = function() {
    var callback, i, len, param, ranges;
    this.stoplistening_for_updates();
    callback = ajax_throttle((function(_this) {
      return function() {
        return _this.update();
      };
    })(this));
    callback = _.debounce(callback, 100);
    callback();
    ranges = [this.plot_state['data_x'], this.plot_state['data_x'], this.plot_state['screen_x'], this.plot_state['screen_y']];
    for (i = 0, len = ranges.length; i < len; i++) {
      param = ranges[i];
      this.listenTo(param, 'change', callback);
      this.callbacks.push([param, 'change', callback]);
    }
    return null;
  };

  ServerSourceUpdater.prototype.update = function() {
    return null;
  };

  ServerSourceUpdater.prototype.plot_state_json = function() {
    var item, key, proxy, ref, sendable_plot_state;
    sendable_plot_state = {};
    ref = this.plot_state;
    for (key in ref) {
      item = ref[key];
      proxy = new Range1d.Model();
      proxy.set('start', item.get('start'));
      proxy.set('end', item.get('end'));
      sendable_plot_state[key] = proxy;
    }
    return sendable_plot_state;
  };

  ServerSourceUpdater.prototype.update_url = function() {
    var base_url, docid, glyph, glyphid, sourceid, url;
    glyph = this.glyph;
    if (this.get('data_url')) {
      url = data_url;
      base_url = url.replace("/compute.json", "/render");
    } else {
      base_url = glyph.get_base().Config.prefix + "render";
    }
    docid = this.glyph.get('doc');
    sourceid = this.data_source.get('id');
    glyphid = glyph.get('id');
    url = base_url + "/" + docid + "/" + sourceid + "/" + glyphid;
    return url;
  };

  return ServerSourceUpdater;

})(Backbone.Model);

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

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

  AbstractRenderingSource.prototype.update = function() {
    var data, plot_state, render_state, resp;
    plot_state = this.plot_state;
    render_state = this.render_state;
    if (!render_state) {
      render_state = {};
    }
    if (plot_state['screen_x'].get('start') === plot_state['screen_x'].get('end') || plot_state['screen_y'].get('start') === plot_state['screen_y'].get('end')) {
      logger.debug("skipping due to under-defined view state");
      return $.ajax();
    }
    logger.debug("Sent render State", render_state);
    data = {
      plot_state: this.plot_state_json(),
      render_state: render_state,
      auto_bounds: this.auto_bounds
    };
    resp = $.ajax({
      method: 'POST',
      dataType: 'json',
      url: this.update_url(),
      xhrField: {
        withCredentials: true
      },
      contentType: 'application/json',
      data: JSON.stringify(data),
      success: (function(_this) {
        return function(data) {
          var new_data;
          if (data.render_state === "NO UPDATE") {
            logger.info("No update");
            return;
          }
          if (_this.auto_bounds) {
            plot_state['data_x'].set({
              start: data.x_range.start,
              end: data.x_range.end
            });
            plot_state['data_y'].set({
              start: data.y_range.start,
              end: data.y_range.end
            });
            _this.auto_bounds = false;
          }
          logger.debug("New render State:", data.render_state);
          new_data = _.clone(_this.data_source.get('data'));
          _.extend(new_data, data['data']);
          _this.data_source.set('data', new_data);
          return null;
        };
      })(this)
    });
    return resp;
  };

  return AbstractRenderingSource;

})(ServerSourceUpdater);

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

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

  Line1dSource.prototype.update = function() {
    var data, plot_state, render_state, resp;
    plot_state = this.plot_state;
    render_state = this.render_state;
    if (!render_state) {
      render_state = {};
    }
    if (plot_state['screen_x'].get('start') === plot_state['screen_x'].get('end') || plot_state['screen_y'].get('start') === plot_state['screen_y'].get('end')) {
      logger.debug("skipping due to under-defined view state");
      return $.ajax();
    }
    logger.debug("Sent render State", render_state);
    data = {
      plot_state: this.plot_state_json(),
      render_state: render_state,
      auto_bounds: this.auto_bounds
    };
    resp = $.ajax({
      method: 'POST',
      dataType: 'json',
      url: this.update_url(),
      xhrField: {
        withCredentials: true
      },
      contentType: 'application/json',
      data: JSON.stringify(data),
      success: (function(_this) {
        return function(data) {
          var new_data;
          if (data.render_state === "NO UPDATE") {
            logger.info("No update");
            return;
          }
          if (_this.auto_bounds) {
            plot_state['data_x'].set({
              start: data.x_range.start,
              end: data.x_range.end
            });
            plot_state['data_y'].set({
              start: data.y_range.start,
              end: data.y_range.end
            });
            _this.auto_bounds = false;
          }
          logger.debug("New render State:", data.render_state);
          new_data = _.clone(_this.data_source.get('data'));
          _.extend(new_data, data['data']);
          _this.data_source.set('data', new_data);
          return null;
        };
      })(this)
    });
    return resp;
  };

  return Line1dSource;

})(ServerSourceUpdater);

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

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

  HeatmapSource.prototype.update = function() {
    var data, plot_state, render_state, resp;
    plot_state = this.plot_state;
    render_state = this.render_state;
    if (!render_state) {
      render_state = {};
    }
    if (plot_state['screen_x'].get('start') === plot_state['screen_x'].get('end') || plot_state['screen_y'].get('start') === plot_state['screen_y'].get('end')) {
      logger.debug("skipping due to under-defined view state");
      return $.ajax();
    }
    logger.debug("Sent render State", render_state);
    data = {
      plot_state: this.plot_state_json(),
      render_state: render_state,
      auto_bounds: this.auto_bounds
    };
    resp = $.ajax({
      method: 'POST',
      dataType: 'json',
      url: this.update_url(),
      xhrField: {
        withCredentials: true
      },
      contentType: 'application/json',
      data: JSON.stringify(data),
      success: (function(_this) {
        return function(data) {
          var new_data;
          if (data.render_state === "NO UPDATE") {
            logger.info("No update");
            return;
          }
          if (_this.auto_bounds) {
            plot_state['data_x'].set({
              start: data.x_range.start,
              end: data.x_range.end
            });
            plot_state['data_y'].set({
              start: data.y_range.start,
              end: data.y_range.end
            });
            _this.auto_bounds = false;
          }
          logger.debug("New render State:", data.render_state);
          new_data = _.clone(_this.data_source.get('data'));
          _.extend(new_data, data['data']);
          _this.data_source.set('data', new_data);
          return null;
        };
      })(this)
    });
    return resp;
  };

  return HeatmapSource;

})(ServerSourceUpdater);

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

  function ServerDataSource() {
    this.setup_proxy = bind(this.setup_proxy, this);
    this.setup = bind(this.setup, this);
    this.initialize = bind(this.initialize, this);
    return ServerDataSource.__super__.constructor.apply(this, arguments);
  }

  ServerDataSource.prototype.type = 'ServerDataSource';

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

  ServerDataSource.prototype.setup = function(plot_view, glyph) {
    var data_x_range, data_y_range, options, plot_h_range, plot_v_range;
    plot_h_range = plot_v_range = data_x_range = data_y_range = options = {
      data_x: plot_view.x_range,
      data_y: plot_view.y_range,
      screen_x: plot_view.frame.get('h_range'),
      screen_y: plot_view.frame.get('v_range'),
      glyph: glyph.model
    };
    return this.setup_proxy(options);
  };

  ServerDataSource.prototype.setup_proxy = function(options) {
    options['data_source'] = this;
    if (this.get('transform')['resample'] === 'abstract rendering') {
      this.proxy = new AbstractRenderingSource({}, options);
    } else if (this.get('transform')['resample'] === 'line1d') {
      this.proxy = new Line1dSource({}, options);
    } else if (this.get('transform')['resample'] === 'heatmap') {
      this.proxy = new HeatmapSource({}, options);
    }
    return this.proxy.listen_for_updates();
  };

  return ServerDataSource;

})(RemoteDataSource.RemoteDataSource);

module.exports = {
  Model: ServerDataSource
};


},{"../common/has_properties":"common/has_properties","../common/logging":"common/logging","../range/data_range1d":"range/data_range1d","../range/range1d":"range/range1d","./remote_data_source":"source/remote_data_source","backbone":"backbone","jquery":"jquery","underscore":"underscore"}],"ticking/abstract_ticker":[function(require,module,exports){
var AbstractTicker, DEFAULT_DESIRED_NUM_TICKS, HasProperties, _, repr,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

HasProperties = require("../common/has_properties");

repr = function(obj) {
  var elem, elems_str, key, obj_as_string, props_str;
  if (obj === null) {
    return "null";
  }
  if (obj == null) {
    return "undefined";
  } else if (obj.constructor === Array) {
    elems_str = ((function() {
      var j, len, results;
      results = [];
      for (j = 0, len = obj.length; j < len; j++) {
        elem = obj[j];
        results.push(repr(elem));
      }
      return results;
    })()).join(", ");
    return "[" + elems_str + "]";
  } else if (obj.constructor === Object) {
    props_str = ((function() {
      var results;
      results = [];
      for (key in obj) {
        results.push(key + ": " + (repr(obj[key])));
      }
      return results;
    })()).join(", ");
    return "{" + props_str + "}";
  } else if (obj.constructor === String) {
    return "\"" + obj + "\"";
  } else if (obj.constructor === Function) {
    return "<Function: " + obj.name + ">";
  } else {
    obj_as_string = obj.toString();
    if (obj_as_string === "[object Object]") {
      return "<" + obj.constructor.name + ">";
    } else {
      return obj_as_string;
    }
  }
};

DEFAULT_DESIRED_NUM_TICKS = 6;

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

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

  AbstractTicker.prototype.type = 'AbstractTicker';

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

  AbstractTicker.prototype.nonserializable_attribute_names = function() {
    return AbstractTicker.__super__.nonserializable_attribute_names.call(this).concat(['toString_properties']);
  };

  AbstractTicker.prototype.set = function(key, value, options) {
    if (key === 'max_interval' && value === null) {
      value = Infinity;
    } else if (_.isObject(key) && 'max_interval' in key && key['max_interval'] === null) {
      key['max_interval'] = Infinity;
    }
    return AbstractTicker.__super__.set.call(this, key, value, options);
  };

  AbstractTicker.prototype.get_ticks = function(data_low, data_high, range, arg) {
    var desired_n_ticks;
    desired_n_ticks = arg.desired_n_ticks;
    return this.get_ticks_no_defaults(data_low, data_high, this.get('desired_num_ticks'));
  };

  AbstractTicker.prototype.get_ticks_no_defaults = function(data_low, data_high, desired_n_ticks) {
    var end_factor, factor, factors, i, interval, j, k, l, len, len1, len2, minor_interval, minor_offsets, minor_ticks, num_minor_ticks, start_factor, tick, ticks, x;
    interval = this.get_interval(data_low, data_high, desired_n_ticks);
    start_factor = Math.floor(data_low / interval);
    end_factor = Math.ceil(data_high / interval);
    if (_.isNaN(start_factor) || _.isNaN(end_factor)) {
      factors = [];
    } else {
      factors = _.range(start_factor, end_factor + 1);
    }
    ticks = (function() {
      var j, len, results;
      results = [];
      for (j = 0, len = factors.length; j < len; j++) {
        factor = factors[j];
        results.push(factor * interval);
      }
      return results;
    })();
    num_minor_ticks = this.get("num_minor_ticks");
    minor_ticks = [];
    if (num_minor_ticks > 1) {
      minor_interval = interval / num_minor_ticks;
      minor_offsets = (function() {
        var j, ref, results;
        results = [];
        for (i = j = 1, ref = num_minor_ticks; 1 <= ref ? j <= ref : j >= ref; i = 1 <= ref ? ++j : --j) {
          results.push(i * minor_interval);
        }
        return results;
      })();
      for (j = 0, len = minor_offsets.length; j < len; j++) {
        x = minor_offsets[j];
        minor_ticks.push(ticks[0] - x);
      }
      for (k = 0, len1 = ticks.length; k < len1; k++) {
        tick = ticks[k];
        for (l = 0, len2 = minor_offsets.length; l < len2; l++) {
          x = minor_offsets[l];
          minor_ticks.push(tick + x);
        }
      }
    }
    return {
      "major": ticks,
      "minor": minor_ticks
    };
  };

  AbstractTicker.prototype.get_interval = void 0;

  AbstractTicker.prototype.get_min_interval = function() {
    return this.get('min_interval');
  };

  AbstractTicker.prototype.get_max_interval = function() {
    return this.get('max_interval');
  };

  AbstractTicker.prototype.toString = function() {
    var class_name, key, params_str, props;
    class_name = typeof this;
    props = this.get('toString_properties');
    params_str = ((function() {
      var j, len, results;
      results = [];
      for (j = 0, len = props.length; j < len; j++) {
        key = props[j];
        results.push(key + "=" + (repr(this[key])));
      }
      return results;
    }).call(this)).join(", ");
    return class_name + "(" + params_str + ")";
  };

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

  AbstractTicker.prototype.defaults = function() {
    return _.extend({}, AbstractTicker.__super__.defaults.call(this), {
      toString_properties: [],
      num_minor_ticks: 5,
      desired_num_ticks: DEFAULT_DESIRED_NUM_TICKS
    });
  };

  return AbstractTicker;

})(HasProperties);

module.exports = {
  Model: AbstractTicker
};


},{"../common/has_properties":"common/has_properties","underscore":"underscore"}],"ticking/adaptive_ticker":[function(require,module,exports){
var AbstractTicker, AdaptiveTicker, _, argmin, clamp, log,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

AbstractTicker = require("./abstract_ticker");

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

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.prototype.initialize = function(attrs, options) {
    var prefix_mantissa, suffix_mantissa;
    AdaptiveTicker.__super__.initialize.call(this, attrs, options);
    prefix_mantissa = _.last(this.get('mantissas')) / this.get('base');
    suffix_mantissa = _.first(this.get('mantissas')) * this.get('base');
    this.extended_mantissas = _.flatten([prefix_mantissa, this.get('mantissas'), suffix_mantissa]);
    return this.base_factor = this.get('min_interval') === 0.0 ? 1.0 : this.get('min_interval');
  };

  AdaptiveTicker.prototype.get_interval = function(data_low, data_high, desired_n_ticks) {
    var best_mantissa, candidate_mantissas, data_range, errors, ideal_interval, ideal_magnitude, ideal_mantissa, interval, interval_exponent;
    data_range = data_high - data_low;
    ideal_interval = this.get_ideal_interval(data_low, data_high, desired_n_ticks);
    interval_exponent = Math.floor(log(ideal_interval / this.base_factor, this.get('base')));
    ideal_magnitude = Math.pow(this.get('base'), interval_exponent) * this.base_factor;
    ideal_mantissa = ideal_interval / ideal_magnitude;
    candidate_mantissas = this.extended_mantissas;
    errors = candidate_mantissas.map(function(mantissa) {
      return Math.abs(desired_n_ticks - (data_range / (mantissa * ideal_magnitude)));
    });
    best_mantissa = candidate_mantissas[argmin(errors)];
    interval = best_mantissa * ideal_magnitude;
    return clamp(interval, this.get('min_interval'), this.get('max_interval'));
  };

  AdaptiveTicker.prototype.defaults = function() {
    return _.extend({}, AdaptiveTicker.__super__.defaults.call(this), {
      toString_properties: ['mantissas', 'base', 'min_magnitude', 'max_magnitude'],
      base: 10.0,
      mantissas: [2, 5, 10],
      min_interval: 0.0,
      max_interval: Infinity
    });
  };

  return AdaptiveTicker;

})(AbstractTicker.Model);

module.exports = {
  Model: AdaptiveTicker
};


},{"./abstract_ticker":"ticking/abstract_ticker","./util":"ticking/util","underscore":"underscore"}],"ticking/basic_tick_formatter":[function(require,module,exports){
var BasicTickFormatter, HasProperties, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

HasProperties = require("../common/has_properties");

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

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

  BasicTickFormatter.prototype.type = 'BasicTickFormatter';

  BasicTickFormatter.prototype.initialize = function(attrs, options) {
    BasicTickFormatter.__super__.initialize.call(this, attrs, options);
    this.register_property('scientific_limit_low', function() {
      return Math.pow(10.0, this.get('power_limit_low'));
    }, true);
    this.add_dependencies('scientific_limit_low', this, ['power_limit_low']);
    this.register_property('scientific_limit_high', function() {
      return Math.pow(10.0, this.get('power_limit_high'));
    }, true);
    this.add_dependencies('scientific_limit_high', this, ['power_limit_high']);
    return this.last_precision = 3;
  };

  BasicTickFormatter.prototype.format = function(ticks) {
    var i, is_ok, j, k, l, labels, len, m, n, need_sci, o, precision, ref, ref1, ref2, ref3, ref4, tick, tick_abs, x, zero_eps;
    if (ticks.length === 0) {
      return [];
    }
    zero_eps = 0;
    if (ticks.length >= 2) {
      zero_eps = Math.abs(ticks[1] - ticks[0]) / 10000;
    }
    need_sci = false;
    if (this.get('use_scientific')) {
      for (j = 0, len = ticks.length; j < len; j++) {
        tick = ticks[j];
        tick_abs = Math.abs(tick);
        if (tick_abs > zero_eps && (tick_abs >= this.get('scientific_limit_high') || tick_abs <= this.get('scientific_limit_low'))) {
          need_sci = true;
          break;
        }
      }
    }
    precision = this.get('precision');
    if ((precision == null) || _.isNumber(precision)) {
      labels = new Array(ticks.length);
      if (need_sci) {
        for (i = k = 0, ref = ticks.length; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) {
          labels[i] = ticks[i].toExponential(precision || void 0);
        }
      } else {
        for (i = l = 0, ref1 = ticks.length; 0 <= ref1 ? l < ref1 : l > ref1; i = 0 <= ref1 ? ++l : --l) {
          labels[i] = ticks[i].toFixed(precision || void 0).replace(/(\.[0-9]*?)0+$/, "$1").replace(/\.$/, "");
        }
      }
      return labels;
    } else if (precision === 'auto') {
      labels = new Array(ticks.length);
      for (x = m = ref2 = this.last_precision; ref2 <= 15 ? m <= 15 : m >= 15; x = ref2 <= 15 ? ++m : --m) {
        is_ok = true;
        if (need_sci) {
          for (i = n = 0, ref3 = ticks.length; 0 <= ref3 ? n < ref3 : n > ref3; i = 0 <= ref3 ? ++n : --n) {
            labels[i] = ticks[i].toExponential(x);
            if (i > 0) {
              if (labels[i] === labels[i - 1]) {
                is_ok = false;
                break;
              }
            }
          }
          if (is_ok) {
            break;
          }
        } else {
          for (i = o = 0, ref4 = ticks.length; 0 <= ref4 ? o < ref4 : o > ref4; i = 0 <= ref4 ? ++o : --o) {
            labels[i] = ticks[i].toFixed(x).replace(/(\.[0-9]*?)0+$/, "$1").replace(/\.$/, "");
            if (i > 0) {
              if (labels[i] === labels[i - 1]) {
                is_ok = false;
                break;
              }
            }
          }
          if (is_ok) {
            break;
          }
        }
        if (is_ok) {
          this.last_precision = x;
          return labels;
        }
      }
    }
    return labels;
  };

  BasicTickFormatter.prototype.defaults = function() {
    return _.extend({}, BasicTickFormatter.__super__.defaults.call(this), {
      precision: 'auto',
      use_scientific: true,
      power_limit_high: 5,
      power_limit_low: -3
    });
  };

  return BasicTickFormatter;

})(HasProperties);

module.exports = {
  Model: BasicTickFormatter
};


},{"../common/has_properties":"common/has_properties","underscore":"underscore"}],"ticking/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';

  BasicTicker.prototype.defaults = function() {
    return _.extend({}, BasicTicker.__super__.defaults.call(this), {
      mantissas: [1, 2, 5]
    });
  };

  return BasicTicker;

})(AdaptiveTicker.Model);

module.exports = {
  Model: BasicTicker
};


},{"./adaptive_ticker":"ticking/adaptive_ticker","underscore":"underscore"}],"ticking/categorical_tick_formatter":[function(require,module,exports){
var CategoricalTickFormatter, HasProperties,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

HasProperties = require("../common/has_properties");

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

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

  CategoricalTickFormatter.prototype.type = 'CategoricalTickFormatter';

  CategoricalTickFormatter.prototype.format = function(ticks) {
    return ticks;
  };

  return CategoricalTickFormatter;

})(HasProperties);

module.exports = {
  Model: CategoricalTickFormatter
};


},{"../common/has_properties":"common/has_properties"}],"ticking/categorical_ticker":[function(require,module,exports){
var CategoricalTicker, HasProperties,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

HasProperties = require("../common/has_properties");

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

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

  CategoricalTicker.prototype.type = 'CategoricalTicker';

  CategoricalTicker.prototype.get_ticks = function(start, end, range, arg) {
    var desired_n_ticks, factors, i, ii, j, majors, ref;
    desired_n_ticks = arg.desired_n_ticks;
    majors = [];
    factors = range.get("factors");
    for (i = j = 0, ref = factors.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      ii = i + range.get('offset');
      if ((ii + 1) > start && (ii + 1) < end) {
        majors.push(factors[i]);
      }
    }
    return {
      "major": majors,
      "minor": []
    };
  };

  return CategoricalTicker;

})(HasProperties);

module.exports = {
  Model: CategoricalTicker
};


},{"../common/has_properties":"common/has_properties"}],"ticking/composite_ticker":[function(require,module,exports){
var AbstractTicker, CompositeTicker, _, argmin,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

AbstractTicker = require("./abstract_ticker");

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

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

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

  CompositeTicker.prototype.type = 'CompositeTicker';

  CompositeTicker.prototype.initialize = function(attrs, options) {
    var tickers;
    CompositeTicker.__super__.initialize.call(this, attrs, options);
    tickers = this.get('tickers');
    this.register_property('min_intervals', function() {
      return _.invoke(tickers, 'get_min_interval');
    }, true);
    this.add_dependencies('min_intervals', this, ['tickers']);
    this.register_property('max_intervals', function() {
      return _.invoke(tickers, 'get_max_interval');
    }, true);
    this.add_dependencies('max_intervals', this, ['tickers']);
    this.register_property('min_interval', function() {
      return _.first(this.get('min_intervals'));
    }, true);
    this.add_dependencies('min_interval', this, ['min_intervals']);
    this.register_property('max_interval', function() {
      return _.first(this.get('max_intervals'));
    }, true);
    return this.add_dependencies('max_interval', this, ['max_interval']);
  };

  CompositeTicker.prototype.get_best_ticker = function(data_low, data_high, desired_n_ticks) {
    var best_index, best_ticker, best_ticker_ndx, data_range, errors, ideal_interval, intervals, ticker_ndxs;
    data_range = data_high - data_low;
    ideal_interval = this.get_ideal_interval(data_low, data_high, desired_n_ticks);
    ticker_ndxs = [_.sortedIndex(this.get('min_intervals'), ideal_interval) - 1, _.sortedIndex(this.get('max_intervals'), ideal_interval)];
    intervals = [this.get('min_intervals')[ticker_ndxs[0]], this.get('max_intervals')[ticker_ndxs[1]]];
    errors = intervals.map(function(interval) {
      return Math.abs(desired_n_ticks - (data_range / interval));
    });
    best_index = argmin(errors);
    if (best_index === Infinity) {
      return this.get('tickers')[0];
    }
    best_ticker_ndx = ticker_ndxs[best_index];
    best_ticker = this.get('tickers')[best_ticker_ndx];
    return best_ticker;
  };

  CompositeTicker.prototype.get_interval = function(data_low, data_high, desired_n_ticks) {
    var best_ticker;
    best_ticker = this.get_best_ticker(data_low, data_high, desired_n_ticks);
    return best_ticker.get_interval(data_low, data_high, desired_n_ticks);
  };

  CompositeTicker.prototype.get_ticks_no_defaults = function(data_low, data_high, desired_n_ticks) {
    var best_ticker, ticks;
    best_ticker = this.get_best_ticker(data_low, data_high, desired_n_ticks);
    ticks = best_ticker.get_ticks_no_defaults(data_low, data_high, desired_n_ticks);
    return ticks;
  };

  return CompositeTicker;

})(AbstractTicker.Model);

module.exports = {
  Model: CompositeTicker
};


},{"./abstract_ticker":"ticking/abstract_ticker","./util":"ticking/util","underscore":"underscore"}],"ticking/datetime_tick_formatter":[function(require,module,exports){
var DatetimeTickFormatter, HasProperties, SPrintf, _, _array, _four_digit_year, _strftime, _two_digit_year, _us, logger, 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");

HasProperties = require("../common/has_properties");

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

_us = function(t) {
  return Math.round(((t / 1000) % 1) * 1000000);
};

_two_digit_year = function(t) {
  var dt, year;
  dt = new Date(t);
  year = dt.getFullYear();
  if (dt.getMonth() >= 7) {
    year += 1;
  }
  return SPrintf.sprintf("'%02d", year % 100);
};

_four_digit_year = function(t) {
  var dt, year;
  dt = new Date(t);
  year = dt.getFullYear();
  if (dt.getMonth() >= 7) {
    year += 1;
  }
  return SPrintf.sprintf("%d", year);
};

_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.prototype.format_order = ['microseconds', 'milliseconds', 'seconds', 'minsec', 'minutes', 'hourmin', 'hours', 'days', 'months', 'years'];

  DatetimeTickFormatter.prototype._formats = {
    'microseconds': ['%fus'],
    'milliseconds': ['%3Nms', '%S.%3Ns'],
    'seconds': ['%Ss'],
    'minsec': [':%M:%S'],
    'minutes': [':%M', '%Mm'],
    'hourmin': ['%H:%M'],
    'hours': ['%Hh', '%H:%M'],
    'days': ['%m/%d', '%a%d'],
    'months': ['%m/%Y', '%b%y'],
    'years': ['%Y', _two_digit_year, _four_digit_year]
  };

  DatetimeTickFormatter.prototype.strip_leading_zeros = true;

  DatetimeTickFormatter.prototype.initialize = function(attrs, options) {
    var fmt, fmt_name, fmt_string, fmt_strings, now, results, sizes, sorted;
    DatetimeTickFormatter.__super__.initialize.call(this, attrs, options);
    fmt = _.extend({}, this._formats, this.get("formats"));
    now = tz(new Date());
    this.formats = {};
    results = [];
    for (fmt_name in fmt) {
      fmt_strings = fmt[fmt_name];
      sizes = (function() {
        var j, len, results1;
        results1 = [];
        for (j = 0, len = fmt_strings.length; j < len; j++) {
          fmt_string = fmt_strings[j];
          results1.push(_strftime(now, fmt_string).length);
        }
        return results1;
      })();
      sorted = _.sortBy(_.zip(sizes, fmt_strings), function(arg) {
        var fmt, size;
        size = arg[0], fmt = arg[1];
        return size;
      });
      results.push(this.formats[fmt_name] = _.zip.apply(_, sorted));
    }
    return results;
  };

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

  DatetimeTickFormatter.prototype.format = function(ticks, num_labels, char_width, fill_ratio, ticker) {
    var error, error1, fmt, format, formats, good_formats, hybrid_handled, i, j, k, l, labels, len, len1, next_format, next_ndx, r, ref, ref1, ref2, resol, resol_ndx, s, span, ss, t, time_tuple_ndx_for_resol, tm, widths;
    if (num_labels == null) {
      num_labels = null;
    }
    if (char_width == null) {
      char_width = null;
    }
    if (fill_ratio == null) {
      fill_ratio = 0.3;
    }
    if (ticker == null) {
      ticker = null;
    }
    if (ticks.length === 0) {
      return [];
    }
    span = Math.abs(ticks[ticks.length - 1] - ticks[0]) / 1000.0;
    if (ticker) {
      r = ticker.resolution;
    } else {
      r = span / (ticks.length - 1);
    }
    resol = this._get_resolution_str(r, span);
    ref = this.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.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.formats[this.format_order[resol_ndx - 1]][1][0];
            s = _strftime(t, next_format);
            break;
          } else {
            hybrid_handled = true;
          }
        }
        next_format = this.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;
  };

  DatetimeTickFormatter.prototype.defaults = function() {
    return _.extend({}, DatetimeTickFormatter.__super__.defaults.call(this), {
      formats: {}
    });
  };

  return DatetimeTickFormatter;

})(HasProperties);

module.exports = {
  Model: DatetimeTickFormatter
};


},{"../common/has_properties":"common/has_properties","../common/logging":"common/logging","sprintf":"sprintf","timezone":"timezone/index","underscore":"underscore"}],"ticking/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.prototype.defaults = function() {
    return _.extend({}, DatetimeTicker.__super__.defaults.call(this), {
      num_minor_ticks: 0,
      tickers: [
        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":"ticking/adaptive_ticker","./composite_ticker":"ticking/composite_ticker","./days_ticker":"ticking/days_ticker","./months_ticker":"ticking/months_ticker","./util":"ticking/util","./years_ticker":"ticking/years_ticker","underscore":"underscore"}],"ticking/days_ticker":[function(require,module,exports){
var DaysTicker, ONE_DAY, SingleIntervalTicker, _, copy_date, date_range_by_month, last_month_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");

SingleIntervalTicker = require("./single_interval_ticker");

util = require("./util");

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.prototype.initialize = function(attrs, options) {
    var days, interval;
    attrs.num_minor_ticks = 0;
    DaysTicker.__super__.initialize.call(this, attrs, options);
    days = this.get('days');
    interval = days.length > 1 ? (days[1] - days[0]) * ONE_DAY : 31 * ONE_DAY;
    return this.set('interval', interval);
  };

  DaysTicker.prototype.get_ticks_no_defaults = function(data_low, data_high, desired_n_ticks) {
    var all_ticks, date, day_dates, days, days_of_month, interval, month_dates, ticks_in_range;
    month_dates = date_range_by_month(data_low, data_high);
    days = this.get('days');
    days_of_month = (function(_this) {
      return function(month_date, interval) {
        var dates, day, day_date, future_date, i, len;
        dates = [];
        for (i = 0, len = days.length; i < len; i++) {
          day = days[i];
          day_date = copy_date(month_date);
          day_date.setUTCDate(day);
          future_date = new Date(day_date.getTime() + (interval / 2));
          if (future_date.getUTCMonth() === month_date.getUTCMonth()) {
            dates.push(day_date);
          }
        }
        return dates;
      };
    })(this);
    interval = this.get('interval');
    day_dates = _.flatten((function() {
      var i, len, results;
      results = [];
      for (i = 0, len = month_dates.length; i < len; i++) {
        date = month_dates[i];
        results.push(days_of_month(date, interval));
      }
      return results;
    })());
    all_ticks = _.invoke(day_dates, 'getTime');
    ticks_in_range = _.filter(all_ticks, (function(tick) {
      return (data_low <= tick && tick <= data_high);
    }));
    return {
      "major": ticks_in_range,
      "minor": []
    };
  };

  DaysTicker.prototype.defaults = function() {
    return _.extend({}, DaysTicker.__super__.defaults.call(this), {
      toString_properties: ['days']
    });
  };

  return DaysTicker;

})(SingleIntervalTicker.Model);

module.exports = {
  Model: DaysTicker
};


},{"./single_interval_ticker":"ticking/single_interval_ticker","./util":"ticking/util","underscore":"underscore"}],"ticking/fixed_ticker":[function(require,module,exports){
var AbstractTicker, FixedTicker, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

AbstractTicker = require("./abstract_ticker");

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

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

  FixedTicker.prototype.type = 'FixedTicker';

  FixedTicker.prototype.get_ticks_no_defaults = function(data_low, data_high, desired_n_ticks) {
    return {
      major: this.get('ticks'),
      minor: []
    };
  };

  FixedTicker.prototype.defaults = function() {
    return _.extend({}, FixedTicker.__super__.defaults.call(this), {
      ticks: []
    });
  };

  return FixedTicker;

})(AbstractTicker.Model);

module.exports = {
  Model: FixedTicker
};


},{"./abstract_ticker":"ticking/abstract_ticker","underscore":"underscore"}],"ticking/log_tick_formatter":[function(require,module,exports){
var BasicTickFormatter, HasProperties, LogTickFormatter, _, 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");

HasProperties = require("../common/has_properties");

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

BasicTickFormatter = require("./basic_tick_formatter");

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

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

  LogTickFormatter.prototype.type = 'LogTickFormatter';

  LogTickFormatter.prototype.initialize = function(attrs, options) {
    LogTickFormatter.__super__.initialize.call(this, attrs, options);
    this.basic_formatter = new BasicTickFormatter.Model();
    if (this.get('ticker') == null) {
      return logger.warn("LogTickFormatter not configured with a ticker, using default base of 10 (labels will be incorrect if ticker base is not 10)");
    }
  };

  LogTickFormatter.prototype.format = function(ticks) {
    var base, i, j, labels, ref, small_interval;
    if (ticks.length === 0) {
      return [];
    }
    if (this.get('ticker') != null) {
      base = this.get('ticker').get('base');
    } else {
      base = 10;
    }
    small_interval = false;
    labels = new Array(ticks.length);
    for (i = j = 0, ref = ticks.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      labels[i] = base + "^" + (Math.round(Math.log(ticks[i]) / Math.log(base)));
      if ((i > 0) && (labels[i] === labels[i - 1])) {
        small_interval = true;
        break;
      }
    }
    if (small_interval) {
      labels = this.basic_formatter.format(ticks);
    }
    return labels;
  };

  return LogTickFormatter;

})(HasProperties);

module.exports = {
  Model: LogTickFormatter
};


},{"../common/has_properties":"common/has_properties","../common/logging":"common/logging","./basic_tick_formatter":"ticking/basic_tick_formatter","underscore":"underscore"}],"ticking/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.prototype.get_ticks_no_defaults = function(data_low, data_high, desired_n_ticks) {
    var base, end_factor, endlog, factor, factors, i, interval, j, k, l, len, len1, len2, len3, len4, len5, log_high, log_interval, log_low, m, minor_interval, minor_offsets, minor_ticks, n, num_minor_ticks, o, ref, start_factor, startlog, tick, ticks, x;
    num_minor_ticks = this.get('num_minor_ticks');
    minor_ticks = [];
    if (data_low <= 0) {
      data_low = 1;
    }
    if (data_low > data_high) {
      ref = [data_high, data_low], data_low = ref[0], data_high = ref[1];
    }
    base = this.get('base');
    log_low = Math.log(data_low) / Math.log(base);
    log_high = Math.log(data_high) / Math.log(base);
    log_interval = log_high - log_low;
    if (log_interval < 2) {
      interval = this.get_interval(data_low, data_high, desired_n_ticks);
      start_factor = Math.floor(data_low / interval);
      end_factor = Math.ceil(data_high / interval);
      if (_.isNaN(start_factor) || _.isNaN(end_factor)) {
        factors = [];
      } else {
        factors = _.range(start_factor, end_factor + 1);
      }
      ticks = (function() {
        var j, len, results;
        results = [];
        for (j = 0, len = factors.length; j < len; j++) {
          factor = factors[j];
          if (factor !== 0) {
            results.push(factor * interval);
          }
        }
        return results;
      })();
      if (num_minor_ticks > 1) {
        minor_interval = interval / num_minor_ticks;
        minor_offsets = (function() {
          var j, ref1, results;
          results = [];
          for (i = j = 1, ref1 = num_minor_ticks; 1 <= ref1 ? j <= ref1 : j >= ref1; i = 1 <= ref1 ? ++j : --j) {
            results.push(i * minor_interval);
          }
          return results;
        })();
        for (j = 0, len = minor_offsets.length; j < len; j++) {
          x = minor_offsets[j];
          minor_ticks.push(ticks[0] - x);
        }
        for (k = 0, len1 = ticks.length; k < len1; k++) {
          tick = ticks[k];
          for (l = 0, len2 = minor_offsets.length; l < len2; l++) {
            x = minor_offsets[l];
            minor_ticks.push(tick + x);
          }
        }
      }
    } else {
      startlog = Math.ceil(log_low);
      endlog = Math.floor(log_high);
      interval = Math.ceil((endlog - startlog) / 9.0);
      ticks = range(startlog, endlog, interval);
      if ((endlog - startlog) % interval === 0) {
        ticks = ticks.concat([endlog]);
      }
      ticks = ticks.map(function(i) {
        return Math.pow(base, i);
      });
      if (num_minor_ticks > 1) {
        minor_interval = Math.pow(base, interval) / num_minor_ticks;
        minor_offsets = (function() {
          var m, ref1, results;
          results = [];
          for (i = m = 1, ref1 = num_minor_ticks; 1 <= ref1 ? m <= ref1 : m >= ref1; i = 1 <= ref1 ? ++m : --m) {
            results.push(i * minor_interval);
          }
          return results;
        })();
        for (m = 0, len3 = minor_offsets.length; m < len3; m++) {
          x = minor_offsets[m];
          minor_ticks.push(ticks[0] / x);
        }
        for (n = 0, len4 = ticks.length; n < len4; n++) {
          tick = ticks[n];
          for (o = 0, len5 = minor_offsets.length; o < len5; o++) {
            x = minor_offsets[o];
            minor_ticks.push(tick * x);
          }
        }
      }
    }
    return {
      "major": ticks,
      "minor": minor_ticks
    };
  };

  LogTicker.prototype.defaults = function() {
    return _.extend({}, LogTicker.__super__.defaults.call(this), {
      mantissas: [1, 5]
    });
  };

  return LogTicker;

})(AdaptiveTicker.Model);

module.exports = {
  Model: LogTicker
};


},{"./adaptive_ticker":"ticking/adaptive_ticker","underscore":"underscore"}],"ticking/months_ticker":[function(require,module,exports){
var MonthsTicker, ONE_MONTH, SingleIntervalTicker, _, copy_date, date_range_by_year, 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");

SingleIntervalTicker = require("./single_interval_ticker");

util = require("./util");

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.prototype.initialize = function(attrs, options) {
    var interval, months;
    MonthsTicker.__super__.initialize.call(this, attrs, options);
    months = this.get('months');
    interval = months.length > 1 ? (months[1] - months[0]) * ONE_MONTH : 12 * ONE_MONTH;
    return this.set('interval', interval);
  };

  MonthsTicker.prototype.get_ticks_no_defaults = function(data_low, data_high, desired_n_ticks) {
    var all_ticks, date, month_dates, months, months_of_year, ticks_in_range, year_dates;
    year_dates = date_range_by_year(data_low, data_high);
    months = this.get('months');
    months_of_year = function(year_date) {
      return months.map(function(month) {
        var month_date;
        month_date = copy_date(year_date);
        month_date.setUTCMonth(month);
        return month_date;
      });
    };
    month_dates = _.flatten((function() {
      var i, len, results;
      results = [];
      for (i = 0, len = year_dates.length; i < len; i++) {
        date = year_dates[i];
        results.push(months_of_year(date));
      }
      return results;
    })());
    all_ticks = _.invoke(month_dates, 'getTime');
    ticks_in_range = _.filter(all_ticks, (function(tick) {
      return (data_low <= tick && tick <= data_high);
    }));
    return {
      "major": ticks_in_range,
      "minor": []
    };
  };

  MonthsTicker.prototype.defaults = function() {
    return _.extend({}, MonthsTicker.__super__.defaults.call(this), {
      toString_properties: ['months']
    });
  };

  return MonthsTicker;

})(SingleIntervalTicker.Model);

module.exports = {
  Model: MonthsTicker
};


},{"./single_interval_ticker":"ticking/single_interval_ticker","./util":"ticking/util","underscore":"underscore"}],"ticking/numeral_tick_formatter":[function(require,module,exports){
var HasProperties, Numeral, NumeralTickFormatter, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

Numeral = require("numeral");

HasProperties = require("../common/has_properties");

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

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

  NumeralTickFormatter.prototype.type = 'NumeralTickFormatter';

  NumeralTickFormatter.prototype.format = function(ticks) {
    var format, labels, language, rounding, tick;
    format = this.get("format");
    language = this.get("language");
    rounding = (function() {
      switch (this.get("rounding")) {
        case "round":
        case "nearest":
          return Math.round;
        case "floor":
        case "rounddown":
          return Math.floor;
        case "ceil":
        case "roundup":
          return Math.ceil;
      }
    }).call(this);
    labels = (function() {
      var i, len, results;
      results = [];
      for (i = 0, len = ticks.length; i < len; i++) {
        tick = ticks[i];
        results.push(Numeral.format(tick, format, language, rounding));
      }
      return results;
    })();
    return labels;
  };

  NumeralTickFormatter.prototype.defaults = function() {
    return _.extend({}, NumeralTickFormatter.__super__.defaults.call(this), {
      format: '0,0',
      language: 'en',
      rounding: 'round'
    });
  };

  return NumeralTickFormatter;

})(HasProperties);

module.exports = {
  Model: NumeralTickFormatter
};


},{"../common/has_properties":"common/has_properties","numeral":"numeral","underscore":"underscore"}],"ticking/printf_tick_formatter":[function(require,module,exports){
var HasProperties, PrintfTickFormatter, SPrintf, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

SPrintf = require("sprintf");

HasProperties = require("../common/has_properties");

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

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

  PrintfTickFormatter.prototype.type = 'PrintfTickFormatter';

  PrintfTickFormatter.prototype.format = function(ticks) {
    var format, labels, tick;
    format = this.get("format");
    labels = (function() {
      var i, len, results;
      results = [];
      for (i = 0, len = ticks.length; i < len; i++) {
        tick = ticks[i];
        results.push(SPrintf.sprintf(format, tick));
      }
      return results;
    })();
    return labels;
  };

  PrintfTickFormatter.prototype.defaults = function() {
    return _.extend({}, PrintfTickFormatter.__super__.defaults.call(this), {
      format: '%s'
    });
  };

  return PrintfTickFormatter;

})(HasProperties);

module.exports = {
  Model: PrintfTickFormatter
};


},{"../common/has_properties":"common/has_properties","sprintf":"sprintf","underscore":"underscore"}],"ticking/single_interval_ticker":[function(require,module,exports){
var AbstractTicker, SingleIntervalTicker, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

AbstractTicker = require("./abstract_ticker");

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

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

  SingleIntervalTicker.prototype.type = 'SingleIntervalTicker';

  SingleIntervalTicker.prototype.initialize = function(attrs, options) {
    SingleIntervalTicker.__super__.initialize.call(this, attrs, options);
    this.register_property('min_interval', function() {
      return this.get('interval');
    }, true);
    this.add_dependencies('min_interval', this, ['interval']);
    this.register_property('max_interval', function() {
      return this.get('interval');
    }, true);
    return this.add_dependencies('max_interval', this, ['interval']);
  };

  SingleIntervalTicker.prototype.get_interval = function(data_low, data_high, n_desired_ticks) {
    return this.get('interval');
  };

  SingleIntervalTicker.prototype.defaults = function() {
    return _.extend({}, SingleIntervalTicker.__super__.defaults.call(this), {
      toString_properties: ['interval']
    });
  };

  return SingleIntervalTicker;

})(AbstractTicker.Model);

module.exports = {
  Model: SingleIntervalTicker
};


},{"./abstract_ticker":"ticking/abstract_ticker","underscore":"underscore"}],"ticking/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"}],"ticking/years_ticker":[function(require,module,exports){
var BasicTicker, ONE_YEAR, SingleIntervalTicker, YearsTicker, _, last_year_no_later_than, util,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

BasicTicker = require("./basic_ticker");

SingleIntervalTicker = require("./single_interval_ticker");

util = require("./util");

last_year_no_later_than = util.last_year_no_later_than;

ONE_YEAR = util.ONE_YEAR;

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

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

  YearsTicker.prototype.type = 'YearsTicker';

  YearsTicker.prototype.initialize = function(attrs, options) {
    YearsTicker.__super__.initialize.call(this, attrs, options);
    this.set('interval', ONE_YEAR);
    return this.basic_ticker = new BasicTicker.Model({
      num_minor_ticks: 0
    });
  };

  YearsTicker.prototype.get_ticks_no_defaults = function(data_low, data_high, desired_n_ticks) {
    var all_ticks, end_year, start_year, ticks_in_range, year, years;
    start_year = last_year_no_later_than(new Date(data_low)).getUTCFullYear();
    end_year = last_year_no_later_than(new Date(data_high)).getUTCFullYear();
    years = this.basic_ticker.get_ticks_no_defaults(start_year, end_year, desired_n_ticks).major;
    all_ticks = (function() {
      var i, len, results;
      results = [];
      for (i = 0, len = years.length; i < len; i++) {
        year = years[i];
        results.push(Date.UTC(year, 0, 1));
      }
      return results;
    })();
    ticks_in_range = _.filter(all_ticks, (function(tick) {
      return (data_low <= tick && tick <= data_high);
    }));
    return {
      major: ticks_in_range,
      minor: []
    };
  };

  YearsTicker.prototype.defaults = function() {
    return _.extend({}, YearsTicker.__super__.defaults.call(this), {
      toString_properties: ['years']
    });
  };

  return YearsTicker;

})(SingleIntervalTicker.Model);

module.exports = {
  Model: YearsTicker
};


},{"./basic_ticker":"ticking/basic_ticker","./single_interval_ticker":"ticking/single_interval_ticker","./util":"ticking/util","underscore":"underscore"}],"tool/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":"tool/button_tool"}],"tool/actions/help_tool":[function(require,module,exports){
var ActionTool, HelpTool, HelpToolView, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

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

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

  HelpToolView.prototype["do"] = function() {
    return window.open(this.mget('redirect'));
  };

  return HelpToolView;

})(ActionTool.View);

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

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

  HelpTool.prototype.default_view = HelpToolView;

  HelpTool.prototype.type = "HelpTool";

  HelpTool.prototype.tool_name = "Help";

  HelpTool.prototype.icon = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA2hpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYxIDY0LjE0MDk0OSwgMjAxMC8xMi8wNy0xMDo1NzowMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDo3NzIwRUFGMDYyMjE2ODExOTdBNUNBNjVEQTY5OTRDRSIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDozMjFERDhDRjIwQjIxMUU0ODREQUYzNzM5QTM2MjBCRSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDozMjFERDhDRTIwQjIxMUU0ODREQUYzNzM5QTM2MjBCRSIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ1M1LjEgTWFjaW50b3NoIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6OTdFQUZCRjQ4NjIxNjgxMTk3QTVDQTY1REE2OTk0Q0UiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6NzcyMEVBRjA2MjIxNjgxMTk3QTVDQTY1REE2OTk0Q0UiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz6QBYrgAAABb0lEQVR42ozTwUeEQRjH8W3bKEs6JkpESqfVpS4RHaJL2b2sLepUh3To0KFVIjp0iegQUdG21WmVvUWsKBGRlIiU7Q+IVaT0ffi9eY33peFj7cw8zzvzzEzV7v5hxGltGEUvutR3hwvs4ck/OeoET6KACrJolaz6Cprz12L6rcEOajGEFyfxtRxhDX0Yx5e3ggV8IqlgW/4J3vCKddRrLKm5894KOjGCHiVrwDZ+sKKvpRQ0pzkzuETeEqSxpT1aa8ezCmbyuEW3b0sVxaQtQT+mfINXGPT9T+n3xqnLKTYsQQseI8FtWnstYdEZs9o0eqdQZxUNSWD9YwHj36i2UyijOWQFVvmPkOR2P8qW4AwDIQma0BEyZjGlqCo9gXjA1+0ePAQExxWTtwT3KOqG/bfZ3GOL9W7ikrIe6FSsvQdswcZymrvsf0xWpIzqYauZRcIXmFBfUUea8Qobc5a2qQtiz3nVec7nGHaf868AAwDKW1RIPmvhEQAAAABJRU5ErkJggg==";

  HelpTool.prototype.initialize = function(attrs, options) {
    HelpTool.__super__.initialize.call(this, attrs, options);
    return this.register_property('tooltip', function() {
      return this.get('help_tooltip');
    });
  };

  HelpTool.prototype.defaults = function() {
    return _.extend({}, HelpTool.__super__.defaults.call(this), {
      help_tooltip: 'Click the question mark to learn more about Bokeh plot tools.',
      redirect: 'http://bokeh.pydata.org/en/latest/docs/user_guide/tools.html'
    });
  };

  return HelpTool;

})(ActionTool.Model);

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


},{"./action_tool":"tool/actions/action_tool","underscore":"underscore"}],"tool/actions/preview_save_tool":[function(require,module,exports){
var $, $1, ActionTool, PreviewSaveTool, PreviewSaveToolView, _, preview_save_tool_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");

$ = require("jquery");

$1 = require("bootstrap/modal");

ActionTool = require("./action_tool");

preview_save_tool_template = require("./preview_save_tool_template");

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

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

  PreviewSaveToolView.prototype.className = "bk-bs-modal";

  PreviewSaveToolView.prototype.template = preview_save_tool_template;

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

  PreviewSaveToolView.prototype.render = function() {
    this.$el.empty();
    this.$el.html(this.template());
    this.$el.attr("tabindex", "-1");
    this.$el.on('hidden', (function(_this) {
      return function() {
        return _this.$el.modal('hide');
      };
    })(this));
    return this.$el.modal({
      show: false
    });
  };

  PreviewSaveToolView.prototype["do"] = function() {
    var canvas;
    canvas = this.plot_view.canvas_view.canvas[0];
    this.$('.bk-bs-modal-body img').attr("src", canvas.toDataURL());
    return this.$el.modal('show');
  };

  return PreviewSaveToolView;

})(ActionTool.View);

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

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

  PreviewSaveTool.prototype.default_view = PreviewSaveToolView;

  PreviewSaveTool.prototype.type = "PreviewSaveTool";

  PreviewSaveTool.prototype.tool_name = "Preview/Save";

  PreviewSaveTool.prototype.icon = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyRpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYxIDY0LjE0MDk0OSwgMjAxMC8xMi8wNy0xMDo1NzowMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNS4xIE1hY2ludG9zaCIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDozMjFERDhENjIwQjIxMUU0ODREQUYzNzM5QTM2MjBCRSIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDozMjFERDhENzIwQjIxMUU0ODREQUYzNzM5QTM2MjBCRSI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOjMyMUREOEQ0MjBCMjExRTQ4NERBRjM3MzlBMzYyMEJFIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOjMyMUREOEQ1MjBCMjExRTQ4NERBRjM3MzlBMzYyMEJFIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+h5hT8AAAAKBJREFUeNpiWbhs5QcGBgZ+hgECTAwDDGAO+AjEjGj4Lw5xUrAAkl3ocr8IhQAzjT3PRu0o+I+EHw65NDDqgJHrABYC8t9JMIuRmiHACS2IKC0LOKH0X1JDAOTzs0BsBs3XlIKz5KSBRCA+RQXLjwNxNDlp4BoQm9Mo7fGPZsNRB4w6YNQBI94BfwfaAV9G08CoA9DbA/xUavkMvRAACDAAaPgYViexODkAAAAASUVORK5CYII=";

  return PreviewSaveTool;

})(ActionTool.Model);

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


},{"./action_tool":"tool/actions/action_tool","./preview_save_tool_template":"tool/actions/preview_save_tool_template","bootstrap/modal":"bootstrap/modal","jquery":"jquery","underscore":"underscore"}],"tool/actions/preview_save_tool_template":[function(require,module,exports){
module.exports = function(__obj) {
  if (!__obj) __obj = {};
  var __out = [], __capture = function(callback) {
    var out = __out, result;
    __out = [];
    callback.call(this);
    result = __out.join('');
    __out = out;
    return __safe(result);
  }, __sanitize = function(value) {
    if (value && value.ecoSafe) {
      return value;
    } else if (typeof value !== 'undefined' && value != null) {
      return __escape(value);
    } else {
      return '';
    }
  }, __safe, __objSafe = __obj.safe, __escape = __obj.escape;
  __safe = __obj.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;
    }
  };
  if (!__escape) {
    __escape = __obj.escape = function(value) {
      return ('' + value)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;');
    };
  }
  (function() {
    (function() {
      __out.push('<div class="bk-bs-modal-dialog">\n  <div class="bk-bs-modal-content">\n    <div class="bk-bs-modal-header">\n      <button type="button" class="bk-bs-close" data-bk-bs-dismiss="modal">&times;</button>\n      <h4 class="bk-bs-modal-title">Image Preview (right click -> \'Save As\' to save PNG)</h4>\n    </div>\n    <div class="bk-bs-modal-body">\n      <img style="max-height: 300px; max-width: 400px">\n    </div>\n    <div class="bk-bs-modal-footer">\n      <button type="button" class="bk-bs-btn bk-bs-btn-primary" data-bk-bs-dismiss="modal">Close</button>\n    </div>\n  </div>\n</div>');
    
    }).call(this);
    
  }).call(__obj);
  __obj.safe = __objSafe, __obj.escape = __escape;
  return __out.join('');
}
},{}],"tool/actions/reset_tool":[function(require,module,exports){
var ActionTool, ResetTool, ResetToolView,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

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

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

  ResetToolView.prototype["do"] = function() {
    return this.plot_view.update_range();
  };

  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 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAgCAYAAABgrToAAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyRpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYxIDY0LjE0MDk0OSwgMjAxMC8xMi8wNy0xMDo1NzowMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNS4xIE1hY2ludG9zaCIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDpCRTI5MDhFMDIwQjUxMUU0ODREQUYzNzM5QTM2MjBCRSIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDoyOUMzNDE3NDIwQkIxMUU0ODREQUYzNzM5QTM2MjBCRSI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOkJFMjkwOERFMjBCNTExRTQ4NERBRjM3MzlBMzYyMEJFIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOkJFMjkwOERGMjBCNTExRTQ4NERBRjM3MzlBMzYyMEJFIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+kFHGtQAAAm1JREFUeNrMmE9ExFEQx3+7ZYmlLrEsUUTHaEV0iESJVqduXaJr1xKlFB1bdYqoQ9GlFBFdikgpIhLd0rLqUsQqrW2G7+YZr+2993vaHT6H3583M795897M+0U2t3cCR6kh+kA3rtvx7IYoEGfEMSi4GIk4OJgg5ogRot5wzBvBhmaJnI2xqMW7dcQC8UCMWzgX4N1xjF2ALq8OctROiGkiHrhLHDpOoNOLg5xXF0Sn5lmWWCUGiBRRC1K4t4p3pLCuKyVnnXMwAUVJcT+HfFo3SH5ePGPI24TmA1Pl8rJcBGPEvsa5I6KVWDNcmQW824qxqiRhI+bi4IxmWjOYuneH/HvH2Ixmumd8bjNhhad8lxgSzrfp8jUa/L/wlI8KZ3h1T4bdB30Kb9zz4t6YbgurlIMBdoBHUQiGTBx8JYoKPqVe0ftFNInnW8J20SSCjRWM8k8E1S+TNfbZYyQ59yJEg0kjw1QyB42k1iI6ReXLfEWSK8iHJnJVsYqN8jtammuFc/FOr3juU7Ia+39uM7fiuq8aVrEqp+J6BPWzahw8IPLKdTPKUNU4yJ3Fhqb1inu0y7qeRNVYsWkWFkXPl0QZ8iVbohFmW0s2DmY1jSUX8mUPzi1rmoLML2eXsvsgR/FO3JtAix53nNZ96FDlDrasW35eKGniRRPJeywck9VdOjTdayL3Ahv5MC1/xy+Hp1Iq7BGHMHatjOEqMUgMlxmbVsaEOpMk4GSnp0VyCedyLtuMTlhRD1ZaPoRjeejoMf1HE7VUPkW04Jz7Ztm9rGHslM1Hhjl2xlCn+4muQP/77RyHdf799uli5FuAAQC+l5Sj5nEBdwAAAABJRU5ErkJggg==";

  return ResetTool;

})(ActionTool.Model);

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


},{"./action_tool":"tool/actions/action_tool"}],"tool/button_tool":[function(require,module,exports){
var Backbone, ButtonTool, ButtonToolButtonView, ButtonToolView, Tool, _, button_tool_template,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Backbone = require("backbone");

Tool = require("./tool");

button_tool_template = require("./button_tool_template");

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() {
    if ('ontouchstart' in document) {
      return {
        'touchstart .bk-toolbar-button': '_clicked'
      };
    } else {
      return {
        'click .bk-toolbar-button': '_clicked'
      };
    }
  };

  ButtonToolButtonView.prototype.initialize = function(options) {
    ButtonToolButtonView.__super__.initialize.call(this, options);
    this.$el.html(this.template(this.model.attrs_and_props()));
    this.listenTo(this.model, 'change:active', this.render);
    return this.render();
  };

  ButtonToolButtonView.prototype.render = function() {
    if (this.model.get('active')) {
      this.$el.children('button').addClass('active');
    } else {
      this.$el.children('button').removeClass('active');
    }
    return this;
  };

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

  return ButtonToolButtonView;

})(Backbone.View);

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

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

  return ButtonToolView;

})(Tool.View);

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

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

  ButtonTool.prototype.initialize = function(attrs, options) {
    ButtonTool.__super__.initialize.call(this, attrs, options);
    return this.register_property('tooltip', function() {
      return this.get('tool_name');
    });
  };

  ButtonTool.prototype.nonserializable_attribute_names = function() {
    return ButtonTool.__super__.nonserializable_attribute_names.call(this).concat(['icon']);
  };

  ButtonTool.prototype.defaults = function() {
    return _.extend({}, ButtonTool.__super__.defaults.call(this), {
      active: false,
      tool_name: this.tool_name,
      icon: this.icon
    });
  };

  return ButtonTool;

})(Tool.Model);

module.exports = {
  Model: ButtonTool,
  View: ButtonToolView,
  ButtonView: ButtonToolButtonView
};


},{"./button_tool_template":"tool/button_tool_template","./tool":"tool/tool","backbone":"backbone","underscore":"underscore"}],"tool/button_tool_template":[function(require,module,exports){
module.exports = function(__obj) {
  if (!__obj) __obj = {};
  var __out = [], __capture = function(callback) {
    var out = __out, result;
    __out = [];
    callback.call(this);
    result = __out.join('');
    __out = out;
    return __safe(result);
  }, __sanitize = function(value) {
    if (value && value.ecoSafe) {
      return value;
    } else if (typeof value !== 'undefined' && value != null) {
      return __escape(value);
    } else {
      return '';
    }
  }, __safe, __objSafe = __obj.safe, __escape = __obj.escape;
  __safe = __obj.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;
    }
  };
  if (!__escape) {
    __escape = __obj.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  <img class=\'bk-btn-icon\' src=');
    
      __out.push(__sanitize(this.icon));
    
      __out.push(' />\n  <span class=\'tip\'>');
    
      __out.push(__sanitize(this.tooltip));
    
      __out.push('</span>\n</button>\n');
    
    }).call(this);
    
  }).call(__obj);
  __obj.safe = __objSafe, __obj.escape = __escape;
  return __out.join('');
}
},{}],"tool/gestures/box_select_tool":[function(require,module,exports){
var BoxSelectTool, BoxSelectToolView, BoxSelection, SelectTool, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

BoxSelection = require("../../renderer/overlay/box_selection");

SelectTool = require("./select_tool");

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

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

  BoxSelectToolView.prototype._pan_start = function(e) {
    var canvas;
    canvas = this.plot_view.canvas;
    this._baseboint = [canvas.sx_to_vx(e.bokeh.sx), canvas.sy_to_vy(e.bokeh.sy)];
    return null;
  };

  BoxSelectToolView.prototype._pan = function(e) {
    var append, canvas, curpoint, dims, frame, ref, ref1, vxlim, vylim;
    canvas = this.plot_view.canvas;
    curpoint = [canvas.sx_to_vx(e.bokeh.sx), canvas.sy_to_vy(e.bokeh.sy)];
    frame = this.plot_model.get('frame');
    dims = this.mget('dimensions');
    ref = this.model._get_dim_limits(this._baseboint, curpoint, frame, dims), vxlim = ref[0], vylim = ref[1];
    this.mget('overlay').set('data', {
      vxlim: vxlim,
      vylim: vylim
    });
    if (this.mget('select_every_mousemove')) {
      append = (ref1 = e.srcEvent.shiftKey) != null ? ref1 : false;
      this._select(vxlim, vylim, false, append);
    }
    return null;
  };

  BoxSelectToolView.prototype._pan_end = function(e) {
    var append, canvas, curpoint, dims, frame, ref, ref1, vxlim, vylim;
    canvas = this.plot_view.canvas;
    curpoint = [canvas.sx_to_vx(e.bokeh.sx), canvas.sy_to_vy(e.bokeh.sy)];
    frame = this.plot_model.get('frame');
    dims = this.mget('dimensions');
    ref = this.model._get_dim_limits(this._baseboint, curpoint, frame, dims), vxlim = ref[0], vylim = ref[1];
    append = (ref1 = e.srcEvent.shiftKey) != null ? ref1 : false;
    this._select(vxlim, vylim, true, append);
    this.mget('overlay').set('data', {});
    this._baseboint = null;
    return null;
  };

  BoxSelectToolView.prototype._select = function(arg, arg1, final, append) {
    var ds, geometry, i, len, r, ref, sm, vx0, vx1, vy0, vy1;
    vx0 = arg[0], vx1 = arg[1];
    vy0 = arg1[0], vy1 = arg1[1];
    if (append == null) {
      append = false;
    }
    geometry = {
      type: 'rect',
      vx0: vx0,
      vx1: vx1,
      vy0: vy0,
      vy1: vy1
    };
    ref = this.mget('renderers');
    for (i = 0, len = ref.length; i < len; i++) {
      r = ref[i];
      ds = r.get('data_source');
      sm = ds.get('selection_manager');
      sm.select(this, this.plot_view.renderers[r.id], geometry, final, append);
    }
    if (this.mget('callback') != null) {
      this._emit_callback(geometry);
    }
    this._save_geometry(geometry, final, append);
    return null;
  };

  BoxSelectToolView.prototype._emit_callback = function(geometry) {
    var canvas, frame, r, xmapper, ymapper;
    r = this.mget('renderers')[0];
    canvas = this.plot_model.get('canvas');
    frame = this.plot_model.get('frame');
    geometry['sx0'] = canvas.vx_to_sx(geometry.vx0);
    geometry['sx1'] = canvas.vx_to_sx(geometry.vx1);
    geometry['sy0'] = canvas.vy_to_sy(geometry.vy0);
    geometry['sy1'] = canvas.vy_to_sy(geometry.vy1);
    xmapper = frame.get('x_mappers')[r.get('x_range_name')];
    ymapper = frame.get('y_mappers')[r.get('y_range_name')];
    geometry['x0'] = xmapper.map_from_target(geometry.vx0);
    geometry['x1'] = xmapper.map_from_target(geometry.vx1);
    geometry['y0'] = ymapper.map_from_target(geometry.vy0);
    geometry['y1'] = ymapper.map_from_target(geometry.vy1);
    this.mget('callback').execute(this.model, {
      geometry: geometry
    });
  };

  return BoxSelectToolView;

})(SelectTool.View);

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 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACQAAAAgCAYAAAB6kdqOAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyRpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYxIDY0LjE0MDk0OSwgMjAxMC8xMi8wNy0xMDo1NzowMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNS4xIE1hY2ludG9zaCIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDpBODVDNDBCRjIwQjMxMUU0ODREQUYzNzM5QTM2MjBCRSIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDpBODVDNDBDMDIwQjMxMUU0ODREQUYzNzM5QTM2MjBCRSI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOkE4NUM0MEJEMjBCMzExRTQ4NERBRjM3MzlBMzYyMEJFIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOkE4NUM0MEJFMjBCMzExRTQ4NERBRjM3MzlBMzYyMEJFIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+hdQ7dQAAAJdJREFUeNpiXLhs5X8GBPgIxAJQNjZxfiD+wIAKGCkUZ0SWZGIYZIAF3YVoPkEHH6kojhUMyhD6jydEaAlgaWnwh9BAgf9DKpfxDxYHjeay0Vw2bHMZw2guG81lwyXKRnMZWlt98JdDTFAX/x9NQwPkIH6kGMAVEyjyo7lstC4jouc69Moh9L42rlyBTZyYXDS00xBAgAEAqsguPe03+cYAAAAASUVORK5CYII=";

  BoxSelectTool.prototype.event_type = "pan";

  BoxSelectTool.prototype.default_order = 30;

  BoxSelectTool.prototype.initialize = function(attrs, options) {
    var plot_renderers;
    BoxSelectTool.__super__.initialize.call(this, attrs, options);
    this.register_property('tooltip', function() {
      return this._get_dim_tooltip(this.get("tool_name"), this._check_dims(this.get('dimensions'), "box select tool"));
    }, false);
    this.add_dependencies('tooltip', this, ['dimensions']);
    this.set('overlay', new BoxSelection.Model);
    plot_renderers = this.get('plot').get('renderers');
    plot_renderers.push(this.get('overlay'));
    return this.get('plot').set('renderers', plot_renderers);
  };

  BoxSelectTool.prototype.defaults = function() {
    return _.extend({}, BoxSelectTool.__super__.defaults.call(this), {
      dimensions: ["width", "height"],
      select_every_mousemove: false
    });
  };

  return BoxSelectTool;

})(SelectTool.Model);

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


},{"../../renderer/overlay/box_selection":"renderer/overlay/box_selection","./select_tool":"tool/gestures/select_tool","underscore":"underscore"}],"tool/gestures/box_zoom_tool":[function(require,module,exports){
var BoxSelection, BoxZoomTool, BoxZoomToolView, GestureTool, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

BoxSelection = require("../../renderer/overlay/box_selection");

GestureTool = require("./gesture_tool");

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

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

  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, vxlim, vylim;
    canvas = this.plot_view.canvas;
    curpoint = [canvas.sx_to_vx(e.bokeh.sx), canvas.sy_to_vy(e.bokeh.sy)];
    frame = this.plot_model.get('frame');
    dims = this.mget('dimensions');
    ref = this.model._get_dim_limits(this._baseboint, curpoint, frame, dims), vxlim = ref[0], vylim = ref[1];
    this.mget('overlay').set('data', {
      vxlim: vxlim,
      vylim: vylim
    });
    return null;
  };

  BoxZoomToolView.prototype._pan_end = function(e) {
    var canvas, curpoint, dims, frame, ref, vxlim, vylim;
    canvas = this.plot_view.canvas;
    curpoint = [canvas.sx_to_vx(e.bokeh.sx), canvas.sy_to_vy(e.bokeh.sy)];
    frame = this.plot_model.get('frame');
    dims = this.mget('dimensions');
    ref = this.model._get_dim_limits(this._baseboint, curpoint, frame, dims), vxlim = ref[0], vylim = ref[1];
    this._update(vxlim, vylim);
    this.mget('overlay').set('data', {});
    this._baseboint = null;
    return null;
  };

  BoxZoomToolView.prototype._update = function(vxlim, vylim) {
    var end, mapper, name, ref, ref1, ref2, ref3, start, xrs, yrs, zoom_info;
    if (Math.abs(vxlim[1] - vxlim[0]) <= 5 || Math.abs(vylim[1] - vylim[0]) <= 5) {
      return;
    }
    xrs = {};
    ref = this.plot_view.frame.get('x_mappers');
    for (name in ref) {
      mapper = ref[name];
      ref1 = mapper.v_map_from_target(vxlim, true), start = ref1[0], end = ref1[1];
      xrs[name] = {
        start: start,
        end: end
      };
    }
    yrs = {};
    ref2 = this.plot_view.frame.get('y_mappers');
    for (name in ref2) {
      mapper = ref2[name];
      ref3 = mapper.v_map_from_target(vylim, true), start = ref3[0], end = ref3[1];
      yrs[name] = {
        start: start,
        end: end
      };
    }
    zoom_info = {
      xrs: xrs,
      yrs: yrs
    };
    return this.plot_view.update_range(zoom_info);
  };

  return BoxZoomToolView;

})(GestureTool.View);

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 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACIAAAAgCAYAAAB3j6rJAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyRpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYxIDY0LjE0MDk0OSwgMjAxMC8xMi8wNy0xMDo1NzowMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNS4xIE1hY2ludG9zaCIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDozMjFERDhEMjIwQjIxMUU0ODREQUYzNzM5QTM2MjBCRSIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDozMjFERDhEMzIwQjIxMUU0ODREQUYzNzM5QTM2MjBCRSI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOjMyMUREOEQwMjBCMjExRTQ4NERBRjM3MzlBMzYyMEJFIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOjMyMUREOEQxMjBCMjExRTQ4NERBRjM3MzlBMzYyMEJFIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+a2Q0KAAAAmVJREFUeNq8V19EpFEUvzOtmKfpJSJKDL2WiLJExKaUEq0eeikiaolZLT2lVUpPydqHqIlIo1ilFOmphxj1miKWWHppnobIt7+zeyZ3jjvz/bnf9OPHd8/9d77z3XN+94ts7ew6SqksWKX+w1GFiLjYdVSAfeAQ2Ag2sf0GvAXT4C/wle1x3lt9UOGBNk6BrYa+FuYIeAWOsmNviGqe6W+q081OmAGvizgh0cpjZ3RjGBFZBpMG+xn4wM8NYJfWFwNXwXrwS96RiIUTwwYn6AxMgb+FvQ5c4zOUxzR4Ce5GLZyo5LfSsQP2G5xQbKO+bWFfoLWinA1OAEcoM2rFRpMe5sloJWgtm4j0iPZcPhVdkOWxBWvZONIi2uc+5sqxbTaO1Ij2o4+5T6JdGy1SF4Kg2mLsi01E/oh2l4+5HTKaNlmTEe0ka40XyNqTsYnIkWiTwC16rMRNci0bR0hJ7w1veizqy9uB5D4ZDZKBtI3WvLCCJoT9E3jHny4j1DdmWOcbrWWjNYuGoqaL2kdmKayTztio7yzTJprz4A/9PuI3a8YMh5IKVC9fetxAY5rB79pNzXdESMJ/GrSjm8/DCTjAgpjQZCDDh5I+w4HuQBBHOsE9USty4KB2KF85m9J+v5XX9KXr3T7fQZS26WefYlcU+ayJlxhDIT40jBnn21hQOPrfgFtEqAhdGETqK7gZ4h/Av4g4Jf5TUoYquQSuqJDhFpEJca3b4EoYOtyyhrSkHTzlcj4R4t4FZ9NL+j6yMzlT/ocZES9aky3D3r6y5t2gaw3xWXgs7XFhdyzsgSpr2fFXgAEAmp2J9DuX/WgAAAAASUVORK5CYII=";

  BoxZoomTool.prototype.event_type = "pan";

  BoxZoomTool.prototype.default_order = 20;

  BoxZoomTool.prototype.initialize = function(attrs, options) {
    var plot_renderers;
    BoxZoomTool.__super__.initialize.call(this, attrs, options);
    this.register_property('tooltip', function() {
      return this._get_dim_tooltip(this.get("tool_name"), this._check_dims(this.get('dimensions'), "box zoom tool"));
    }, false);
    this.add_dependencies('tooltip', this, ['dimensions']);
    this.set('overlay', new BoxSelection.Model);
    plot_renderers = this.get('plot').get('renderers');
    plot_renderers.push(this.get('overlay'));
    return this.get('plot').set('renderers', plot_renderers);
  };

  BoxZoomTool.prototype.defaults = function() {
    return _.extend({}, BoxZoomTool.__super__.defaults.call(this), {
      dimensions: ["width", "height"]
    });
  };

  return BoxZoomTool;

})(GestureTool.Model);

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


},{"../../renderer/overlay/box_selection":"renderer/overlay/box_selection","./gesture_tool":"tool/gestures/gesture_tool","underscore":"underscore"}],"tool/gestures/gesture_tool":[function(require,module,exports){
var ButtonTool, GestureTool, GestureToolButtonView, GestureToolView, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

ButtonTool = require("../button_tool");

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

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

  GestureToolButtonView.prototype._clicked = function() {
    var active;
    active = this.model.get('active');
    return this.model.set('active', !active);
  };

  return GestureToolButtonView;

})(ButtonTool.ButtonView);

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

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

  return GestureToolView;

})(ButtonTool.View);

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

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

  GestureTool.prototype.nonserializable_attribute_names = function() {
    return GestureTool.__super__.nonserializable_attribute_names.call(this).concat(['overlay', 'event_type', 'default_order']);
  };

  GestureTool.prototype.defaults = function() {
    return _.extend({}, GestureTool.__super__.defaults.call(this), {
      event_type: this.event_type,
      default_order: this.default_order
    });
  };

  return GestureTool;

})(ButtonTool.Model);

module.exports = {
  Model: GestureTool,
  View: GestureToolView,
  ButtonView: GestureToolButtonView
};


},{"../button_tool":"tool/button_tool","underscore":"underscore"}],"tool/gestures/lasso_select_tool":[function(require,module,exports){
var LassoSelectTool, LassoSelectToolView, PolySelection, SelectTool, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

PolySelection = require("../../renderer/overlay/poly_selection");

SelectTool = require("./select_tool");

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

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

  LassoSelectToolView.prototype.initialize = function(options) {
    LassoSelectToolView.__super__.initialize.call(this, options);
    this.listenTo(this.model, 'change:active', this._active_change);
    return this.data = null;
  };

  LassoSelectToolView.prototype._active_change = function() {
    if (!this.mget('active')) {
      return this._clear_overlay();
    }
  };

  LassoSelectToolView.prototype._keyup = function(e) {
    if (e.keyCode === 13) {
      return this._clear_overlay();
    }
  };

  LassoSelectToolView.prototype._pan_start = function(e) {
    var canvas, vx, vy;
    canvas = this.plot_view.canvas;
    vx = canvas.sx_to_vx(e.bokeh.sx);
    vy = canvas.sy_to_vy(e.bokeh.sy);
    this.data = {
      vx: [vx],
      vy: [vy]
    };
    return null;
  };

  LassoSelectToolView.prototype._pan = function(e) {
    var append, canvas, new_data, overlay, ref, 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.push(vx);
    this.data.vy.push(vy);
    overlay = this.mget('overlay');
    new_data = {};
    new_data.vx = _.clone(this.data.vx);
    new_data.vy = _.clone(this.data.vy);
    overlay.set('data', new_data);
    if (this.mget('select_every_mousemove')) {
      append = (ref = e.srcEvent.shiftKey) != null ? ref : false;
      return this._select(this.data.vx, this.data.vy, false, append);
    }
  };

  LassoSelectToolView.prototype._pan_end = function(e) {
    var append, ref;
    this._clear_overlay();
    append = (ref = e.srcEvent.shiftKey) != null ? ref : false;
    return this._select(this.data.vx, this.data.vy, true, append);
  };

  LassoSelectToolView.prototype._clear_overlay = function() {
    return this.mget('overlay').set('data', null);
  };

  LassoSelectToolView.prototype._select = function(vx, vy, final, append) {
    var ds, geometry, i, len, r, ref, sm;
    geometry = {
      type: 'poly',
      vx: vx,
      vy: vy
    };
    ref = this.mget('renderers');
    for (i = 0, len = ref.length; i < len; i++) {
      r = ref[i];
      ds = r.get('data_source');
      sm = ds.get('selection_manager');
      sm.select(this, this.plot_view.renderers[r.id], geometry, final, append);
    }
    this._save_geometry(geometry, final, append);
    return null;
  };

  return LassoSelectToolView;

})(SelectTool.View);

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 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAAQCAYAAAAbBi9cAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAABx0RVh0U29mdHdhcmUAQWRvYmUgRmlyZXdvcmtzIENTNui8sowAAAGlSURBVDiNldNNiM1hFMfxz/3PHQqxoCgWYmNDk0jyUqwsuP/719xnPVkQStl4mYWpsVXKQkYpL1m4qWmyYElZkDLKyiSbkdKYNBovo8m1uM+d/nPd/2TO6nn5nW+/c57zlCwQ9eGRBPuwF7uxAUswjme4V6tWxqFUAFiLXlSxDaswiz9RkqAL79Ffq1YeldoAXTiNs9iIn3iN0Zj0OULWYycORU1fKQdZh5s4ggncxX28DVk6W+D8MG5hrJQr5Ql68AADIUvfFTZvPuw5VpZjOVcjZCBk6eD/ACJkF7ZgMMEJVHB7kZDNeIhXGEpwEg3cWASkFy9i3vFatTJTxvJ4sAcvo3ANpkOW/sold+MgTsUKRlGbm6P68Mh59GvOSR2/cVTzqYfifisOYDtm4vmlkKVTjUZDC5TgIi5gBX7gG7qxVHNuluEjHuN6yNI3LadzoJz1HejDMXzP3X2Njp+GLJ1o79c/oBzwGgK+YHV0cyVk6eV27YKgCNuEKZzBubjeH7J0rAiUdAKFLP0QsnQSdzCp+Wl7Omlb0RGUi0+YRlmz+YXxF2YZkqkolYwKAAAAAElFTkSuQmCC";

  LassoSelectTool.prototype.event_type = "pan";

  LassoSelectTool.prototype.default_order = 12;

  LassoSelectTool.prototype.initialize = function(attrs, options) {
    var plot_renderers;
    LassoSelectTool.__super__.initialize.call(this, attrs, options);
    this.set('overlay', new PolySelection.Model({
      line_width: 2
    }));
    plot_renderers = this.get('plot').get('renderers');
    plot_renderers.push(this.get('overlay'));
    return this.get('plot').set('renderers', plot_renderers);
  };

  LassoSelectTool.prototype.defaults = function() {
    return _.extend({}, LassoSelectTool.__super__.defaults.call(this), {
      select_every_mousemove: true
    });
  };

  return LassoSelectTool;

})(SelectTool.Model);

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


},{"../../renderer/overlay/poly_selection":"renderer/overlay/poly_selection","./select_tool":"tool/gestures/select_tool","underscore":"underscore"}],"tool/gestures/pan_tool":[function(require,module,exports){
var GestureTool, PanTool, PanToolView, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

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

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

  PanToolView.prototype._pan_start = function(e) {
    var canvas, frame, hr, vr, vx, vy;
    this.last_dx = 0;
    this.last_dy = 0;
    canvas = this.plot_view.canvas;
    frame = this.plot_view.frame;
    vx = canvas.sx_to_vx(e.bokeh.sx);
    vy = canvas.sy_to_vy(e.bokeh.sy);
    if (!frame.contains(vx, vy)) {
      hr = frame.get('h_range');
      vr = frame.get('v_range');
      if (vx < hr.get('start') || vx > hr.get('end')) {
        this.v_axis_only = true;
      }
      if (vy < vr.get('start') || vy > vr.get('end')) {
        this.h_axis_only = true;
      }
    }
    return this.plot_view.interactive_timestamp = Date.now();
  };

  PanToolView.prototype._pan = function(e) {
    this._update(e.deltaX, -e.deltaY);
    return this.plot_view.interactive_timestamp = Date.now();
  };

  PanToolView.prototype._pan_end = function(e) {
    this.h_axis_only = false;
    return this.v_axis_only = false;
  };

  PanToolView.prototype._update = function(dx, dy) {
    var dims, end, frame, hr, mapper, name, new_dx, new_dy, pan_info, ref, ref1, ref2, ref3, sdx, sdy, start, sx0, sx1, sx_high, sx_low, sy0, sy1, sy_high, sy_low, vr, xrs, yrs;
    frame = this.plot_view.frame;
    new_dx = dx - this.last_dx;
    new_dy = dy - this.last_dy;
    hr = _.clone(frame.get('h_range'));
    sx_low = hr.get('start') - new_dx;
    sx_high = hr.get('end') - new_dx;
    vr = _.clone(frame.get('v_range'));
    sy_low = vr.get('start') - new_dy;
    sy_high = vr.get('end') - new_dy;
    dims = this.mget('dimensions');
    if (dims.indexOf('width') > -1 && !this.v_axis_only) {
      sx0 = sx_low;
      sx1 = sx_high;
      sdx = -new_dx;
    } else {
      sx0 = hr.get('start');
      sx1 = hr.get('end');
      sdx = 0;
    }
    if (dims.indexOf('height') > -1 && !this.h_axis_only) {
      sy0 = sy_low;
      sy1 = sy_high;
      sdy = new_dy;
    } else {
      sy0 = vr.get('start');
      sy1 = vr.get('end');
      sdy = 0;
    }
    this.last_dx = dx;
    this.last_dy = dy;
    xrs = {};
    ref = frame.get('x_mappers');
    for (name in ref) {
      mapper = ref[name];
      ref1 = mapper.v_map_from_target([sx0, sx1], true), start = ref1[0], end = ref1[1];
      xrs[name] = {
        start: start,
        end: end
      };
    }
    yrs = {};
    ref2 = frame.get('y_mappers');
    for (name in ref2) {
      mapper = ref2[name];
      ref3 = mapper.v_map_from_target([sy0, sy1], true), start = ref3[0], end = ref3[1];
      yrs[name] = {
        start: start,
        end: end
      };
    }
    pan_info = {
      xrs: xrs,
      yrs: yrs,
      sdx: sdx,
      sdy: sdy
    };
    this.plot_view.update_range(pan_info);
    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 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyRpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYxIDY0LjE0MDk0OSwgMjAxMC8xMi8wNy0xMDo1NzowMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNS4xIE1hY2ludG9zaCIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDpCRTI5MDhEODIwQjUxMUU0ODREQUYzNzM5QTM2MjBCRSIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDpCRTI5MDhEOTIwQjUxMUU0ODREQUYzNzM5QTM2MjBCRSI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOkJFMjkwOEQ2MjBCNTExRTQ4NERBRjM3MzlBMzYyMEJFIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOkJFMjkwOEQ3MjBCNTExRTQ4NERBRjM3MzlBMzYyMEJFIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+OXzPwwAAAKNJREFUeNrsVsEKgCAM3cyj0f8fuwT9XdEHrLyVIOKYY4kPPDim0+fenF+3HZi4nhFec+Rs4oCPAALwjDVUsKMWA6DNAFX6YXcMYIERdRWIYBzAZbKYGsSKex6mVUAK8Za0TphgoFTbpSvlx3/I0EQOILO2i/ibegLk/mgVONM4JvuBVizgkGH3XTGrR/xlV0ycbO8qCeMN54wdtVQwSTFwCzAATqEZUn8W8W4AAAAASUVORK5CYII=";

  PanTool.prototype.event_type = "pan";

  PanTool.prototype.default_order = 10;

  PanTool.prototype.initialize = function(attrs, options) {
    PanTool.__super__.initialize.call(this, attrs, options);
    this.register_property('tooltip', function() {
      return this._get_dim_tooltip("Pan", this._check_dims(this.get('dimensions'), "pan tool"));
    }, false);
    return this.add_dependencies('tooltip', this, ['dimensions']);
  };

  PanTool.prototype.nonserializable_attribute_names = function() {
    return PanTool.__super__.nonserializable_attribute_names.call(this).concat(['level', 'default_order', 'event_type']);
  };

  PanTool.prototype.defaults = function() {
    return _.extend({}, PanTool.__super__.defaults.call(this), {
      dimensions: ["width", "height"]
    });
  };

  return PanTool;

})(GestureTool.Model);

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


},{"./gesture_tool":"tool/gestures/gesture_tool","underscore":"underscore"}],"tool/gestures/poly_select_tool":[function(require,module,exports){
var PolySelectTool, PolySelectToolView, PolySelection, SelectTool, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

PolySelection = require("../../renderer/overlay/poly_selection");

SelectTool = require("./select_tool");

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

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

  PolySelectToolView.prototype.initialize = function(options) {
    PolySelectToolView.__super__.initialize.call(this, options);
    this.listenTo(this.model, 'change:active', this._active_change);
    return this.data = null;
  };

  PolySelectToolView.prototype._active_change = function() {
    if (!this.mget('active')) {
      return this._clear_data();
    }
  };

  PolySelectToolView.prototype._keyup = function(e) {
    if (e.keyCode === 13) {
      return this._clear_data();
    }
  };

  PolySelectToolView.prototype._doubletap = function(e) {
    var append, ref;
    append = (ref = e.srcEvent.shiftKey) != null ? ref : false;
    this._select(this.data.vx, this.data.vy, true, append);
    return this._clear_data();
  };

  PolySelectToolView.prototype._clear_data = function() {
    this.data = null;
    return this.mget('overlay').set('data', null);
  };

  PolySelectToolView.prototype._tap = function(e) {
    var canvas, new_data, overlay, vx, vy;
    canvas = this.plot_view.canvas;
    vx = canvas.sx_to_vx(e.bokeh.sx);
    vy = canvas.sy_to_vy(e.bokeh.sy);
    if (this.data == null) {
      this.data = {
        vx: [vx],
        vy: [vy]
      };
      return null;
    }
    this.data.vx.push(vx);
    this.data.vy.push(vy);
    overlay = this.mget('overlay');
    new_data = {};
    new_data.vx = _.clone(this.data.vx);
    new_data.vy = _.clone(this.data.vy);
    return overlay.set('data', new_data);
  };

  PolySelectToolView.prototype._select = function(vx, vy, final, append) {
    var ds, geometry, i, len, r, ref, sm;
    geometry = {
      type: 'poly',
      vx: vx,
      vy: vy
    };
    ref = this.mget('renderers');
    for (i = 0, len = ref.length; i < len; i++) {
      r = ref[i];
      ds = r.get('data_source');
      sm = ds.get('selection_manager');
      sm.select(this, this.plot_view.renderers[r.id], geometry, final, append);
    }
    this._save_geometry(geometry, final, append);
    return null;
  };

  return PolySelectToolView;

})(SelectTool.View);

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 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAAQCAYAAAAbBi9cAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAABx0RVh0U29mdHdhcmUAQWRvYmUgRmlyZXdvcmtzIENTNui8sowAAAGdSURBVDiNjdO/axRBGMbxT8IiwSBBi4AiBBVRJE3UIqIIilrYLGuxMYo/AimsrNTCWkH/AbFR78Dc5dZiWW3SKQaVaKWlIFEiithooaiIZ7EbPM7b3D0wzLzzvvOdZ5iZviTNmnKN4gE2YSteYjW24A2+Yh/ux1G4uVij2cyXB0V8AYuYwBq8x5Ei/wEH8LNoHRVgWxyFr4v4RUvuScv4ESRpFhTQ/9SPmSTNdpbt1KZhXCsD7cZQj6AB7OqUCDCCTz2C3mF/maNnGOsRtB53y0BD/t1eN32T32pH0HY870ZI0mwMFZwvA73F+AqA4STNduCS3PlSpdbY0F4XFKAfJZA9mMO9OAonl+crtcZcpdaYP3ti4mqro0Py79AKOJqk2TwGMRVH4XTbHqtwpVJrVKv1ZGDZ0SIO4mGSZqNYh2m8wtM4Cr93MPur6E9jY7WenAvkz38pSbO9eIzrcRQe63TUFg3iDz7iIj73Yxa3i4LxOAovr0S4MzPbhzoOYy1GzkzGXwLcxC0sxFH4u4sTUyePN3EDKrXGAk4h/QvU5XGB9rRYawAAAABJRU5ErkJggg==";

  PolySelectTool.prototype.event_type = "tap";

  PolySelectTool.prototype.default_order = 11;

  PolySelectTool.prototype.initialize = function(attrs, options) {
    var plot_renderers;
    PolySelectTool.__super__.initialize.call(this, attrs, options);
    this.set('overlay', new PolySelection.Model);
    plot_renderers = this.get('plot').get('renderers');
    plot_renderers.push(this.get('overlay'));
    return this.get('plot').set('renderers', plot_renderers);
  };

  return PolySelectTool;

})(SelectTool.Model);

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


},{"../../renderer/overlay/poly_selection":"renderer/overlay/poly_selection","./select_tool":"tool/gestures/select_tool","underscore":"underscore"}],"tool/gestures/resize_tool":[function(require,module,exports){
var GestureTool, ResizeTool, ResizeToolView, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

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

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

  ResizeToolView.prototype.className = "bk-resize-popup";

  ResizeToolView.prototype.initialize = function(options) {
    var wrapper;
    ResizeToolView.__super__.initialize.call(this, options);
    wrapper = this.plot_view.$el.find('div.bk-canvas-wrapper');
    this.$el.appendTo(wrapper);
    this.$el.hide();
    this.active = false;
    return null;
  };

  ResizeToolView.prototype.activate = function() {
    this.active = true;
    this.render();
    return null;
  };

  ResizeToolView.prototype.deactivate = function() {
    this.active = false;
    this.render();
    return null;
  };

  ResizeToolView.prototype.render = function(ctx) {
    var canvas, frame, left, top;
    if (this.active) {
      canvas = this.plot_view.canvas;
      frame = this.plot_view.frame;
      left = canvas.vx_to_sx(frame.get('h_range').get('end') - 40);
      top = canvas.vy_to_sy(frame.get('v_range').get('start') + 40);
      this.$el.attr('style', "position:absolute; top:" + top + "px; left:" + left + "px;");
      this.$el.show();
    } else {
      this.$el.hide();
    }
    return this;
  };

  ResizeToolView.prototype._pan_start = function(e) {
    var canvas;
    canvas = this.plot_view.canvas;
    this.ch = canvas.get('height');
    this.cw = canvas.get('width');
    this.plot_view.interactive_timestamp = Date.now();
    return null;
  };

  ResizeToolView.prototype._pan = function(e) {
    this._update(e.deltaX, e.deltaY);
    this.plot_view.interactive_timestamp = Date.now();
    return null;
  };

  ResizeToolView.prototype._update = function(dx, dy) {
    var canvas;
    this.plot_view.pause();
    canvas = this.plot_view.canvas;
    canvas._set_dims([this.cw + dx, this.ch + dy]);
    this.plot_view.unpause();
    return null;
  };

  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 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACIAAAAgCAYAAAB3j6rJAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyRpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYxIDY0LjE0MDk0OSwgMjAxMC8xMi8wNy0xMDo1NzowMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNS4xIE1hY2ludG9zaCIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDpBODVDNDBCQjIwQjMxMUU0ODREQUYzNzM5QTM2MjBCRSIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDpBODVDNDBCQzIwQjMxMUU0ODREQUYzNzM5QTM2MjBCRSI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOjMyMUREOEQ4MjBCMjExRTQ4NERBRjM3MzlBMzYyMEJFIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOkE4NUM0MEJBMjBCMzExRTQ4NERBRjM3MzlBMzYyMEJFIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+nIbQ0AAAAIJJREFUeNpiXLhs5X8G7ICRgTYAq31MDIMEwBzyERoCyJhWAN2ej4MqRFiIjUMahczgSyMsNE4PxACBQZlrcAFsuYkcLECpQwZNiIw6ZNQhow4ZdcioQ0YdMuoQerRZkQE/vdqwgypqQD7+MIBuANn9f1CnEcbRXIMjd4zM0QCAAAMAbdAPQaze1JcAAAAASUVORK5CYII=";

  ResizeTool.prototype.event_type = "pan";

  ResizeTool.prototype.default_order = 40;

  ResizeTool.prototype.nonserializable_attribute_names = function() {
    return ResizeTool.__super__.nonserializable_attribute_names.call(this).concat(['data']);
  };

  ResizeTool.prototype.defaults = function() {
    return _.extend({}, ResizeTool.__super__.defaults.call(this), {
      level: 'overlay',
      data: {}
    });
  };

  return ResizeTool;

})(GestureTool.Model);

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


},{"./gesture_tool":"tool/gestures/gesture_tool","underscore":"underscore"}],"tool/gestures/select_tool":[function(require,module,exports){
var GestureTool, SelectTool, SelectToolView, _, 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");

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

GestureTool = require("./gesture_tool");

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

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

  SelectToolView.prototype._keyup = function(e) {
    var ds, j, len, r, ref, results, sm;
    if (e.keyCode === 27) {
      ref = this.mget('renderers');
      results = [];
      for (j = 0, len = ref.length; j < len; j++) {
        r = ref[j];
        ds = r.get('data_source');
        sm = ds.get('selection_manager');
        results.push(sm.clear());
      }
      return results;
    }
  };

  SelectToolView.prototype._save_geometry = function(geometry, final, append) {
    var g, geoms, i, j, ref, tool_events, xm, ym;
    g = _.clone(geometry);
    xm = this.plot_view.frame.get('x_mappers')['default'];
    ym = this.plot_view.frame.get('y_mappers')['default'];
    if (g.type === 'point') {
      g.x = xm.map_from_target(g.vx);
      g.y = ym.map_from_target(g.vy);
    } else if (g.type === 'rect') {
      g.x0 = xm.map_from_target(g.vx0);
      g.y0 = ym.map_from_target(g.vy0);
      g.x1 = xm.map_from_target(g.vx1);
      g.y1 = ym.map_from_target(g.vy1);
    } else if (g.type === 'poly') {
      g.x = new Array(g.vx.length);
      g.y = new Array(g.vy.length);
      for (i = j = 0, ref = g.vx.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
        g.x[i] = xm.map_from_target(g.vx[i]);
        g.y[i] = ym.map_from_target(g.vy[i]);
      }
    } else {
      logger.debug("Unrecognized selection geometry type: '" + g.type + "'");
    }
    if (final) {
      tool_events = this.plot_model.get('tool_events');
      if (append) {
        geoms = tool_events.get('geometries');
        geoms.push(g);
      } else {
        geoms = [g];
      }
      tool_events.set("geometries", geoms);
    }
    return null;
  };

  return SelectToolView;

})(GestureTool.View);

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

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

  SelectTool.prototype.initialize = function(attrs, options) {
    var all_renderers, j, len, names, r, renderers;
    SelectTool.__super__.initialize.call(this, attrs, options);
    names = this.get('names');
    renderers = this.get('renderers');
    if (renderers.length === 0) {
      all_renderers = this.get('plot').get('renderers');
      renderers = (function() {
        var j, len, results;
        results = [];
        for (j = 0, len = all_renderers.length; j < len; j++) {
          r = all_renderers[j];
          if (r.type === "GlyphRenderer") {
            results.push(r);
          }
        }
        return results;
      })();
    }
    if (names.length > 0) {
      renderers = (function() {
        var j, len, results;
        results = [];
        for (j = 0, len = renderers.length; j < len; j++) {
          r = renderers[j];
          if (names.indexOf(r.get('name')) >= 0) {
            results.push(r);
          }
        }
        return results;
      })();
    }
    this.set('renderers', renderers);
    logger.debug("setting " + renderers.length + " renderers for " + this.type + " " + this.id);
    for (j = 0, len = renderers.length; j < len; j++) {
      r = renderers[j];
      logger.debug(" - " + r.type + " " + r.id);
    }
    return null;
  };

  SelectTool.prototype.nonserializable_attribute_names = function() {
    return SelectTool.__super__.nonserializable_attribute_names.call(this).concat(['multi_select_modifier']);
  };

  SelectTool.prototype.defaults = function() {
    return _.extend({}, SelectTool.__super__.defaults.call(this), {
      renderers: [],
      names: [],
      multi_select_modifier: "shift"
    });
  };

  return SelectTool;

})(GestureTool.Model);

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


},{"../../common/logging":"common/logging","./gesture_tool":"tool/gestures/gesture_tool","underscore":"underscore"}],"tool/gestures/tap_tool":[function(require,module,exports){
var SelectTool, TapTool, TapToolView, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

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, ds, geometry, i, len, r, ref, sm;
    geometry = {
      type: 'point',
      vx: vx,
      vy: vy
    };
    callback = this.mget("callback");
    ref = this.mget('renderers');
    for (i = 0, len = ref.length; i < len; i++) {
      r = ref[i];
      ds = r.get('data_source');
      sm = ds.get('selection_manager');
      sm.select(this, this.plot_view.renderers[r.id], geometry, final, append);
      if (callback != null) {
        callback.execute(ds);
      }
    }
    this._save_geometry(geometry, final, append);
    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 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAABx0RVh0U29mdHdhcmUAQWRvYmUgRmlyZXdvcmtzIENTNui8sowAAAHWSURBVDiNbdJfaI9RGAfwz/7JNlLGjdxLyDU2u0EIx6uc7UIpF5pIU1OSGzfkUhvSiuSCvZbXGxeT0IxcSYlIiVxSJmqZzbj4nbafcer0nM75Ps/5Pt/vU2PWyouyAbsRsTJdv0SOGzELE9X4mlnJ7TiOtentV3qqS/EJTsUsDP9TIC/KvTiHZgyhwHP8Tkx2Ygd+4EDMwpXpAnlRtuJu+vFozMLF2a0lXAfOowkbYxYe1+RF2Yhb2IT9MQv9eVHOxTGsSwxGcCZm4WdelLuSHg8QatGZeh5KyQtxB/NwCIfRgtt5US6IWbiJgZTTWZ/UrsG1xLQHL2IWeqrYd+dF2YdunMRVBMRaLMckXiVwK3r/I0E/tqXzW0xgdX0VYCrFOjO2Va+PuJTO4/iE8Xq8RhuWqdj2FAdxpDo7ZmEUF/KiXIwxrMJUvYqibSrTdx2nUeZFeRaX8SFm4Suk5PcYiVnYAtU2bkBHzMJgXpTNOIHtqfdeLMUS3Mcz7GFmkNbjHr6jK2ZhsJp+XpQt6ec6jKIB86cLJNA+9GFOamsAb1Qc+qJic2PSagzv/iqQirQn6mvS1SQ+Y0WawkXJjUcxC5uhdpbSw9iKLjzEt7QnE6QpxWmb/wA4250STmTc7QAAAABJRU5ErkJggg==";

  TapTool.prototype.event_type = "tap";

  TapTool.prototype.default_order = 10;

  return TapTool;

})(SelectTool.Model);

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


},{"./select_tool":"tool/gestures/select_tool","underscore":"underscore"}],"tool/gestures/wheel_zoom_tool":[function(require,module,exports){
var GestureTool, WheelZoomTool, WheelZoomToolView, _, document,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

if (typeof document === "undefined" || document === null) {
  document = {};
}

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

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

  WheelZoomToolView.prototype._pinch = function(e) {
    var delta;
    if (e.scale >= 1) {
      delta = (e.scale - 1) * 20.0;
    } else {
      delta = -20.0 / e.scale;
    }
    e.bokeh.delta = delta;
    return this._scroll(e);
  };

  WheelZoomToolView.prototype._scroll = function(e) {
    var delta, dims, end, factor, frame, h_axis_only, hr, mapper, multiplier, name, ref, ref1, ref2, ref3, ref4, start, sx0, sx1, sy0, sy1, v_axis_only, vr, vx, vx_high, vx_low, vy, vy_high, vy_low, xrs, yrs, zoom_info;
    frame = this.plot_model.get('frame');
    hr = frame.get('h_range');
    vr = frame.get('v_range');
    vx = this.plot_view.canvas.sx_to_vx(e.bokeh.sx);
    vy = this.plot_view.canvas.sy_to_vy(e.bokeh.sy);
    if (vx < hr.get('start') || vx > hr.get('end')) {
      v_axis_only = true;
    }
    if (vy < vr.get('start') || vy > vr.get('end')) {
      h_axis_only = true;
    }
    if (navigator.userAgent.toLowerCase().indexOf("firefox") > -1) {
      multiplier = 20;
    } else {
      multiplier = 1;
    }
    if (((ref = e.originalEvent) != null ? ref.deltaY : void 0) != null) {
      delta = -e.originalEvent.deltaY * multiplier;
    } else {
      delta = e.bokeh.delta;
    }
    factor = this.mget('speed') * delta;
    if (factor > 0.9) {
      factor = 0.9;
    } else if (factor < -0.9) {
      factor = -0.9;
    }
    vx_low = hr.get('start');
    vx_high = hr.get('end');
    vy_low = vr.get('start');
    vy_high = vr.get('end');
    dims = this.mget('dimensions');
    if (dims.indexOf('width') > -1 && !v_axis_only) {
      sx0 = vx_low - (vx_low - vx) * factor;
      sx1 = vx_high - (vx_high - vx) * factor;
    } else {
      sx0 = vx_low;
      sx1 = vx_high;
    }
    if (dims.indexOf('height') > -1 && !h_axis_only) {
      sy0 = vy_low - (vy_low - vy) * factor;
      sy1 = vy_high - (vy_high - vy) * factor;
    } else {
      sy0 = vy_low;
      sy1 = vy_high;
    }
    xrs = {};
    ref1 = frame.get('x_mappers');
    for (name in ref1) {
      mapper = ref1[name];
      ref2 = mapper.v_map_from_target([sx0, sx1], true), start = ref2[0], end = ref2[1];
      xrs[name] = {
        start: start,
        end: end
      };
    }
    yrs = {};
    ref3 = frame.get('y_mappers');
    for (name in ref3) {
      mapper = ref3[name];
      ref4 = mapper.v_map_from_target([sy0, sy1], true), start = ref4[0], end = ref4[1];
      yrs[name] = {
        start: start,
        end: end
      };
    }
    zoom_info = {
      xrs: xrs,
      yrs: yrs,
      factor: factor
    };
    this.plot_view.update_range(zoom_info);
    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 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACwAAAAgCAYAAABpRpp6AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyRpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYxIDY0LjE0MDk0OSwgMjAxMC8xMi8wNy0xMDo1NzowMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNS4xIE1hY2ludG9zaCIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDpCRTI5MDhEQzIwQjUxMUU0ODREQUYzNzM5QTM2MjBCRSIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDpCRTI5MDhERDIwQjUxMUU0ODREQUYzNzM5QTM2MjBCRSI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOkJFMjkwOERBMjBCNTExRTQ4NERBRjM3MzlBMzYyMEJFIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOkJFMjkwOERCMjBCNTExRTQ4NERBRjM3MzlBMzYyMEJFIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+sFLapAAAA8xJREFUeNq8WH9k1VEU/+67ecTYxKM8xlJiifKIMUqUKMvy1CqbEmUxJZbSlGXTLBuJpYi18dpqStOzacT+WcTXpkiRUjziETEeY9bnzHm5O53vj/te7fDx3r3fc+/9fM/3nHPPvWWP0mOOIlVAC3AQqOc2SRZ4A9Cg58CSNrj1+FEnSIYfPynHTyOQArYCO/jRPPAJGAcmMM9f87vKfG3AF+AucMAgS5LgRZ4CH/mFrARkieAs8Aw4ASSBckaS++jZLOv6El4HjAKDwPoIa28GXgLdFmQv4WcO2BVBnXTmeIxK+D5wzLGXa8D1CGT78NPPhjFlGnjAmBbPSLefx65IBf+eZZ81hfznIfsr+W0eaACa2G3MhbuAt8CUD1kyRIfongDa4affhW4Nu2Oj0d2Bfg+6Y2UIukr2x4ShkAMOMQlNyLcmgVqj7z2wk17UDDosFOOYMOdPQ+dkyBcZFkb8DGxz2ckTwrKHA8g6HMn7gQWjbzsHqZSUmJ8sej6Cq7WzrhkzKVeYnmSEXSBM6I17RZ+WNWRfJ6z7K2xy1umUc7lGDizIkDL+AsNRXs6U3YpOUrRfWwS01K2noIuLzg+iTcFSiFLKlQPi8+aNAIwri24QlstaEM6JdoIsHBOdiyJl9RntfiXazUljEdJb3IKw1F10Q/Krtin0KaSD5Ido77MYK10sG0S4ByjzwW2LRT3pYlxLRBFpGM91/r9kRJuC/FbEnVEmhEwQYRqw7IMuC8LjnAKllSeBhEI0Qc8U636luWinWxYPqoFCnuxmX16VR9ldCvINqOH/NK5alpe8NY8qL5Nnl/GMFJhU6g2SZtqaw1xCkrss2pGEFhLp0CxuGow83+BDdoDn+FP8hJFeYusNlODL9LI/ubKLRRxDKfamuaNWRBx4o9TI49NDD9yjSdn9NKFa5jTGrdrIKpw1FJCtU8h6Rp/HwbVyBNOOSGtKGHJKtGdAao/NBO4aWrecS9mwQiuU8KLoi1nOEfepQ6TsFXVxnnO0NWFZEdVZjK8RaSgXoHtGbihwh4ViCM+LvhaL8VJ3xscdqnwOCk4xhDNKYNRHPOZfCakbzGOS+SWyloX8KsIj4lNScLwIuTsgsq+ASnFkmor4JdJayopKeEHZGOJ8OzMoatIkF0XvxIm5cGhcUtyhVqlrh4rNNoU8fI+jOCUs3cYIk14L63py9yo2D7fyBZ+t3AGuWgTmiFOCuCIvHuHFo6QbCpxm4GLIxZ+880j/K8Lm593EVZqnXF9N8UXIFt7zgwoeunDZCJzju44M+nKlEP4twAAD1RclkNDukAAAAABJRU5ErkJggg==";

  WheelZoomTool.prototype.event_type = 'ontouchstart' in window.document ? 'pinch' : 'scroll';

  WheelZoomTool.prototype.default_order = 10;

  WheelZoomTool.prototype.initialize = function(attrs, options) {
    WheelZoomTool.__super__.initialize.call(this, attrs, options);
    this.register_property('tooltip', function() {
      return this._get_dim_tooltip(this.get("tool_name"), this._check_dims(this.get('dimensions'), "wheel zoom tool"));
    }, false);
    return this.add_dependencies('tooltip', this, ['dimensions']);
  };

  WheelZoomTool.prototype.nonserializable_attribute_names = function() {
    return WheelZoomTool.__super__.nonserializable_attribute_names.call(this).concat(['speed']);
  };

  WheelZoomTool.prototype.defaults = function() {
    return _.extend({}, WheelZoomTool.__super__.defaults.call(this), {
      dimensions: ["width", "height"],
      speed: 1 / 600
    });
  };

  return WheelZoomTool;

})(GestureTool.Model);

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


},{"./gesture_tool":"tool/gestures/gesture_tool","underscore":"underscore"}],"tool/inspectors/crosshair_tool":[function(require,module,exports){
var CrosshairTool, CrosshairToolView, InspectTool, Span, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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");

Span = require("../../renderer/annotation/span");

InspectTool = require("./inspect_tool");

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

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

  CrosshairToolView.prototype._move = function(e) {
    var canvas, dim, frame, i, len, ref, results, span, vx, vy;
    if (!this.mget('active')) {
      return;
    }
    frame = this.plot_model.get('frame');
    canvas = this.plot_model.get('canvas');
    vx = canvas.sx_to_vx(e.bokeh.sx);
    vy = canvas.sy_to_vy(e.bokeh.sy);
    ref = this.mget('dimensions');
    results = [];
    for (i = 0, len = ref.length; i < len; i++) {
      dim = ref[i];
      span = this.mget('spans')[dim];
      if (!frame.contains(vx, vy)) {
        results.push(span.unset('location'));
      } else {
        if (dim === "width") {
          results.push(span.set('location', vy));
        } else {
          results.push(span.set('location', vx));
        }
      }
    }
    return results;
  };

  CrosshairToolView.prototype._move_exit = function(e) {
    var dim, i, len, ref, results, span;
    ref = this.mget('dimensions');
    results = [];
    for (i = 0, len = ref.length; i < len; i++) {
      dim = ref[i];
      span = this.mget('spans')[dim];
      results.push(span.unset('location'));
    }
    return results;
  };

  return CrosshairToolView;

})(InspectTool.View);

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

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

  CrosshairTool.prototype.default_view = CrosshairToolView;

  CrosshairTool.prototype.type = "CrosshairTool";

  CrosshairTool.prototype.tool_name = "Crosshair";

  CrosshairTool.prototype.initialize = function(attrs, options) {
    var ast, renderers;
    CrosshairTool.__super__.initialize.call(this, attrs, options);
    this.register_property('tooltip', function() {
      return this._get_dim_tooltip("Crosshair", this._check_dims(this.get('dimensions'), "crosshair tool"));
    }, false);
    this.add_dependencies('tooltip', this, ['dimensions']);
    this.set('spans', {
      width: new Span.Model({
        dimension: "width",
        render_mode: this.get("render_mode"),
        location_units: this.get("location_units"),
        line_color: this.get("line_color"),
        line_width: this.get('line_width'),
        line_alpha: this.get('line_alpha')
      }),
      height: new Span.Model({
        dimension: "height",
        render_mode: this.get("render_mode"),
        location_units: this.get("location_units"),
        line_color: this.get("line_color"),
        line_width: this.get('line_width'),
        line_alpha: this.get('line_alpha')
      })
    });
    renderers = this.get('plot').get('renderers');
    renderers.push(this.get('spans').width);
    renderers.push(this.get('spans').height);
    this.get('plot').set('renderers', renderers);
    return ast = this.display_defaults;
  };

  CrosshairTool.prototype.nonserializable_attribute_names = function() {
    return CrosshairTool.__super__.nonserializable_attribute_names.call(this).concat(['location_units', 'render_mode', 'spans']);
  };

  CrosshairTool.prototype.defaults = function() {
    return _.extend({}, CrosshairTool.__super__.defaults.call(this), {
      dimensions: ["width", "height"],
      location_units: "screen",
      render_mode: "css"
    });
  };

  CrosshairTool.prototype.display_defaults = function() {
    return _.extend({}, CrosshairTool.__super__.display_defaults.call(this), {
      line_color: 'black',
      line_width: 1,
      line_alpha: 1.0
    });
  };

  return CrosshairTool;

})(InspectTool.Model);

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


},{"../../renderer/annotation/span":"renderer/annotation/span","./inspect_tool":"tool/inspectors/inspect_tool","underscore":"underscore"}],"tool/inspectors/hover_tool":[function(require,module,exports){
var $, HoverTool, HoverToolView, InspectTool, Tooltip, Util, _, _color_to_hex, 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");

$ = require("jquery");

Tooltip = require("../../renderer/annotation/tooltip");

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

InspectTool = require("./inspect_tool");

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

_color_to_hex = function(color) {
  var blue, digits, green, red, rgb;
  if (color.substr(0, 1) === '#') {
    return color;
  }
  digits = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(color);
  red = parseInt(digits[2]);
  green = parseInt(digits[3]);
  blue = parseInt(digits[4]);
  rgb = blue | (green << 8) | (red << 16);
  return digits[1] + '#' + rgb.toString(16);
};

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

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

  HoverToolView.prototype.bind_bokeh_events = function() {
    var j, len, r, ref;
    ref = this.mget('renderers');
    for (j = 0, len = ref.length; j < len; j++) {
      r = ref[j];
      this.listenTo(r.get('data_source'), 'inspect', this._update);
    }
    return this.plot_view.canvas_view.canvas_wrapper.css('cursor', 'crosshair');
  };

  HoverToolView.prototype._move = function(e) {
    var canvas, ref, rid, tt, vx, vy;
    if (!this.mget('active')) {
      return;
    }
    canvas = this.plot_view.canvas;
    vx = canvas.sx_to_vx(e.bokeh.sx);
    vy = canvas.sy_to_vy(e.bokeh.sy);
    if (!this.plot_view.frame.contains(vx, vy)) {
      ref = this.mget('ttmodels');
      for (rid in ref) {
        tt = ref[rid];
        tt.clear();
      }
      return;
    }
    return this._inspect(vx, vy);
  };

  HoverToolView.prototype._move_exit = function() {
    var ref, results, rid, tt;
    ref = this.mget('ttmodels');
    results = [];
    for (rid in ref) {
      tt = ref[rid];
      results.push(tt.clear());
    }
    return results;
  };

  HoverToolView.prototype._inspect = function(vx, vy, e) {
    var geometry, hovered_indexes, hovered_renderers, j, len, r, ref, sm;
    geometry = {
      type: 'point',
      vx: vx,
      vy: vy
    };
    if (this.mget('mode') === 'mouse') {
      geometry['type'] = 'point';
    } else {
      geometry['type'] = 'span';
      if (this.mget('mode') === 'vline') {
        geometry.direction = 'h';
      } else {
        geometry.direction = 'v';
      }
    }
    hovered_indexes = [];
    hovered_renderers = [];
    ref = this.mget('renderers');
    for (j = 0, len = ref.length; j < len; j++) {
      r = ref[j];
      sm = r.get('data_source').get('selection_manager');
      sm.inspect(this, this.plot_view.renderers[r.id], geometry, {
        "geometry": geometry
      });
    }
    if (this.mget('callback') != null) {
      this._emit_callback(geometry);
    }
  };

  HoverToolView.prototype._update = function(indices, tool, renderer, ds, arg) {
    var canvas, d1x, d1y, d2x, d2y, data_x, data_y, dist1, dist2, frame, geometry, i, i1d, i2d, j, k, len, len1, ref, ref1, ref10, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, rx, ry, sdatax, sdatay, sx, sy, tooltip, vars, vx, vy, x, xmapper, y, ymapper;
    geometry = arg.geometry;
    tooltip = (ref = this.mget('ttmodels')[renderer.model.id]) != null ? ref : null;
    if (tooltip == null) {
      return;
    }
    tooltip.clear();
    ref1 = [indices['1d'].indices, indices['2d'].indices], i1d = ref1[0], i2d = ref1[1];
    if (indices['0d'].flag === false && i1d.length === 0 && i2d.length === 0) {
      return;
    }
    vx = geometry.vx;
    vy = geometry.vy;
    canvas = this.plot_model.get('canvas');
    frame = this.plot_model.get('frame');
    sx = canvas.vx_to_sx(vx);
    sy = canvas.vy_to_sy(vy);
    xmapper = frame.get('x_mappers')[renderer.mget('x_range_name')];
    ymapper = frame.get('y_mappers')[renderer.mget('y_range_name')];
    x = xmapper.map_from_target(vx);
    y = ymapper.map_from_target(vy);
    ref2 = indices['0d'].indices;
    for (j = 0, len = ref2.length; j < len; j++) {
      i = ref2[j];
      data_x = renderer.glyph.x[i + 1];
      data_y = renderer.glyph.y[i + 1];
      if (this.mget('line_policy') === "interp") {
        ref3 = renderer.glyph.get_interpolation_hit(i, geometry), data_x = ref3[0], data_y = ref3[1];
        rx = xmapper.map_to_target(data_x);
        ry = ymapper.map_to_target(data_y);
      } else if (this.mget('line_policy') === "prev") {
        rx = canvas.sx_to_vx(renderer.glyph.sx[i]);
        ry = canvas.sy_to_vy(renderer.glyph.sy[i]);
      } else if (this.mget('line_policy') === "next") {
        rx = canvas.sx_to_vx(renderer.glyph.sx[i + 1]);
        ry = canvas.sy_to_vy(renderer.glyph.sy[i + 1]);
      } else if (this.mget('line_policy') === "nearest") {
        d1x = renderer.glyph.sx[i];
        d1y = renderer.glyph.sy[i];
        dist1 = hittest.dist_2_pts(d1x, d1y, sx, sy);
        d2x = renderer.glyph.sx[i + 1];
        d2y = renderer.glyph.sy[i + 1];
        dist2 = hittest.dist_2_pts(d2x, d2y, sx, sy);
        if (dist1 < dist2) {
          ref4 = [d1x, d1y], sdatax = ref4[0], sdatay = ref4[1];
        } else {
          ref5 = [d2x, d2y], sdatax = ref5[0], sdatay = ref5[1];
          i = i + 1;
        }
        data_x = renderer.glyph.x[i];
        data_y = renderer.glyph.y[i];
        rx = canvas.sx_to_vx(sdatax);
        ry = canvas.sy_to_vy(sdatay);
      } else {
        ref6 = [vx, vy], rx = ref6[0], ry = ref6[1];
      }
      vars = {
        index: i,
        x: x,
        y: y,
        vx: vx,
        vy: vy,
        sx: sx,
        sy: sy,
        data_x: data_x,
        data_y: data_y,
        rx: rx,
        ry: ry
      };
      tooltip.add(rx, ry, this._render_tooltips(ds, i, vars));
    }
    ref7 = indices['1d'].indices;
    for (k = 0, len1 = ref7.length; k < len1; k++) {
      i = ref7[k];
      data_x = (ref8 = renderer.glyph.x) != null ? ref8[i] : void 0;
      data_y = (ref9 = renderer.glyph.y) != null ? ref9[i] : void 0;
      if (this.mget('point_policy') === 'snap_to_data') {
        rx = canvas.sx_to_vx(renderer.glyph.scx(i, sx, sy));
        ry = canvas.sy_to_vy(renderer.glyph.scy(i, sx, sy));
      } else {
        ref10 = [vx, vy], rx = ref10[0], ry = ref10[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 canvas, frame, indices, r, xmapper, ymapper;
    r = this.mget('renderers')[0];
    indices = this.plot_view.renderers[r.id].hit_test(geometry);
    canvas = this.plot_model.get('canvas');
    frame = this.plot_model.get('frame');
    geometry['sx'] = canvas.vx_to_sx(geometry.vx);
    geometry['sy'] = canvas.vy_to_sy(geometry.vy);
    xmapper = frame.get('x_mappers')[r.get('x_range_name')];
    ymapper = frame.get('y_mappers')[r.get('y_range_name')];
    geometry['x'] = xmapper.map_from_target(geometry.vx);
    geometry['y'] = ymapper.map_from_target(geometry.vy);
    this.mget('callback').execute(this.model, {
      index: indices,
      geometry: geometry
    });
  };

  HoverToolView.prototype._render_tooltips = function(ds, i, vars) {
    var colname, color, column, hex, j, label, len, match, opts, ref, ref1, row, span, swatch, table, td, tooltips, value;
    tooltips = this.mget("tooltips");
    if (_.isString(tooltips)) {
      return $('<div>').html(Util.replace_placeholders(tooltips, ds, i, vars));
    } else {
      table = $('<table></table>');
      for (j = 0, len = tooltips.length; j < len; j++) {
        ref = tooltips[j], label = ref[0], value = ref[1];
        row = $("<tr></tr>");
        row.append($("<td class='bk-tooltip-row-label'>").text(label + ": "));
        td = $("<td class='bk-tooltip-row-value'></td>");
        if (value.indexOf("$color") >= 0) {
          ref1 = value.match(/\$color(\[.*\])?:(\w*)/), match = ref1[0], opts = ref1[1], colname = ref1[2];
          column = ds.get_column(colname);
          if (column == null) {
            span = $("<span>").text(colname + " unknown");
            td.append(span);
            continue;
          }
          hex = (opts != null ? opts.indexOf("hex") : void 0) >= 0;
          swatch = (opts != null ? opts.indexOf("swatch") : void 0) >= 0;
          color = column[i];
          if (color == null) {
            span = $("<span>(null)</span>");
            td.append(span);
            continue;
          }
          if (hex) {
            color = _color_to_hex(color);
          }
          span = $("<span>").text(color);
          td.append(span);
          if (swatch) {
            span = $("<span class='bk-tooltip-color-block'> </span>");
            span.css({
              backgroundColor: color
            });
          }
          td.append(span);
        } else {
          value = value.replace("$~", "$data_");
          value = Util.replace_placeholders(value, ds, i, vars);
          td.append($('<span>').html(value));
        }
        row.append(td);
        table.append(row);
      }
      return table;
    }
  };

  return HoverToolView;

})(InspectTool.View);

HoverTool = (function(superClass) {
  var icon;

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

  icon = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAA8ElEQVQ4T42T0Q2CMBCGaQjPxgmMG/jelIQN3ECZQEfADRwBJzBuQCC81wlkBHxvqP8lmhTsUfpSWvp/vfvvKiJn1HVdpml6dPdC38I90DSNxVobYzKMPiSm/z5AZK3t4zjOpJQ6BPECfiKAcqRUzkFmASQEhHzJOUgQ8BWyviwFsL4sBnC+LAE84YMWQnSAVCixdkvMAiB6Q7TCfJtrLq4PHkmSnHHbi0LHvOYa6w/g3kitjSgOYFyUUoWvlCPA9C1gvQfgDmiHNLZBgO8A3geZt+G6chQBA7hi/0QVQBrZ9EwQ0LbtbhgGghQAVFPAB25HmRH8b2/nAAAAAElFTkSuQmCC';

  HoverTool.prototype.initialize = function(attrs, options) {
    var j, len, r, ref, renderers, tooltip, tooltips, ttmodels;
    HoverTool.__super__.initialize.call(this, attrs, options);
    ttmodels = {};
    renderers = this.get('plot').get('renderers');
    tooltips = this.get("tooltips");
    if (tooltips) {
      ref = this.get('renderers');
      for (j = 0, len = ref.length; j < len; j++) {
        r = ref[j];
        tooltip = new Tooltip.Model();
        tooltip.set("custom", _.isString(tooltips));
        ttmodels[r.id] = tooltip;
        renderers.push(tooltip);
      }
    }
    this.set('ttmodels', ttmodels);
    this.get('plot').set('renderers', renderers);
  };

  HoverTool.prototype.defaults = function() {
    return _.extend({}, HoverTool.__super__.defaults.call(this), {
      tooltips: [["index", "$index"], ["data (x, y)", "($x, $y)"], ["canvas (x, y)", "($sx, $sy)"]],
      mode: 'mouse',
      point_policy: "snap_to_data",
      line_policy: "prev"
    });
  };

  return HoverTool;

})(InspectTool.Model);

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


},{"../../common/hittest":"common/hittest","../../renderer/annotation/tooltip":"renderer/annotation/tooltip","../../util/util":"util/util","./inspect_tool":"tool/inspectors/inspect_tool","jquery":"jquery","underscore":"underscore"}],"tool/inspectors/inspect_tool":[function(require,module,exports){
var Backbone, InspectTool, InspectToolListItemView, InspectToolView, Tool, _, inspect_tool_list_item_template, 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");

Backbone = require("backbone");

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

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(this.model.attrs_and_props()));
    return this;
  };

  InspectToolListItemView.prototype._clicked = function(e) {
    var active;
    active = this.model.get('active');
    return this.model.set('active', !active);
  };

  return InspectToolListItemView;

})(Backbone.View);

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

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

  return InspectToolView;

})(Tool.View);

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

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

  InspectTool.prototype.event_type = "move";

  InspectTool.prototype.initialize = function(attrs, options) {
    var all_renderers, i, len, names, r, renderers, results;
    InspectTool.__super__.initialize.call(this, attrs, options);
    names = this.get('names');
    renderers = this.get('renderers');
    if (renderers.length === 0) {
      all_renderers = this.get('plot').get('renderers');
      renderers = (function() {
        var i, len, results;
        results = [];
        for (i = 0, len = all_renderers.length; i < len; i++) {
          r = all_renderers[i];
          if (r.type === "GlyphRenderer") {
            results.push(r);
          }
        }
        return results;
      })();
    }
    if (names.length > 0) {
      renderers = (function() {
        var i, len, results;
        results = [];
        for (i = 0, len = renderers.length; i < len; i++) {
          r = renderers[i];
          if (names.indexOf(r.get('name')) >= 0) {
            results.push(r);
          }
        }
        return results;
      })();
    }
    this.set('renderers', renderers);
    logger.debug("setting " + renderers.length + " renderers for " + this.type + " " + this.id);
    results = [];
    for (i = 0, len = renderers.length; i < len; i++) {
      r = renderers[i];
      results.push(logger.debug(" - " + r.type + " " + r.id));
    }
    return results;
  };

  InspectTool.prototype.nonserializable_attribute_names = function() {
    return InspectTool.__super__.nonserializable_attribute_names.call(this).concat(['names', 'renderers', 'event_type', 'inner_only']);
  };

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

  InspectTool.prototype.defaults = function() {
    return _.extend({}, InspectTool.__super__.defaults.call(this), {
      renderers: [],
      names: [],
      inner_only: true,
      active: true,
      event_type: 'move'
    });
  };

  return InspectTool;

})(Tool.Model);

module.exports = {
  Model: InspectTool,
  View: InspectToolView,
  ListItemView: InspectToolListItemView
};


},{"../../common/logging":"common/logging","../tool":"tool/tool","./inspect_tool_list_item_template":"tool/inspectors/inspect_tool_list_item_template","backbone":"backbone","underscore":"underscore"}],"tool/inspectors/inspect_tool_list_item_template":[function(require,module,exports){
module.exports = function(__obj) {
  if (!__obj) __obj = {};
  var __out = [], __capture = function(callback) {
    var out = __out, result;
    __out = [];
    callback.call(this);
    result = __out.join('');
    __out = out;
    return __safe(result);
  }, __sanitize = function(value) {
    if (value && value.ecoSafe) {
      return value;
    } else if (typeof value !== 'undefined' && value != null) {
      return __escape(value);
    } else {
      return '';
    }
  }, __safe, __objSafe = __obj.safe, __escape = __obj.escape;
  __safe = __obj.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;
    }
  };
  if (!__escape) {
    __escape = __obj.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.active) {
        __out.push('checked');
      }
    
      __out.push('>');
    
      __out.push(__sanitize(this.tool_name));
    
      __out.push('</input>\n');
    
    }).call(this);
    
  }).call(__obj);
  __obj.safe = __objSafe, __obj.escape = __escape;
  return __out.join('');
}
},{}],"tool/tool":[function(require,module,exports){
var HasProperties, PlotWidget, Tool, ToolView, _, 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");

HasProperties = require("../common/has_properties");

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

PlotWidget = require("../common/plot_widget");

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

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

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

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

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

  return ToolView;

})(PlotWidget);

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

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

  Tool.prototype.nonserializable_attribute_names = function() {
    return Tool.__super__.nonserializable_attribute_names.call(this).concat(['active', 'level', 'tool_name']);
  };

  Tool.prototype._check_dims = function(dims, tool_name) {
    var hdim, ref, wdim;
    ref = [false, false], wdim = ref[0], hdim = ref[1];
    if (dims.length === 0) {
      logger.warn(tool_name + " given empty dimensions");
    } else if (dims.length === 1) {
      if (dims[0] !== 'width' && dims[0] !== 'height') {
        logger.warn(tool_name + " given unrecognized dimensions: " + dims);
      }
    } else if (dims.length === 2) {
      if (dims.indexOf('width') < 0 || dims.indexOf('height') < 0) {
        logger.warn(tool_name + " given unrecognized dimensions: " + dims);
      }
    } else {
      logger.warn(tool_name + " given more than two dimensions: " + dims);
    }
    if (dims.indexOf('width') >= 0) {
      wdim = true;
    }
    if (dims.indexOf('height') >= 0) {
      hdim = true;
    }
    return [wdim, hdim];
  };

  Tool.prototype._get_dim_tooltip = function(name, arg) {
    var hdim, wdim;
    wdim = arg[0], hdim = arg[1];
    if (wdim && !hdim) {
      return name + " (x-axis)";
    } else if (hdim && !wdim) {
      return name + " (y-axis)";
    } else {
      return name;
    }
  };

  Tool.prototype._get_dim_limits = function(arg, arg1, frame, dims) {
    var hr, vr, vx0, vx1, vxlim, vy0, vy1, vylim;
    vx0 = arg[0], vy0 = arg[1];
    vx1 = arg1[0], vy1 = arg1[1];
    hr = frame.get('h_range');
    if (dims.indexOf('width') >= 0) {
      vxlim = [_.min([vx0, vx1]), _.max([vx0, vx1])];
      vxlim = [_.max([vxlim[0], hr.get('min')]), _.min([vxlim[1], hr.get('max')])];
    } else {
      vxlim = [hr.get('min'), hr.get('max')];
    }
    vr = frame.get('v_range');
    if (dims.indexOf('height') >= 0) {
      vylim = [_.min([vy0, vy1]), _.max([vy0, vy1])];
      vylim = [_.max([vylim[0], vr.get('min')]), _.min([vylim[1], vr.get('max')])];
    } else {
      vylim = [vr.get('min'), vr.get('max')];
    }
    return [vxlim, vylim];
  };

  Tool.prototype.defaults = function() {
    return _.extend({}, Tool.__super__.defaults.call(this), {
      tool_name: this.tool_name,
      level: 'overlay'
    });
  };

  return Tool;

})(HasProperties);

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


},{"../common/has_properties":"common/has_properties","../common/logging":"common/logging","../common/plot_widget":"common/plot_widget","underscore":"underscore"}],"util/bezier":[function(require,module,exports){
var arc_to_bezier, segment_to_bezier;

segment_to_bezier = function(cx, cy, th0, th1, rx, ry, sin_th, cos_th) {
  var a00, a01, a10, a11, t, th_half, x1, x2, x3, y1, y2, y3;
  a00 = cos_th * rx;
  a01 = -sin_th * ry;
  a10 = sin_th * rx;
  a11 = cos_th * ry;
  th_half = 0.5 * (th1 - th0);
  t = (8 / 3) * Math.sin(th_half * 0.5) * Math.sin(th_half * 0.5) / Math.sin(th_half);
  x1 = cx + Math.cos(th0) - t * Math.sin(th0);
  y1 = cy + Math.sin(th0) + t * Math.cos(th0);
  x3 = cx + Math.cos(th1);
  y3 = cy + Math.sin(th1);
  x2 = x3 + t * Math.sin(th1);
  y2 = y3 - t * Math.cos(th1);
  return [a00 * x1 + a01 * y1, a10 * x1 + a11 * y1, a00 * x2 + a01 * y2, a10 * x2 + a11 * y2, a00 * x3 + a01 * y3, a10 * x3 + a11 * y3];
};

arc_to_bezier = function(ox, oy, radx, rady, rotateX, large, sweep, x, y) {
  var a00, a01, a10, a11, cos_th, d, i, pl, px, py, result, rx, ry, segments, sfactor, sfactor_sq, sin_th, th, th0, th1, th2, th3, th_arc, x0, x1, xc, y0, y1, yc;
  th = rotateX * (Math.PI / 180);
  sin_th = Math.sin(th);
  cos_th = Math.cos(th);
  rx = Math.abs(radx);
  ry = Math.abs(rady);
  px = cos_th * (ox - x) * 0.5 + sin_th * (oy - y) * 0.5;
  py = cos_th * (oy - y) * 0.5 - sin_th * (ox - x) * 0.5;
  pl = (px * px) / (rx * rx) + (py * py) / (ry * ry);
  if (pl > 1) {
    pl = Math.sqrt(pl);
    rx *= pl;
    ry *= pl;
  }
  a00 = cos_th / rx;
  a01 = sin_th / rx;
  a10 = -sin_th / ry;
  a11 = cos_th / ry;
  x0 = a00 * ox + a01 * oy;
  y0 = a10 * ox + a11 * oy;
  x1 = a00 * x + a01 * y;
  y1 = a10 * x + a11 * y;
  d = (x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0);
  sfactor_sq = 1 / d - 0.25;
  if (sfactor_sq < 0) {
    sfactor_sq = 0;
  }
  sfactor = Math.sqrt(sfactor_sq);
  if (sweep === large) {
    sfactor = -sfactor;
  }
  xc = 0.5 * (x0 + x1) - sfactor * (y1 - y0);
  yc = 0.5 * (y0 + y1) + sfactor * (x1 - x0);
  th0 = Math.atan2(y0 - yc, x0 - xc);
  th1 = Math.atan2(y1 - yc, x1 - xc);
  th_arc = th1 - th0;
  if (th_arc < 0 && sweep === 1) {
    th_arc += 2 * Math.PI;
  } else if (th_arc > 0 && sweep === 0) {
    th_arc -= 2 * Math.PI;
  }
  segments = Math.ceil(Math.abs(th_arc / (Math.PI * 0.5 + 0.001)));
  result = (function() {
    var j, ref, results;
    results = [];
    for (i = j = 0, ref = segments; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      th2 = th0 + i * th_arc / segments;
      th3 = th0 + (i + 1) * th_arc / segments;
      results.push(segment_to_bezier(xc, yc, th2, th3, rx, ry, sin_th, cos_th));
    }
    return results;
  })();
  return result;
};

module.exports = {
  arc_to_bezier: arc_to_bezier,
  segment_to_bezier: segment_to_bezier
};


},{}],"util/util":[function(require,module,exports){
var Numeral, SPrintf, _, _format_number, get_indices, replace_placeholders;

_ = require("underscore");

SPrintf = require("sprintf");

Numeral = require("numeral");

_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 ? Numeral.format(value, format) : _format_number(value);
      return "" + prefix + (_.escape(replacement));
    };
  })(this));
  return string;
};

get_indices = function(data_source) {
  var selected;
  selected = data_source.get("selected");
  if (selected['0d'].flag) {
    return selected['0d'].indices;
  } else if (selected['1d'].indices.length > 0) {
    return selected['1d'].indices;
  } else if (selected['2d'].indices.length > 0) {
    return selected['2d'].indices;
  } else {
    return [];
  }
};

module.exports = {
  replace_placeholders: replace_placeholders,
  get_indices: get_indices
};


},{"numeral":"numeral","sprintf":"sprintf","underscore":"underscore"}],"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"}],"bootstrap/modal":[function(require,module,exports){
var $ = require("jquery");
/* ========================================================================
 * Bootstrap: modal.js v3.1.1
 * http://getbootstrap.com/javascript/#modals
 * ========================================================================
 * Copyright 2011-2014 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */

'use strict';

// MODAL CLASS DEFINITION
// ======================

var Modal = function (element, options) {
  this.options   = options
  this.$element  = $(element)
  this.$backdrop =
  this.isShown   = null

  if (this.options.remote) {
    this.$element
      .find('.bk-bs-modal-content')
      .load(this.options.remote, $.proxy(function () {
        this.$element.trigger('loaded.bk-bs.modal')
      }, this))
  }
}

Modal.DEFAULTS = {
  backdrop: true,
  keyboard: true,
  show: true
}

Modal.prototype.toggle = function (_relatedTarget) {
  return this[!this.isShown ? 'show' : 'hide'](_relatedTarget)
}

Modal.prototype.show = function (_relatedTarget) {
  var that = this
  var e    = $.Event('show.bk-bs.modal', { relatedTarget: _relatedTarget })

  this.$element.trigger(e)

  if (this.isShown || e.isDefaultPrevented()) return

  this.isShown = true

  this.escape()

  this.$element.on('click.dismiss.bk-bs.modal', '[data-bk-bs-dismiss="modal"]', $.proxy(this.hide, this))

  this.backdrop(function () {
    var transition = $.support.transition && that.$element.hasClass('bk-bs-fade')

    if (!that.$element.parent().length) {
      that.$element.appendTo(document.body) // don't move modals dom position
    }

    that.$element
      .show()
      .scrollTop(0)

    if (transition) {
      that.$element[0].offsetWidth // force reflow
    }

    that.$element
      .addClass('bk-bs-in')
      .attr('aria-hidden', false)

    that.enforceFocus()

    var e = $.Event('shown.bk-bs.modal', { relatedTarget: _relatedTarget })

    transition ?
      that.$element.find('.bk-bs-modal-dialog') // wait for modal to slide in
        .one($.support.transition.end, function () {
          that.$element.focus().trigger(e)
        })
        .emulateTransitionEnd(300) :
      that.$element.focus().trigger(e)
  })
}

Modal.prototype.hide = function (e) {
  if (e) e.preventDefault()

  e = $.Event('hide.bk-bs.modal')

  this.$element.trigger(e)

  if (!this.isShown || e.isDefaultPrevented()) return

  this.isShown = false

  this.escape()

  $(document).off('focusin.bk-bs.modal')

  this.$element
    .removeClass('bk-bs-in')
    .attr('aria-hidden', true)
    .off('click.dismiss.bk-bs.modal')

  $.support.transition && this.$element.hasClass('bk-bs-fade') ?
    this.$element
      .one($.support.transition.end, $.proxy(this.hideModal, this))
      .emulateTransitionEnd(300) :
    this.hideModal()
}

Modal.prototype.enforceFocus = function () {
  $(document)
    .off('focusin.bk-bs.modal') // guard against infinite focus loop
    .on('focusin.bk-bs.modal', $.proxy(function (e) {
      if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
        this.$element.focus()
      }
    }, this))
}

Modal.prototype.escape = function () {
  if (this.isShown && this.options.keyboard) {
    this.$element.on('keyup.dismiss.bk-bs.modal', $.proxy(function (e) {
      e.which == 27 && this.hide()
    }, this))
  } else if (!this.isShown) {
    this.$element.off('keyup.dismiss.bk-bs.modal')
  }
}

Modal.prototype.hideModal = function () {
  var that = this
  this.$element.hide()
  this.backdrop(function () {
    that.removeBackdrop()
    that.$element.trigger('hidden.bk-bs.modal')
  })
}

Modal.prototype.removeBackdrop = function () {
  this.$backdrop && this.$backdrop.remove()
  this.$backdrop = null
}

Modal.prototype.backdrop = function (callback) {
  var animate = this.$element.hasClass('bk-bs-fade') ? 'bk-bs-fade' : ''

  if (this.isShown && this.options.backdrop) {
    var doAnimate = $.support.transition && animate

    this.$backdrop = $('<div class="bk-bs-modal-backdrop ' + animate + '" />')
      .appendTo(document.body)

    this.$element.on('click.dismiss.bk-bs.modal', $.proxy(function (e) {
      if (e.target !== e.currentTarget) return
      this.options.backdrop == 'static'
        ? this.$element[0].focus.call(this.$element[0])
        : this.hide.call(this)
    }, this))

    if (doAnimate) this.$backdrop[0].offsetWidth // force reflow

    this.$backdrop.addClass('bk-bs-in')

    if (!callback) return

    doAnimate ?
      this.$backdrop
        .one($.support.transition.end, callback)
        .emulateTransitionEnd(150) :
      callback()

  } else if (!this.isShown && this.$backdrop) {
    this.$backdrop.removeClass('bk-bs-in')

    $.support.transition && this.$element.hasClass('bk-bs-fade') ?
      this.$backdrop
        .one($.support.transition.end, callback)
        .emulateTransitionEnd(150) :
      callback()

  } else if (callback) {
    callback()
  }
}


// MODAL PLUGIN DEFINITION
// =======================

var old = $.fn.modal

$.fn.modal = function (option, _relatedTarget) {
  return this.each(function () {
    var $this   = $(this)
    var data    = $this.data('bk-bs.modal')
    var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)

    if (!data) $this.data('bk-bs.modal', (data = new Modal(this, options)))
    if (typeof option == 'string') data[option](_relatedTarget)
    else if (options.show) data.show(_relatedTarget)
  })
}

$.fn.modal.Constructor = Modal


// MODAL NO CONFLICT
// =================

$.fn.modal.noConflict = function () {
  $.fn.modal = old
  return this
}


// MODAL DATA-API
// ==============

$(document).on('click.bk-bs.modal.data-api', '[data-bk-bs-toggle="modal"]', function (e) {
  var $this   = $(this)
  var href    = $this.attr('href')
  var $target = $($this.attr('data-bk-bs-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7
  var option  = $target.data('bk-bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())

  if ($this.is('a')) e.preventDefault()

  $target
    .modal(option, this)
    .one('hide', function () {
      $this.is(':visible') && $this.focus()
    })
})

$(document)
  .on('show.bk-bs.modal', '.bk-bs-modal', function () { $(document.body).addClass('bk-bs-modal-open') })
  .on('hidden.bk-bs.modal', '.bk-bs-modal', function () { $(document.body).removeClass('bk-bs-modal-open') })

},{"jquery":"jquery"}],"gear_utils":[function(require,module,exports){
/*==========================================================================*
  Filename: gearUtils-04.js
  By: Dr A.R.Collins

  JavaScript involute gear drawing utilities.
  Requires:
  'involuteBezCoeffs' can stand alone,
  'createGearTooth' and 'createIntGearTooth' generate draw commands for use
  in Cango graphics library but may be simply converted for use in SVG.

  Kindly give credit to Dr A.R.Collins <http://www.arc.id.au/>
  Report bugs to tony at arc.id.au

  Date   |Description                                                   |By
  --------------------------------------------------------------------------
  20Feb13 First public release                                           ARC
  21Feb13 Clarified variable names of start and end parameters           ARC
  06Mar13 Fixed Rf and filletAngle calculations                          ARC
  25Jun13 Code tidy for JSLint, use strict                               ARC
 *==========================================================================*/

  // exposed globals
  var involuteBezCoeffs, createGearTooth, createIntGearTooth;

(function()
{
  "use strict";
/* ----------------------------------------------------------
 * involuteBezCoeffs
 *
 * JavaScript calculation of Bezier coefficients for
 * Higuchi et al. approximation to an involute.
 * ref: YNU Digital Eng Lab Memorandum 05-1
 *
 * Parameters:
 * module - sets the size of teeth (see gear design texts)
 * numTeeth - number of teeth on the gear
 * pressure angle - angle in degrees, usually 14.5 or 20
 * order - the order of the Bezier curve to be fitted [3, 4, 5, ..]
 * fstart - fraction of distance along tooth profile to start
 * fstop - fraction of distance along profile to stop
 *-----------------------------------------------------------*/
involuteBezCoeffs = function(module, numTeeth, pressureAngle, order, fstart, fstop)
{
  var PI = Math.PI,
      Rpitch = module*numTeeth/2,       // pitch circle radius
      phi = pressureAngle || 20,        // pressure angle
      Rb = Rpitch*Math.cos(phi*PI/180), // base circle radius
      Ra = Rpitch+module,               // addendum radius (outer radius)
      p = order || 3,                   // order of Bezier approximation
      ta = Math.sqrt(Ra*Ra-Rb*Rb)/Rb,   // involute angle at addendum
      stop = fstop || 1,
      start = 0.01,
      te, ts,
      bzCoeffs = [],
      i, bcoeff;

  function chebyExpnCoeffs(j, func)
  {
    var N = 50,      // a suitably large number  N>>p
        c = 0,
        k;

    for (k=1; k<=N; k++)
    {
      c += func(Math.cos(PI*(k-0.5)/N)) * Math.cos(PI*j*(k-0.5)/N);
    }
    return 2*c/N;
  }

  function chebyPolyCoeffs(p, func)
  {
    var coeffs = [],
        fnCoeff = [],
        T = [[], []],
        i, j, k, pwr;

    // populate 1st 2 rows of T
    for (i=0; i<p+1; i++)
    {
      T[0][i] = 0;
      T[1][i] = 0;
    }
    T[0][0] = 1;
    T[1][1] = 1;
    /* now generate the Chebyshev polynomial coefficient using
       formula T(k+1) = 2xT(k) - T(k-1) which yields
    T = [ [ 1,  0,  0,  0,  0,  0],    // T0(x) =  +1
          [ 0,  1,  0,  0,  0,  0],    // T1(x) =   0  +x
          [-1,  0,  2,  0,  0,  0],    // T2(x) =  -1  0  +2xx
          [ 0, -3,  0,  4,  0,  0],    // T3(x) =   0 -3x    0   +4xxx
          [ 1,  0, -8,  0,  8,  0],    // T4(x) =  +1  0  -8xx       0  +8xxxx
          [ 0,  5,  0,-20,  0, 16],    // T5(x) =   0  5x    0  -20xxx       0  +16xxxxx
          ...                     ];
    */
    for (k=1; k<p+1; k++)
    {
      T[k+1] = [0];
      for (j=0; j<T[k].length-1; j++)
      {
        T[k+1][j+1] = 2*T[k][j];
      }
      for (j=0; j<T[k-1].length; j++)
      {
        T[k+1][j] -= T[k-1][j];
      }
    }
    // convert the chebyshev function series into a simple polynomial
    // and collect like terms, out T polynomial coefficients
    for (k=0; k<=p; k++)
    {
      fnCoeff[k] = chebyExpnCoeffs(k, func);
      coeffs[k] = 0;
    }
    for (k=0; k<=p; k++)
    {
      for (pwr=0; pwr<=p; pwr++)    // loop thru powers of x
      {
        coeffs[pwr] += fnCoeff[k]*T[k][pwr];
      }
    }
    coeffs[0] -= chebyExpnCoeffs(0, func)/2;  // fix the 0th coeff

    return coeffs;
  }

  // Equation of involute using the Bezier parameter t as variable
  function involuteXbez(t)
  {
    // map t (0 <= t <= 1) onto x (where -1 <= x <= 1)
    var x = t*2-1;
    //map theta (where ts <= theta <= te) from x (-1 <=x <= 1)
    var theta = x*(te-ts)/2 + (ts + te)/2;
    return Rb*(Math.cos(theta)+theta*Math.sin(theta));
  }

  function involuteYbez(t)
  {
    // map t (0 <= t <= 1) onto x (where -1 <= x <= 1)
    var x = t*2-1;
    //map theta (where ts <= theta <= te) from x (-1 <=x <= 1)
    var theta = x*(te-ts)/2 + (ts + te)/2;
    return Rb*(Math.sin(theta)-theta*Math.cos(theta));
  }

  function binom(n, k)
  {
    var coeff = 1;
    var i;
    for (i = n-k+1; i <= n; i++)
    {
      coeff *= i;
    }
    for (i = 1; i <= k; i++)
    {
      coeff /= i;
    }

    return coeff;
  }

  function bezCoeff(i, func)
  {
    // generate the polynomial coeffs in one go
    var polyCoeffs = chebyPolyCoeffs(p, func),
        bc, j;

    for (bc=0, j=0; j<=i; j++)
    {
      bc += binom(i,j)*polyCoeffs[j]/binom(p,j);
    }
    return bc;
  }

  if ((fstart !== undefined)&&(fstart<stop))
  {
    start = fstart;
  }
  te = Math.sqrt(stop)*ta;          // involute angle, theta, at end of approx
  ts = Math.sqrt(start)*ta;         // involute angle, theta, at start of approx
  // calc Bezier coeffs
  for (i=0; i<=p; i++)
  {
    bcoeff = {};
    bcoeff.x = bezCoeff(i, involuteXbez);
    bcoeff.y = bezCoeff(i, involuteYbez);
    bzCoeffs.push(bcoeff);
  }

  return bzCoeffs;
};

/*----------------------------------------------------------
  createGearTooth
  Create an array of drawing commands and their coordinates
  to draw a single spur gear tooth based on a circle
  involute using the metric gear standards.

  Requires Cango graphics library Rev 2.08 or later
 ----------------------------------------------------------*/
createGearTooth = function(module, teeth, pressureAngle)
{
  function genInvolutePolar(Rb, R)  // Rb = base circle radius
  {
    // returns the involute angle as function of radius R.
    return (Math.sqrt(R*R - Rb*Rb)/Rb) - Math.acos(Rb/R);
  }

  function rotate(pt, rads)  // rotate pt by rads radians about origin
  {
    var sinA = Math.sin(rads);
    var cosA = Math.cos(rads);
    return {x: pt.x*cosA - pt.y*sinA,
            y: pt.x*sinA + pt.y*cosA};
  }

  function toCartesian(radius, angle)   // convert polar coords to cartesian
  {
    return {x: radius*Math.cos(angle),
            y: radius*Math.sin(angle)};
  }
  // ****** external gear specifications
  var m = module,                                     // Module = mm of pitch diameter per tooth
      Z = teeth,                                      // Number of teeth
      phi = pressureAngle || 20,                      // pressure angle (degrees)
      addendum = m,                                   // distance from pitch circle to tip circle
      dedendum = 1.25*m,                              // pitch circle to root, sets clearance
      clearance = dedendum - addendum,
      // Calculate radii
      Rpitch = Z*m/2,                                 // pitch circle radius
      Rb = Rpitch*Math.cos(phi*Math.PI/180),          // base circle radius
      Ra = Rpitch + addendum,                         // tip (addendum) circle radius
      Rroot = Rpitch - dedendum,                      // root circle radius
      fRad = 1.5*clearance,                           // fillet radius, max 1.5*clearance
      Rf,                                             // radius at top of fillet
      // ****** calculate angles (all in radians)
      pitchAngle = 2*Math.PI/Z,                       // angle subtended by whole tooth (rads)
      baseToPitchAngle = genInvolutePolar(Rb, Rpitch),
      pitchToFilletAngle = baseToPitchAngle,          // profile starts at base circle
      filletAngle = Math.atan(fRad/(fRad+Rroot)),     // radians
      fe, fs, fm,
      dedBz, addBz, inv, invR,
      fillet, filletR, filletNext,
      rootR, rootNext,
      pt, i, data;

  Rf = Math.sqrt((Rroot+fRad)*(Rroot+fRad)-(fRad*fRad)); // radius at top of fillet
  if (Rb < Rf)
  {
    Rf = Rroot+clearance;
  }
  if (Rf > Rb)                   // start profile at top of fillet (if its greater)
  {
    pitchToFilletAngle -= genInvolutePolar(Rb, Rf);
  }
  // ****** generate Higuchi involute approximation
  fe = 1;                    // fraction of profile length at end of approx
  fs = 0.01;                 // fraction of length offset from base to avoid singularity
  if (Rf > Rb)
  {
    fs = (Rf*Rf-Rb*Rb)/(Ra*Ra-Rb*Rb);  // offset start to top of fillet
  }
  // approximate in 2 sections, split 25% along the involute
  fm = fs+(fe-fs)/4;         // fraction of length at junction (25% along profile)
  dedBz = involuteBezCoeffs(m, Z, phi, 3, fs, fm);
  addBz = involuteBezCoeffs(m, Z, phi, 3, fm, fe);
  // join the 2 sets of coeffs (skip duplicate mid point)
  inv = dedBz.concat(addBz.slice(1));
  //create the back profile of tooth (mirror image)
  invR = [];                // involute profile along back of tooth
  for (i=0; i<inv.length; i++)
  {
    // rotate all points to put pitch point at y = 0
    pt = rotate(inv[i], -baseToPitchAngle-pitchAngle/4);
    inv[i] = pt;
    // generate the back of tooth profile nodes, mirror coords in X axis
    invR[i] = {x:pt.x, y:-pt.y};
  }
  // ****** calculate section junction points R=back of tooth, Next=front of next tooth)
  fillet = toCartesian(Rf, -pitchAngle/4-pitchToFilletAngle); // top of fillet
  filletR = {x:fillet.x, y:-fillet.y};   // flip to make same point on back of tooth
  rootR = toCartesian(Rroot, pitchAngle/4+pitchToFilletAngle+filletAngle);
  rootNext = toCartesian(Rroot, 3*pitchAngle/4-pitchToFilletAngle-filletAngle);
  filletNext = rotate(fillet, pitchAngle);  // top of fillet, front of next tooth
  // ****** create the drawing command data array for the tooth
  data = [];
  data.push("M", fillet.x, fillet.y);           // start at top of fillet
  if (Rf < Rb)
  {
    data.push("L", inv[0].x, inv[0].y);         // line from fillet up to base circle
  }
  data.push("C", inv[1].x, inv[1].y, inv[2].x, inv[2].y, inv[3].x, inv[3].y,
                 inv[4].x, inv[4].y, inv[5].x, inv[5].y, inv[6].x, inv[6].y);
  data.push("A", Ra, Ra, 0, 0, 0, invR[6].x, invR[6].y); // arc across addendum circle
  data.push("C", invR[5].x, invR[5].y, invR[4].x, invR[4].y, invR[3].x, invR[3].y,
                 invR[2].x, invR[2].y, invR[1].x, invR[1].y, invR[0].x, invR[0].y);
  if (Rf < Rb)
  {
    data.push("L", filletR.x, filletR.y);       // line down to top of fillet
  }
  if (rootNext.y > rootR.y)    // is there a section of root circle between fillets?
  {
    data.push("A", fRad, fRad, 0, 0, 1, rootR.x, rootR.y);// back fillet
    data.push("A", Rroot, Rroot, 0, 0, 0, rootNext.x, rootNext.y); // root circle arc
  }
  data.push("A", fRad, fRad, 0, 0, 1, filletNext.x, filletNext.y);

  return data;  // return an array of Cango (SVG) format draw commands
};

/*----------------------------------------------------------
  createIntGearTooth
  Create an array of drawing commands and their coordinates
  to draw a single internal (ring)gear tooth based on a
  circle involute using the metric gear standards.

  Requires Cango graphics library Rev 2.08 or later
 ----------------------------------------------------------*/
createIntGearTooth = function(module, teeth, pressureAngle)
{
  // ****** gear specifications
  var m = module,                               // Module = mm of pitch diameter per tooth
      Z = teeth,                                // Number of teeth
      phi = pressureAngle || 20,                // pressure angle (degrees)
      addendum = 0.6*m,                         // pitch circle to tip circle (ref G.M.Maitra)
      dedendum = 1.25*m,                        // pitch circle to root radius, sets clearance
      // Calculate radii
      Rpitch = Z*m/2,                           // pitch radius
      Rb = Rpitch*Math.cos(phi*Math.PI/180),    // base radius
      Ra = Rpitch - addendum,                   // addendum radius
      Rroot = Rpitch + dedendum,                // root radius
      clearance = 0.25*m,                       // gear dedendum - pinion addendum
      Rf = Rroot - clearance,                   // radius of top of fillet (end of profile)
      fRad = 1.5*clearance,                     // fillet radius, 1 .. 1.5*clearance
      pitchAngle,                               // angle between teeth (rads)
      baseToPitchAngle,
      tipToPitchAngle,
      pitchToFilletAngle,
      filletAngle,
      fe, fs, fm,
      addBz, dedBz,
      inv, invR,
      pt, i, data,
      fillet, filletNext,
      tip, tipR,
      rootR, rootNext;

  function genInvolutePolar(Rb, R)  // Rb = base circle radius
  {
    // returns the involute angle as function of radius R.
    return (Math.sqrt(R*R - Rb*Rb)/Rb) - Math.acos(Rb/R);
  }

  function rotate(pt, rads)  // rotate pt by rads radians about origin
  {
    var sinA = Math.sin(rads);
    var cosA = Math.cos(rads);
    return {x: pt.x*cosA - pt.y*sinA,
            y: pt.x*sinA + pt.y*cosA};
  }

  function toCartesian(radius, angle)   // convert polar coords to cartesian
  {
    return {x: radius*Math.cos(angle),
            y: radius*Math.sin(angle)};
  }

  // ****** calculate subtended angles
  pitchAngle = 2*Math.PI/Z;                       // angle between teeth (rads)
  baseToPitchAngle = genInvolutePolar(Rb, Rpitch);
  tipToPitchAngle = baseToPitchAngle;             // profile starts from base circle
  if (Ra > Rb)
  {
    tipToPitchAngle -= genInvolutePolar(Rb, Ra);  // start profile from addendum
  }
  pitchToFilletAngle = genInvolutePolar(Rb, Rf) - baseToPitchAngle;
  filletAngle = 1.414*clearance/Rf;               // to make fillet tangential to root
  // ****** generate Higuchi involute approximation
  fe = 1;                   // fraction of involute length at end of approx (fillet circle)
  fs = 0.01;                 // fraction of length offset from base to avoid singularity
  if (Ra > Rb)
  {
    fs = (Ra*Ra-Rb*Rb)/(Rf*Rf-Rb*Rb);    // start profile from addendum (tip circle)
  }
  // approximate in 2 sections, split 25% along the profile
  fm = fs+(fe-fs)/4;        //
  addBz = involuteBezCoeffs(m, Z, phi, 3, fs, fm);
  dedBz = involuteBezCoeffs(m, Z, phi, 3, fm, fe);
  // join the 2 sets of coeffs (skip duplicate mid point)
  invR = addBz.concat(dedBz.slice(1));
  //create the front profile of tooth (mirror image)
  inv = [];         // back involute profile
  for (i=0; i<invR.length; i++)
  {
    // rotate involute to put center of tooth at y = 0
    pt = rotate(invR[i], pitchAngle/4-baseToPitchAngle);
    invR[i] = pt;
    // generate the back of tooth profile, flip Y coords
    inv[i] = {x:pt.x, y:-pt.y};
  }
  // ****** calculate coords of section junctions
  fillet = {x:inv[6].x, y:inv[6].y};    // top of fillet, front of tooth
  tip = toCartesian(Ra, -pitchAngle/4+tipToPitchAngle);  // tip, front of tooth
  tipR = {x:tip.x, y:-tip.y};  // addendum, back of tooth
  rootR = toCartesian(Rroot, pitchAngle/4+pitchToFilletAngle+filletAngle);
  rootNext = toCartesian(Rroot, 3*pitchAngle/4-pitchToFilletAngle-filletAngle);
  filletNext = rotate(fillet, pitchAngle);  // top of fillet, front of next tooth
  // ****** create the drawing command data array for the tooth
  data = [];
  data.push("M", inv[6].x, inv[6].y);  // start at top of front profile
  data.push("C", inv[5].x, inv[5].y, inv[4].x, inv[4].y, inv[3].x, inv[3].y,
                 inv[2].x, inv[2].y, inv[1].x, inv[1].y, inv[0].x, inv[0].y);
  if (Ra < Rb)
  {
    data.push("L", tip.x, tip.y);  // line from end of involute to addendum (tip)
  }
  data.push("A", Ra, Ra, 0, 0, 0, tipR.x, tipR.y); // arc across tip circle
  if (Ra < Rb)
  {
    data.push("L", invR[0].x, invR[0].y);  // line from addendum to start of involute
  }
  data.push("C", invR[1].x, invR[1].y, invR[2].x, invR[2].y, invR[3].x, invR[3].y,
                 invR[4].x, invR[4].y, invR[5].x, invR[5].y, invR[6].x, invR[6].y);
  if (rootR.y < rootNext.y)    // there is a section of root circle between fillets
  {
    data.push("A", fRad, fRad, 0, 0, 0, rootR.x, rootR.y); // fillet on back of tooth
    data.push("A", Rroot, Rroot, 0, 0, 0, rootNext.x, rootNext.y); // root circle arc
  }
  data.push("A", fRad, fRad, 0, 0, 0, filletNext.x, filletNext.y); // fillet on next

  return data;  // return an array of Cango (SVG) format draw commands
};

}());

module.exports = {
  create_gear_tooth: createGearTooth,
  create_internal_gear_tooth: createIntGearTooth
};

},{}],"gloo2":[function(require,module,exports){
/* 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 Buffer, GlooObject, IndexBuffer, Program, Texture2D, VertexBuffer, check_error;
    // PyScript module for gloo.js
    // Lightweight gloo

    check_error = function (gl, when) {
        var dummy1_sequence, dummy2_iter, dummy3_length, e, err, err_3, errors, msg;
        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 ((err == gl.NO_ERROR) || (errors && (err == (errors[errors.length -1])))) {
                break;
            }
            (errors.append || errors.push).apply(errors, [err]);
        }
        if (errors.length) {
            msg = '';
            dummy1_sequence = errors;
            if ((typeof dummy1_sequence === "object") && (!Array.isArray(dummy1_sequence))) {
                dummy1_sequence = Object.keys(dummy1_sequence);
            }
            dummy3_length = dummy1_sequence.length;
            for (dummy2_iter = 0; dummy2_iter < dummy3_length; dummy2_iter += 1) {
                e = dummy1_sequence[dummy2_iter];
                msg += e
            }
            err_3 = new Error('RuntimeError:' + ('OpenGL got errors (' + when + '): ' + msg + '')); err_3.name = "RuntimeError"; throw err_3;
        }
    };

    GlooObject = function () {
        // Abstract base class for all Gloo classes.
        if (this.__init__) {
           this.__init__.apply(this, arguments);
        }
    };
    GlooObject.prototype._base_class = Object;
    

    GlooObject.prototype.__init__ = function (gl) {
        this._gl = gl;
        this._handle = null;
        this._create();
        if (!(this._handle !== null)) {throw "AssertionError: this._handle !== null";}
    };

    GlooObject.prototype._create = function () {
        var err_2;
        err_2 = new Error('NotImplementedError:' + ""); err_2.name = "NotImplementedError"; throw err_2;
    };


    Program = function () {
        // The program.
        // combines vertex and fragment shader
        if (this.__init__) {
           this.__init__.apply(this, arguments);
        }
    };
    Program.prototype = Object.create(GlooObject.prototype);
    Program.prototype._base_class = GlooObject.prototype;
    

    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._handles = [];
        this._unset_variables = [];
        this._validated = false;
        this._samplers = {};
        this._attributes = {};
        this._known_invalid = [];
    };

    Program.prototype.delete = function () {
        this._gl.deleteProgram(this._handle);
    };

    Program.prototype.activate = function () {
        this._gl.useProgram(this._handle);
    };

    Program.prototype.deactivate = function () {
        this._gl.useProgram(0);
    };

    Program.prototype.set_shaders = function (vert, frag) {
        var code, dummy4_, err_3, err_4, errors, frag_handle, gl, handle, i, status, tmp, type_, vert_handle;
        // This function takes care of setting the shading code and
        // compiling+linking it into a working program object that is ready
        // to use.
        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) {
            dummy4_ = tmp[i];
            code = dummy4_[0];handle = dummy4_[1];type_ = dummy4_[2];
            gl.shaderSource(handle, code);
            gl.compileShader(handle);
            status = gl.getShaderParameter(handle, gl.COMPILE_STATUS);
            if (!status) {
                errors = gl.getShaderInfoLog(handle);
                err_4 = new Error('RuntimeError:' + ((('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 (!(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;
        }
        gl.detachShader(this._handle, vert_handle);
        gl.detachShader(this._handle, frag_handle);
        gl.deleteShader(vert_handle);
        gl.deleteShader(frag_handle);
        this._unset_variables = this._get_active_attributes_and_uniforms();
        this._handles = {};
        this._known_invalid = [];
        this._linked = true;
    };

    Program.prototype._get_active_attributes_and_uniforms = function () {
        var attributes, ca, container, count, cu, dummy10_iter, dummy11_length, dummy12_sequence, dummy13_iter, dummy14_length, dummy5_, dummy6_sequence, dummy7_iter, dummy8_length, dummy9_sequence, func, gl, i, info, m, name, regex, uniforms, v, x;
        // Retrieve active attributes and uniforms to be able to check that
        // all uniforms/attributes are set by the user.
        gl = this._gl;
        regex = new RegExp('(\\w+)\\s*(\\[(\\d+)\\])\\s*');
        cu = gl.getProgramParameter(this._handle, gl.ACTIVE_UNIFORMS);
        ca = gl.getProgramParameter(this._handle, gl.ACTIVE_ATTRIBUTES);
        attributes = [];
        uniforms = [];
        dummy6_sequence = [[attributes, ca, gl.getActiveAttrib], [uniforms, cu, gl.getActiveUniform]];
        if ((typeof dummy6_sequence === "object") && (!Array.isArray(dummy6_sequence))) {
            dummy6_sequence = Object.keys(dummy6_sequence);
        }
        dummy8_length = dummy6_sequence.length;
        for (dummy7_iter = 0; dummy7_iter < dummy8_length; dummy7_iter += 1) {
            x = dummy6_sequence[dummy7_iter];
            dummy5_ = x;
            container = dummy5_[0];count = dummy5_[1];func = dummy5_[2];
            for (i = 0; i < count; i += 1) {
                info = func.call(gl, this._handle, i);
                name = info.name;
                m = name.match(regex);
                if (m) {
                    name = m.group(0);
                    for (i = 0; i < info.size; i += 1) {
                        (container.append || container.push).apply(container, [['' + name + '[' + i + ']', info.type]]);
                    }
                } else {
                    (container.append || container.push).apply(container, [[name, info.type]]);
                }
            }
        }
        x = [];
        dummy9_sequence = attributes;
        if ((typeof dummy9_sequence === "object") && (!Array.isArray(dummy9_sequence))) {
            dummy9_sequence = Object.keys(dummy9_sequence);
        }
        dummy11_length = dummy9_sequence.length;
        for (dummy10_iter = 0; dummy10_iter < dummy11_length; dummy10_iter += 1) {
            v = dummy9_sequence[dummy10_iter];
            (x.append || x.push).apply(x, [v[0]]);
        }
        dummy12_sequence = uniforms;
        if ((typeof dummy12_sequence === "object") && (!Array.isArray(dummy12_sequence))) {
            dummy12_sequence = Object.keys(dummy12_sequence);
        }
        dummy14_length = dummy12_sequence.length;
        for (dummy13_iter = 0; dummy13_iter < dummy14_length; dummy13_iter += 1) {
            v = dummy12_sequence[dummy13_iter];
            (x.append || x.push).apply(x, [v[0]]);
        }
        return x;
    };

    Program.prototype.set_texture = function (name, value) {
        var dummy15_, dummy16_, dummy17_, dummy18_, err_3, handle, unit;
        // Set a texture sampler. Value is the id of the texture to link.
        if (!this._linked) {
            err_3 = new Error('RuntimeError:' + 'Cannot set uniform when program has no code'); err_3.name = "RuntimeError"; throw err_3;
        }
        handle = (/*py-dict.get*/typeof (dummy15_=this._handles).get==="function" ? dummy15_.get(name, -1) : (dummy15_[name] || (-1)));
        if (handle < 0) {
            if (((dummy16_ = this._known_invalid).indexOf ? dummy16_ : Object.keys(dummy16_)).indexOf(name) >= 0) {
                return;
            }
            handle = this._gl.getUniformLocation(this._handle, name);
            if (((dummy17_ = this._unset_variables).indexOf ? dummy17_ : Object.keys(dummy17_)).indexOf(name) >= 0) {
                (this._unset_variables.remove || function (x) {this.splice(this.indexOf(x), 1);}).apply(this._unset_variables, [name]);
            }
            this._handles[name] = handle;
            if (handle < 0) {
                (this._known_invalid.append || this._known_invalid.push).apply(this._known_invalid, [name]);
                console.log(('Variable ' + name + ' is not an active uniform'));
                return;
            }
        }
        this.activate();
        if (true) {
            unit = (Object.keys(this._samplers)).length;
            if (((dummy18_ = this._samplers).indexOf ? dummy18_ : Object.keys(dummy18_)).indexOf(name) >= 0) {
                unit = this._samplers[name][(this._samplers[name]).length -1];
            }
            this._samplers[name] = [value._target, value._handle, unit];
            this._gl.uniform1i(handle, unit);
        }
    };

    Program.prototype.set_uniform = function (name, type_, value) {
        var count, dummy19_, dummy20_, dummy21_, dummy22_, dummy23_, err_3, funcname, handle, ii, name_;
        // Set a uniform value. Value is assumed to have been checked.
        if (!this._linked) {
            err_3 = new Error('RuntimeError:' + 'Cannot set uniform when program has no code'); err_3.name = "RuntimeError"; throw err_3;
        }
        handle = (/*py-dict.get*/typeof (dummy19_=this._handles).get==="function" ? dummy19_.get(name, -1) : (dummy19_[name] || (-1)));
        count = 1;
        if (handle < 0) {
            if (((dummy20_ = this._known_invalid).indexOf ? dummy20_ : Object.keys(dummy20_)).indexOf(name) >= 0) {
                return;
            }
            handle = this._gl.getUniformLocation(this._handle, name);
            if (((dummy21_ = this._unset_variables).indexOf ? dummy21_ : Object.keys(dummy21_)).indexOf(name) >= 0) {
                (this._unset_variables.remove || function (x) {this.splice(this.indexOf(x), 1);}).apply(this._unset_variables, [name]);
            }
            if (!(type_.indexOf('mat') == 0)) {
                count = Math.floor(value.length/(this.ATYPEINFO[type_][0]));
            }
            if (count > 1) {
                for (ii = 0; ii < count; ii += 1) {
                    if (((dummy22_ = this._unset_variables).indexOf ? dummy22_ : Object.keys(dummy22_)).indexOf(('' + name + '[' + ii + ']')) >= 0) {
                        name_ = '' + name + '[' + ii + ']';
                        if (((dummy23_ = this._unset_variables).indexOf ? dummy23_ : Object.keys(dummy23_)).indexOf(name_) >= 0) {
                            (this._unset_variables.remove || function (x) {this.splice(this.indexOf(x), 1);}).apply(this._unset_variables, [name_]);
                        }
                    }
                }
            }
            this._handles[name] = handle;
            if (handle < 0) {
                this._known_invalid.add(name);
                logger.info('Variable ' + name + ' is not an active uniform');
                return;
            }
        }
        funcname = this.UTYPEMAP[type_];
        this.activate();
        (this._gl[funcname])(handle, value);
    };

    Program.prototype.set_attribute = function (name, type_, vbo_info, value) {
        var args, dummy24_, dummy25_, dummy26_, dummy27_, dummy28_, err_3, funcname, gtype, handle, offset, size, stride, vbo;
        value = (value === undefined) ? null: value;
        // Set an attribute value. vbo_info is (vbo, stride, offset).
        // It can also be null, in which case value must be an array with
        // the actual values to apply to all vertices (as in a uniform).
        if (!this._linked) {
            err_3 = new Error('RuntimeError:' + 'Cannot set attribute when program has no code'); err_3.name = "RuntimeError"; throw err_3;
        }
        handle = (/*py-dict.get*/typeof (dummy24_=this._handles).get==="function" ? dummy24_.get(name, -1) : (dummy24_[name] || (-1)));
        if (handle < 0) {
            if (((dummy25_ = this._known_invalid).indexOf ? dummy25_ : Object.keys(dummy25_)).indexOf(name) >= 0) {
                return;
            }
            handle = this._gl.getAttribLocation(this._handle, name);
            if (((dummy26_ = this._unset_variables).indexOf ? dummy26_ : Object.keys(dummy26_)).indexOf(name) >= 0) {
                (this._unset_variables.remove || function (x) {this.splice(this.indexOf(x), 1);}).apply(this._unset_variables, [name]);
            }
            this._handles[name] = handle;
            if (handle < 0) {
                (this._known_invalid.append || this._known_invalid.push).apply(this._known_invalid, [name]);
                if (vbo_info && ((vbo_info[0]) != 0) && ((vbo_info[2]) > 0)) {
                    return;
                }
                console.log(('Variable ' + name + ' is not an active attribute'));
                return;
            }
        }
        this.activate();
        if (vbo_info === null) {
            funcname = this.ATYPEMAP[type_];
            this._attributes[name] = [0, handle, funcname, value];
        } else {
            dummy27_ = vbo_info;
            vbo = dummy27_[0];stride = dummy27_[1];offset = dummy27_[2];
            dummy28_ = this.ATYPEINFO[type_];
            size = dummy28_[0];gtype = dummy28_[1];
            funcname = 'vertexAttribPointer';
            args = [size, gtype, this._gl.FALSE, stride, offset];
            this._attributes[name] = [vbo._handle, handle, funcname, args];
        }
    };

    Program.prototype._pre_draw = function () {
        var args, attr_handle, dummy29_, dummy30_sequence, dummy31_, dummy32_sequence, funcname, tex_handle, tex_target, unit, vbo_handle, x;
        this.activate();
        dummy30_sequence = this._samplers;
        for (x in dummy30_sequence) {
            if (!dummy30_sequence.hasOwnProperty(x)){ continue; }
            x = dummy30_sequence[x];
            dummy29_ = x;
            tex_target = dummy29_[0];tex_handle = dummy29_[1];unit = dummy29_[2];
            this._gl.activeTexture(this._gl.TEXTURE0 + unit);
            this._gl.bindTexture(tex_target, tex_handle);
        }
        dummy32_sequence = this._attributes;
        for (x in dummy32_sequence) {
            if (!dummy32_sequence.hasOwnProperty(x)){ continue; }
            x = dummy32_sequence[x];
            dummy31_ = x;
            vbo_handle = dummy31_[0];attr_handle = dummy31_[1];funcname = dummy31_[2];args = dummy31_[3];
            if (vbo_handle) {
                this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo_handle);
                this._gl.enableVertexAttribArray(attr_handle);
                (this._gl[funcname]).apply(this._gl, [attr_handle].concat(args));
            } else {
                this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
                this._gl.disableVertexAttribArray(attr_handle);
                (this._gl[funcname]).apply(this._gl, [attr_handle].concat(args));
            }
        }
        if (!this._validated) {
            this._validated = true;
            this._validate();
        }
    };

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

    Program.prototype.draw = function (mode, selection) {
        var count, dummy33_, e, err_3, first, gtype;
        // Draw program in given mode, with given selection (IndexBuffer or
        // first, count).
        if (!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 (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 {
            dummy33_ = selection;
            first = dummy33_[0];count = dummy33_[1];
            if (count) {
                this._pre_draw();
                this._gl.drawArrays(mode, first, count);
            }
        }
        e = this._gl.getError();
        check_error(this._gl, 'after draw');
    };


    Buffer = function () {
        if (this.__init__) {
           this.__init__.apply(this, arguments);
        }
    };
    Buffer.prototype = Object.create(GlooObject.prototype);
    Buffer.prototype._base_class = GlooObject.prototype;
    

    Buffer.prototype._target = null;
    Buffer.prototype._usage = 35048;
    Buffer.prototype._create = function () {
        this._handle = this._gl.createBuffer();
        this._buffer_size = 0;
    };

    Buffer.prototype.delete = function () {
        this._gl.deleteBuffer(this._handle);
    };

    Buffer.prototype.activate = function () {
        this._gl.bindBuffer(this._target, this._handle);
    };

    Buffer.prototype.deactivate = function () {
        this._gl.bindBuffer(this._target, null);
    };

    Buffer.prototype.set_size = function (nbytes) {
        if (nbytes != this._buffer_size) {
            this.activate();
            this._gl.bufferData(this._target, nbytes, this._usage);
            this._buffer_size = nbytes;
        }
    };

    Buffer.prototype.set_data = function (offset, data) {
        var nbytes;
        this.activate();
        nbytes = data.length * data.BYTES_PER_ELEMENT;
        this._gl.bufferSubData(this._target, offset, data);
    };


    VertexBuffer = function () {
        if (this.__init__) {
           this.__init__.apply(this, arguments);
        }
    };
    VertexBuffer.prototype = Object.create(Buffer.prototype);
    VertexBuffer.prototype._base_class = Buffer.prototype;
    

    VertexBuffer.prototype._target = 34962;

    IndexBuffer = function () {
        if (this.__init__) {
           this.__init__.apply(this, arguments);
        }
    };
    IndexBuffer.prototype = Object.create(Buffer.prototype);
    IndexBuffer.prototype._base_class = Buffer.prototype;
    

    IndexBuffer.prototype._target = 34963;

    Texture2D = function () {
        if (this.__init__) {
           this.__init__.apply(this, arguments);
        }
    };
    Texture2D.prototype = Object.create(GlooObject.prototype);
    Texture2D.prototype._base_class = GlooObject.prototype;
    

    Texture2D.prototype._target = 3553;
    Texture2D.prototype._types = {'Int8Array': 5120, 'Uint8Array': 5121, 'Int16Array': 5122, 'Uint16Array': 5123, 'Int32Array': 5124, 'Int32Array': 5125, 'Float32Array': 5126};
    Texture2D.prototype._create = function () {
        this._handle = this._gl.createTexture();
        this._shape_format = null;
    };

    Texture2D.prototype.delete = function () {
        this._gl.deleteTexture(this._handle);
    };

    Texture2D.prototype.activate = function () {
        this._gl.bindTexture(this._target, this._handle);
    };

    Texture2D.prototype.deactivate = function () {
        this._gl.bindTexture(this._target, 0);
    };

    Texture2D.prototype._get_alignment = function (width) {
        var alignment, alignments, dummy34_sequence, dummy35_iter, dummy36_length;
        // 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];
        dummy34_sequence = alignments;
        if ((typeof dummy34_sequence === "object") && (!Array.isArray(dummy34_sequence))) {
            dummy34_sequence = Object.keys(dummy34_sequence);
        }
        dummy36_length = dummy34_sequence.length;
        for (dummy35_iter = 0; dummy35_iter < dummy36_length; dummy35_iter += 1) {
            alignment = dummy34_sequence[dummy35_iter];
            if ((width % alignment) == 0) {
                return alignment;
            }
        }
    };

    Texture2D.prototype.set_wrapping = function (wrap_s, wrap_t) {
        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);
    };

    Texture2D.prototype.set_interpolation = function (min, mag) {
        this.activate();
        this._gl.texParameterf(this._target, this._gl.TEXTURE_MIN_FILTER, min);
        this._gl.texParameterf(this._target, this._gl.TEXTURE_MAG_FILTER, mag);
    };

    Texture2D.prototype.set_size = function (shape, format) {
        var dummy37_, height, width;
        dummy37_ = shape;
        height = dummy37_[0];width = dummy37_[1];
        if (([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);
        }
    };

    Texture2D.prototype.set_data = function (offset, shape, data) {
        var alignment, dummy38_, dummy39_, dummy40_, err_3, format, gtype, height, width, x, y;
        this.activate();
        format = this._shape_format[2];
        dummy38_ = shape;
        height = dummy38_[0];width = dummy38_[1];
        dummy39_ = offset;
        y = dummy39_[0];x = dummy39_[1];
        gtype = (/*py-dict.get*/typeof (dummy40_=this._types).get==="function" ? dummy40_.get(data.constructor.name, null) : (dummy40_[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((shape[shape.length -2]) * (shape[shape.length -1]));
        if (alignment != 4) {
            this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, alignment);
        }
        this._gl.texSubImage2D(this._target, 0, x, y, width, height, format, gtype, data);
        if (alignment != 4) {
            this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 4);
        }
    };


    return {'Buffer': Buffer, 'GlooObject': GlooObject, 'IndexBuffer': IndexBuffer, 'Program': Program, 'Texture2D': Texture2D, 'VertexBuffer': VertexBuffer, 'check_error': check_error};
}));

},{}],"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("unsatifiable 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)) {
                    throw new Error("unsatisfiable constraint");
                }
            } 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

},{}],"numeral":[function(require,module,exports){
/*!
 * numeral.js
 * version : 1.5.3
 * author : Adam Draper
 * license : MIT
 * http://adamwdraper.github.com/Numeral-js/
 */

var _ = require("underscore");

    var languages = {};
    var defaultFormat = '0,0';
    var defaultLanguage = 'en';

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

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

    // determine what type of formatting we need to do
    function formatNumeral(value, format, language, roundingFunction) {
        var output;

        // figure out what kind of format we are dealing with
        if (format.indexOf('$') > -1) { // currency!!!!!
            output = formatCurrency(value, format, language, roundingFunction);
        } else if (format.indexOf('%') > -1) { // percentage
            output = formatPercentage(value, format, language, roundingFunction);
        } else if (format.indexOf(':') > -1) { // time
            output = formatTime(value, format, language);
        } else { // plain ol' numbers or bytes
            output = formatNumber(value, format, language, roundingFunction);
        }

        return output;
    }

    function formatCurrency(value, format, language, roundingFunction) {
        var symbolIndex = format.indexOf('$'),
            openParenIndex = format.indexOf('('),
            minusSignIndex = format.indexOf('-'),
            space = '',
            spliceIndex,
            output;

        // 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, language, roundingFunction);

        // position the symbol
        if (symbolIndex <= 1) {
            if (output.indexOf('(') > -1 || output.indexOf('-') > -1) {
                output = output.split('');
                spliceIndex = 1;
                if (symbolIndex < openParenIndex || symbolIndex < minusSignIndex){
                    // the symbol appears before the "(" or "-"
                    spliceIndex = 0;
                }
                output.splice(spliceIndex, 0, language.currency.symbol + space);
                output = output.join('');
            } else {
                output = language.currency.symbol + space + output;
            }
        } else {
            if (output.indexOf(')') > -1) {
                output = output.split('');
                output.splice(-1, 0, space + language.currency.symbol);
                output = output.join('');
            } else {
                output = output + space + language.currency.symbol;
            }
        }

        return output;
    }

    function formatPercentage(value, format, language, 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, language, 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, language) {
        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, language, roundingFunction) {
        var negP = false,
            signed = false,
            optDec = false,
            abbr = '',
            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),
            suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
            min,
            max,
            power,
            w,
            precision,
            thousands,
            d = '',
            neg = false;

        // 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) {
            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) {
            // 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', '');
            }

            if (abs >= Math.pow(10, 12) && !abbrForce || abbrT) {
                // trillion
                abbr = abbr + language.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 + language.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 + language.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 + language.abbreviations.thousand;
                value = value / Math.pow(10, 3);
            }
        }

        // see if we are formatting 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 <= suffixes.length; power++) {
                min = Math.pow(1024, power);
                max = Math.pow(1024, power+1);

                if (value >= min && value < max) {
                    bytes = bytes + suffixes[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', '');
            }

            ord = ord + language.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) {
                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) {
                d = language.delimiters.decimal + 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 (thousands > -1) {
            w = w.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' + language.delimiters.thousands);
        }

        if (format.indexOf('.') === 0) {
            w = '';
        }

        return ((negP && neg) ? '(' : '') +
               ((!negP && neg) ? '-' : '') +
               ((!neg && signed) ? '+' : '') +
               w +
               d +
               ((ord) ? ord : '') +
               ((abbr) ? abbr : '') +
               ((bytes) ? bytes : '') +
               ((negP && neg) ? ')' : '');
    }

    function addLanguage(key, spec) {
        languages[key] = spec;
    }

    addLanguage('en', {
        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: '$'
        }
    });

    function format(input, formatString, language, roundingFunction) {
        return formatNumeral(
            Number(input),
            _.isString(formatString)        ? formatString        : defaultFormat,
            _.isString(language)            ? languages[language] : languages[defaultLanguage],
            _.isUndefined(roundingFunction) ? Math.round          : roundingFunction);
    }

    module.exports = {"format": format};

},{"underscore":"underscore"}]},{},["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
