(function (root, factory) {
  root.Bokeh = factory();
}(this, function () {
  //almond, and your modules will be inlined here

/**
 * @license almond 0.2.9 Copyright (c) 2011-2014, The Dojo Foundation All Rights Reserved.
 * Available via the MIT or new BSD license.
 * see: http://github.com/jrburke/almond for details
 */
//Going sloppy to avoid 'use strict' string cost, but strict practices should
//be followed.
/*jslint sloppy: true */
/*global setTimeout: false */

var requirejs, require, define;
(function (undef) {
    var main, req, makeMap, handlers,
        defined = {},
        waiting = {},
        config = {},
        defining = {},
        hasOwn = Object.prototype.hasOwnProperty,
        aps = [].slice,
        jsSuffixRegExp = /\.js$/;

    function hasProp(obj, prop) {
        return hasOwn.call(obj, prop);
    }

    /**
     * Given a relative module name, like ./something, normalize it to
     * a real name that can be mapped to a path.
     * @param {String} name the relative name
     * @param {String} baseName a real name that the name arg is relative
     * to.
     * @returns {String} normalized name
     */
    function normalize(name, baseName) {
        var nameParts, nameSegment, mapValue, foundMap, lastIndex,
            foundI, foundStarMap, starI, i, j, part,
            baseParts = baseName && baseName.split("/"),
            map = config.map,
            starMap = (map && map['*']) || {};

        //Adjust any relative paths.
        if (name && name.charAt(0) === ".") {
            //If have a base name, try to normalize against it,
            //otherwise, assume it is a top-level require that will
            //be relative to baseUrl in the end.
            if (baseName) {
                //Convert baseName to array, and lop off the last part,
                //so that . matches that "directory" and not name of the baseName's
                //module. For instance, baseName of "one/two/three", maps to
                //"one/two/three.js", but we want the directory, "one/two" for
                //this normalization.
                baseParts = baseParts.slice(0, baseParts.length - 1);
                name = name.split('/');
                lastIndex = name.length - 1;

                // Node .js allowance:
                if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
                    name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
                }

                name = baseParts.concat(name);

                //start trimDots
                for (i = 0; i < name.length; i += 1) {
                    part = name[i];
                    if (part === ".") {
                        name.splice(i, 1);
                        i -= 1;
                    } else if (part === "..") {
                        if (i === 1 && (name[2] === '..' || name[0] === '..')) {
                            //End of the line. Keep at least one non-dot
                            //path segment at the front so it can be mapped
                            //correctly to disk. Otherwise, there is likely
                            //no path mapping for a path starting with '..'.
                            //This can still fail, but catches the most reasonable
                            //uses of ..
                            break;
                        } else if (i > 0) {
                            name.splice(i - 1, 2);
                            i -= 2;
                        }
                    }
                }
                //end trimDots

                name = name.join("/");
            } else if (name.indexOf('./') === 0) {
                // No baseName, so this is ID is resolved relative
                // to baseUrl, pull off the leading dot.
                name = name.substring(2);
            }
        }

        //Apply map config if available.
        if ((baseParts || starMap) && map) {
            nameParts = name.split('/');

            for (i = nameParts.length; i > 0; i -= 1) {
                nameSegment = nameParts.slice(0, i).join("/");

                if (baseParts) {
                    //Find the longest baseName segment match in the config.
                    //So, do joins on the biggest to smallest lengths of baseParts.
                    for (j = baseParts.length; j > 0; j -= 1) {
                        mapValue = map[baseParts.slice(0, j).join('/')];

                        //baseName segment has  config, find if it has one for
                        //this name.
                        if (mapValue) {
                            mapValue = mapValue[nameSegment];
                            if (mapValue) {
                                //Match, update name to the new value.
                                foundMap = mapValue;
                                foundI = i;
                                break;
                            }
                        }
                    }
                }

                if (foundMap) {
                    break;
                }

                //Check for a star map match, but just hold on to it,
                //if there is a shorter segment match later in a matching
                //config, then favor over this star map.
                if (!foundStarMap && starMap && starMap[nameSegment]) {
                    foundStarMap = starMap[nameSegment];
                    starI = i;
                }
            }

            if (!foundMap && foundStarMap) {
                foundMap = foundStarMap;
                foundI = starI;
            }

            if (foundMap) {
                nameParts.splice(0, foundI, foundMap);
                name = nameParts.join('/');
            }
        }

        return name;
    }

    function makeRequire(relName, forceSync) {
        return function () {
            //A version of a require function that passes a moduleName
            //value for items that may need to
            //look up paths relative to the moduleName
            return req.apply(undef, aps.call(arguments, 0).concat([relName, forceSync]));
        };
    }

    function makeNormalize(relName) {
        return function (name) {
            return normalize(name, relName);
        };
    }

    function makeLoad(depName) {
        return function (value) {
            defined[depName] = value;
        };
    }

    function callDep(name) {
        if (hasProp(waiting, name)) {
            var args = waiting[name];
            delete waiting[name];
            defining[name] = true;
            main.apply(undef, args);
        }

        if (!hasProp(defined, name) && !hasProp(defining, name)) {
            throw new Error('No ' + name);
        }
        return defined[name];
    }

    //Turns a plugin!resource to [plugin, resource]
    //with the plugin being undefined if the name
    //did not have a plugin prefix.
    function splitPrefix(name) {
        var prefix,
            index = name ? name.indexOf('!') : -1;
        if (index > -1) {
            prefix = name.substring(0, index);
            name = name.substring(index + 1, name.length);
        }
        return [prefix, name];
    }

    /**
     * Makes a name map, normalizing the name, and using a plugin
     * for normalization if necessary. Grabs a ref to plugin
     * too, as an optimization.
     */
    makeMap = function (name, relName) {
        var plugin,
            parts = splitPrefix(name),
            prefix = parts[0];

        name = parts[1];

        if (prefix) {
            prefix = normalize(prefix, relName);
            plugin = callDep(prefix);
        }

        //Normalize according
        if (prefix) {
            if (plugin && plugin.normalize) {
                name = plugin.normalize(name, makeNormalize(relName));
            } else {
                name = normalize(name, relName);
            }
        } else {
            name = normalize(name, relName);
            parts = splitPrefix(name);
            prefix = parts[0];
            name = parts[1];
            if (prefix) {
                plugin = callDep(prefix);
            }
        }

        //Using ridiculous property names for space reasons
        return {
            f: prefix ? prefix + '!' + name : name, //fullName
            n: name,
            pr: prefix,
            p: plugin
        };
    };

    function makeConfig(name) {
        return function () {
            return (config && config.config && config.config[name]) || {};
        };
    }

    handlers = {
        require: function (name) {
            return makeRequire(name);
        },
        exports: function (name) {
            var e = defined[name];
            if (typeof e !== 'undefined') {
                return e;
            } else {
                return (defined[name] = {});
            }
        },
        module: function (name) {
            return {
                id: name,
                uri: '',
                exports: defined[name],
                config: makeConfig(name)
            };
        }
    };

    main = function (name, deps, callback, relName) {
        var cjsModule, depName, ret, map, i,
            args = [],
            callbackType = typeof callback,
            usingExports;

        //Use name if no relName
        relName = relName || name;

        //Call the callback to define the module, if necessary.
        if (callbackType === 'undefined' || callbackType === 'function') {
            //Pull out the defined dependencies and pass the ordered
            //values to the callback.
            //Default to [require, exports, module] if no deps
            deps = !deps.length && callback.length ? ['require', 'exports', 'module'] : deps;
            for (i = 0; i < deps.length; i += 1) {
                map = makeMap(deps[i], relName);
                depName = map.f;

                //Fast path CommonJS standard dependencies.
                if (depName === "require") {
                    args[i] = handlers.require(name);
                } else if (depName === "exports") {
                    //CommonJS module spec 1.1
                    args[i] = handlers.exports(name);
                    usingExports = true;
                } else if (depName === "module") {
                    //CommonJS module spec 1.1
                    cjsModule = args[i] = handlers.module(name);
                } else if (hasProp(defined, depName) ||
                           hasProp(waiting, depName) ||
                           hasProp(defining, depName)) {
                    args[i] = callDep(depName);
                } else if (map.p) {
                    map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {});
                    args[i] = defined[depName];
                } else {
                    throw new Error(name + ' missing ' + depName);
                }
            }

            ret = callback ? callback.apply(defined[name], args) : undefined;

            if (name) {
                //If setting exports via "module" is in play,
                //favor that over return value and exports. After that,
                //favor a non-undefined return value over exports use.
                if (cjsModule && cjsModule.exports !== undef &&
                        cjsModule.exports !== defined[name]) {
                    defined[name] = cjsModule.exports;
                } else if (ret !== undef || !usingExports) {
                    //Use the return value from the function.
                    defined[name] = ret;
                }
            }
        } else if (name) {
            //May just be an object definition for the module. Only
            //worry about defining if have a module name.
            defined[name] = callback;
        }
    };

    requirejs = require = req = function (deps, callback, relName, forceSync, alt) {
        if (typeof deps === "string") {
            if (handlers[deps]) {
                //callback in this case is really relName
                return handlers[deps](callback);
            }
            //Just return the module wanted. In this scenario, the
            //deps arg is the module name, and second arg (if passed)
            //is just the relName.
            //Normalize module name, if it contains . or ..
            return callDep(makeMap(deps, callback).f);
        } else if (!deps.splice) {
            //deps is a config object, not an array.
            config = deps;
            if (config.deps) {
                req(config.deps, config.callback);
            }
            if (!callback) {
                return;
            }

            if (callback.splice) {
                //callback is an array, which means it is a dependency list.
                //Adjust args if there are dependencies
                deps = callback;
                callback = relName;
                relName = null;
            } else {
                deps = undef;
            }
        }

        //Support require(['a'])
        callback = callback || function () {};

        //If relName is a function, it is an errback handler,
        //so remove it.
        if (typeof relName === 'function') {
            relName = forceSync;
            forceSync = alt;
        }

        //Simulate async callback;
        if (forceSync) {
            main(undef, deps, callback, relName);
        } else {
            //Using a non-zero value because of concern for what old browsers
            //do, and latest browsers "upgrade" to 4 if lower value is used:
            //http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout:
            //If want a value immediately, use require('id') instead -- something
            //that works in almond on the global level, but not guaranteed and
            //unlikely to work in other AMD implementations.
            setTimeout(function () {
                main(undef, deps, callback, relName);
            }, 4);
        }

        return req;
    };

    /**
     * Just drops the config on the floor, but returns req in case
     * the config return value is used.
     */
    req.config = function (cfg) {
        return req(cfg);
    };

    /**
     * Expose module registry for debugging and tooling
     */
    requirejs._defined = defined;

    define = function (name, deps, callback) {

        //This module may not have dependencies
        if (!deps.splice) {
            //deps is not an array, so probably means
            //an object literal or factory function for
            //the value. Adjust args.
            callback = deps;
            deps = [];
        }

        if (!hasProp(defined, name) && !hasProp(waiting, name)) {
            waiting[name] = [name, deps, callback];
        }
    };

    define.amd = {
        jQuery: true
    };
}());

define("vendor/almond/almond", function(){});

//     Underscore.js 1.5.2
//     http://underscorejs.org
//     (c) 2009-2013 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._;

  // Establish the object that gets returned to break out of a loop iteration.
  var breaker = {};

  // 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,
    concat           = ArrayProto.concat,
    toString         = ObjProto.toString,
    hasOwnProperty   = ObjProto.hasOwnProperty;

  // All **ECMAScript 5** native function implementations that we hope to use
  // are declared here.
  var
    nativeForEach      = ArrayProto.forEach,
    nativeMap          = ArrayProto.map,
    nativeReduce       = ArrayProto.reduce,
    nativeReduceRight  = ArrayProto.reduceRight,
    nativeFilter       = ArrayProto.filter,
    nativeEvery        = ArrayProto.every,
    nativeSome         = ArrayProto.some,
    nativeIndexOf      = ArrayProto.indexOf,
    nativeLastIndexOf  = ArrayProto.lastIndexOf,
    nativeIsArray      = Array.isArray,
    nativeKeys         = Object.keys,
    nativeBind         = FuncProto.bind;

  // 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 via a string identifier,
  // for Closure Compiler "advanced" mode.
  if (typeof exports !== 'undefined') {
    if (typeof module !== 'undefined' && module.exports) {
      exports = module.exports = _;
    }
    exports._ = _;
  } else {
    root._ = _;
  }

  // Current version.
  _.VERSION = '1.5.2';

  // Collection Functions
  // --------------------

  // The cornerstone, an `each` implementation, aka `forEach`.
  // Handles objects with the built-in `forEach`, arrays, and raw objects.
  // Delegates to **ECMAScript 5**'s native `forEach` if available.
  var each = _.each = _.forEach = function(obj, iterator, context) {
    if (obj == null) return;
    if (nativeForEach && obj.forEach === nativeForEach) {
      obj.forEach(iterator, context);
    } else if (obj.length === +obj.length) {
      for (var i = 0, length = obj.length; i < length; i++) {
        if (iterator.call(context, obj[i], i, obj) === breaker) return;
      }
    } else {
      var keys = _.keys(obj);
      for (var i = 0, length = keys.length; i < length; i++) {
        if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return;
      }
    }
  };

  // Return the results of applying the iterator to each element.
  // Delegates to **ECMAScript 5**'s native `map` if available.
  _.map = _.collect = function(obj, iterator, context) {
    var results = [];
    if (obj == null) return results;
    if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
    each(obj, function(value, index, list) {
      results.push(iterator.call(context, value, index, list));
    });
    return results;
  };

  var reduceError = 'Reduce of empty array with no initial value';

  // **Reduce** builds up a single result from a list of values, aka `inject`,
  // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
  _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
    var initial = arguments.length > 2;
    if (obj == null) obj = [];
    if (nativeReduce && obj.reduce === nativeReduce) {
      if (context) iterator = _.bind(iterator, context);
      return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
    }
    each(obj, function(value, index, list) {
      if (!initial) {
        memo = value;
        initial = true;
      } else {
        memo = iterator.call(context, memo, value, index, list);
      }
    });
    if (!initial) throw new TypeError(reduceError);
    return memo;
  };

  // The right-associative version of reduce, also known as `foldr`.
  // Delegates to **ECMAScript 5**'s native `reduceRight` if available.
  _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
    var initial = arguments.length > 2;
    if (obj == null) obj = [];
    if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
      if (context) iterator = _.bind(iterator, context);
      return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
    }
    var length = obj.length;
    if (length !== +length) {
      var keys = _.keys(obj);
      length = keys.length;
    }
    each(obj, function(value, index, list) {
      index = keys ? keys[--length] : --length;
      if (!initial) {
        memo = obj[index];
        initial = true;
      } else {
        memo = iterator.call(context, memo, obj[index], index, list);
      }
    });
    if (!initial) throw new TypeError(reduceError);
    return memo;
  };

  // Return the first value which passes a truth test. Aliased as `detect`.
  _.find = _.detect = function(obj, iterator, context) {
    var result;
    any(obj, function(value, index, list) {
      if (iterator.call(context, value, index, list)) {
        result = value;
        return true;
      }
    });
    return result;
  };

  // Return all the elements that pass a truth test.
  // Delegates to **ECMAScript 5**'s native `filter` if available.
  // Aliased as `select`.
  _.filter = _.select = function(obj, iterator, context) {
    var results = [];
    if (obj == null) return results;
    if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
    each(obj, function(value, index, list) {
      if (iterator.call(context, value, index, list)) results.push(value);
    });
    return results;
  };

  // Return all the elements for which a truth test fails.
  _.reject = function(obj, iterator, context) {
    return _.filter(obj, function(value, index, list) {
      return !iterator.call(context, value, index, list);
    }, context);
  };

  // Determine whether all of the elements match a truth test.
  // Delegates to **ECMAScript 5**'s native `every` if available.
  // Aliased as `all`.
  _.every = _.all = function(obj, iterator, context) {
    iterator || (iterator = _.identity);
    var result = true;
    if (obj == null) return result;
    if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
    each(obj, function(value, index, list) {
      if (!(result = result && iterator.call(context, value, index, list))) return breaker;
    });
    return !!result;
  };

  // Determine if at least one element in the object matches a truth test.
  // Delegates to **ECMAScript 5**'s native `some` if available.
  // Aliased as `any`.
  var any = _.some = _.any = function(obj, iterator, context) {
    iterator || (iterator = _.identity);
    var result = false;
    if (obj == null) return result;
    if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
    each(obj, function(value, index, list) {
      if (result || (result = iterator.call(context, value, index, list))) return breaker;
    });
    return !!result;
  };

  // Determine if the array or object contains a given value (using `===`).
  // Aliased as `include`.
  _.contains = _.include = function(obj, target) {
    if (obj == null) return false;
    if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
    return any(obj, function(value) {
      return value === target;
    });
  };

  // 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) {
      return (isFunc ? method : value[method]).apply(value, args);
    });
  };

  // Convenience version of a common use case of `map`: fetching a property.
  _.pluck = function(obj, key) {
    return _.map(obj, function(value){ return value[key]; });
  };

  // Convenience version of a common use case of `filter`: selecting only objects
  // containing specific `key:value` pairs.
  _.where = function(obj, attrs, first) {
    if (_.isEmpty(attrs)) return first ? void 0 : [];
    return _[first ? 'find' : 'filter'](obj, function(value) {
      for (var key in attrs) {
        if (attrs[key] !== value[key]) return false;
      }
      return true;
    });
  };

  // Convenience version of a common use case of `find`: getting the first object
  // containing specific `key:value` pairs.
  _.findWhere = function(obj, attrs) {
    return _.where(obj, attrs, true);
  };

  // Return the maximum element or (element-based computation).
  // Can't optimize arrays of integers longer than 65,535 elements.
  // See [WebKit Bug 80797](https://bugs.webkit.org/show_bug.cgi?id=80797)
  _.max = function(obj, iterator, context) {
    if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
      return Math.max.apply(Math, obj);
    }
    if (!iterator && _.isEmpty(obj)) return -Infinity;
    var result = {computed : -Infinity, value: -Infinity};
    each(obj, function(value, index, list) {
      var computed = iterator ? iterator.call(context, value, index, list) : value;
      computed > result.computed && (result = {value : value, computed : computed});
    });
    return result.value;
  };

  // Return the minimum element (or element-based computation).
  _.min = function(obj, iterator, context) {
    if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
      return Math.min.apply(Math, obj);
    }
    if (!iterator && _.isEmpty(obj)) return Infinity;
    var result = {computed : Infinity, value: Infinity};
    each(obj, function(value, index, list) {
      var computed = iterator ? iterator.call(context, value, index, list) : value;
      computed < result.computed && (result = {value : value, computed : computed});
    });
    return result.value;
  };

  // Shuffle an array, using the modern version of the 
  // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
  _.shuffle = function(obj) {
    var rand;
    var index = 0;
    var shuffled = [];
    each(obj, function(value) {
      rand = _.random(index++);
      shuffled[index - 1] = shuffled[rand];
      shuffled[rand] = value;
    });
    return shuffled;
  };

  // Sample **n** random values from an array.
  // If **n** is not specified, returns a single random element from the array.
  // The internal `guard` argument allows it to work with `map`.
  _.sample = function(obj, n, guard) {
    if (arguments.length < 2 || guard) {
      return obj[_.random(obj.length - 1)];
    }
    return _.shuffle(obj).slice(0, Math.max(0, n));
  };

  // An internal function to generate lookup iterators.
  var lookupIterator = function(value) {
    return _.isFunction(value) ? value : function(obj){ return obj[value]; };
  };

  // Sort the object's values by a criterion produced by an iterator.
  _.sortBy = function(obj, value, context) {
    var iterator = lookupIterator(value);
    return _.pluck(_.map(obj, function(value, index, list) {
      return {
        value: value,
        index: index,
        criteria: iterator.call(context, 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, value, context) {
      var result = {};
      var iterator = value == null ? _.identity : lookupIterator(value);
      each(obj, function(value, index) {
        var key = iterator.call(context, value, index, obj);
        behavior(result, key, value);
      });
      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, key, value) {
    (_.has(result, key) ? result[key] : (result[key] = [])).push(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, key, value) {
    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, key) {
    _.has(result, key) ? result[key]++ : result[key] = 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, iterator, context) {
    iterator = iterator == null ? _.identity : lookupIterator(iterator);
    var value = iterator.call(context, obj);
    var low = 0, high = array.length;
    while (low < high) {
      var mid = (low + high) >>> 1;
      iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
    }
    return low;
  };

  // Safely create a real, live array from anything iterable.
  _.toArray = function(obj) {
    if (!obj) return [];
    if (_.isArray(obj)) return slice.call(obj);
    if (obj.length === +obj.length) return _.map(obj, _.identity);
    return _.values(obj);
  };

  // Return the number of elements in an object.
  _.size = function(obj) {
    if (obj == null) return 0;
    return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;
  };

  // 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;
    return (n == null) || guard ? array[0] : slice.call(array, 0, 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. The **guard** check allows it to work with
  // `_.map`.
  _.initial = function(array, n, guard) {
    return slice.call(array, 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. The **guard** check allows it to work with `_.map`.
  _.last = function(array, n, guard) {
    if (array == null) return void 0;
    if ((n == null) || guard) {
      return array[array.length - 1];
    } else {
      return slice.call(array, Math.max(array.length - n, 0));
    }
  };

  // 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. The **guard**
  // check allows it to work with `_.map`.
  _.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, output) {
    if (shallow && _.every(input, _.isArray)) {
      return concat.apply(output, input);
    }
    each(input, function(value) {
      if (_.isArray(value) || _.isArguments(value)) {
        shallow ? push.apply(output, value) : flatten(value, shallow, output);
      } else {
        output.push(value);
      }
    });
    return output;
  };

  // Flatten out an array, either recursively (by default), or just one level.
  _.flatten = function(array, shallow) {
    return flatten(array, shallow, []);
  };

  // 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, iterator, context) {
    if (_.isFunction(isSorted)) {
      context = iterator;
      iterator = isSorted;
      isSorted = false;
    }
    var initial = iterator ? _.map(array, iterator, context) : array;
    var results = [];
    var seen = [];
    each(initial, function(value, index) {
      if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) {
        seen.push(value);
        results.push(array[index]);
      }
    });
    return results;
  };

  // Produce an array that contains the union: each distinct element from all of
  // the passed-in arrays.
  _.union = function() {
    return _.uniq(_.flatten(arguments, true));
  };

  // Produce an array that contains every item shared between all the
  // passed-in arrays.
  _.intersection = function(array) {
    var rest = slice.call(arguments, 1);
    return _.filter(_.uniq(array), function(item) {
      return _.every(rest, function(other) {
        return _.indexOf(other, item) >= 0;
      });
    });
  };

  // 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 = concat.apply(ArrayProto, slice.call(arguments, 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() {
    var length = _.max(_.pluck(arguments, "length").concat(0));
    var results = new Array(length);
    for (var i = 0; i < length; i++) {
      results[i] = _.pluck(arguments, '' + i);
    }
    return results;
  };

  // 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) {
    if (list == null) return {};
    var result = {};
    for (var i = 0, length = list.length; i < length; i++) {
      if (values) {
        result[list[i]] = values[i];
      } else {
        result[list[i][0]] = list[i][1];
      }
    }
    return result;
  };

  // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
  // we need this function. Return the position of the first occurrence of an
  // item in an array, or -1 if the item is not included in the array.
  // Delegates to **ECMAScript 5**'s native `indexOf` if available.
  // If the array is large and already in sort order, pass `true`
  // for **isSorted** to use binary search.
  _.indexOf = function(array, item, isSorted) {
    if (array == null) return -1;
    var i = 0, length = array.length;
    if (isSorted) {
      if (typeof isSorted == 'number') {
        i = (isSorted < 0 ? Math.max(0, length + isSorted) : isSorted);
      } else {
        i = _.sortedIndex(array, item);
        return array[i] === item ? i : -1;
      }
    }
    if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
    for (; i < length; i++) if (array[i] === item) return i;
    return -1;
  };

  // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
  _.lastIndexOf = function(array, item, from) {
    if (array == null) return -1;
    var hasIndex = from != null;
    if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
      return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
    }
    var i = (hasIndex ? from : array.length);
    while (i--) if (array[i] === item) return i;
    return -1;
  };

  // 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 (arguments.length <= 1) {
      stop = start || 0;
      start = 0;
    }
    step = arguments[2] || 1;

    var length = Math.max(Math.ceil((stop - start) / step), 0);
    var idx = 0;
    var range = new Array(length);

    while(idx < length) {
      range[idx++] = start;
      start += step;
    }

    return range;
  };

  // Function (ahem) Functions
  // ------------------

  // Reusable constructor function for prototype setting.
  var ctor = function(){};

  // 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) {
    var args, bound;
    if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
    if (!_.isFunction(func)) throw new TypeError;
    args = slice.call(arguments, 2);
    return bound = function() {
      if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
      ctor.prototype = func.prototype;
      var self = new ctor;
      ctor.prototype = null;
      var result = func.apply(self, args.concat(slice.call(arguments)));
      if (Object(result) === result) return result;
      return self;
    };
  };

  // Partially apply a function by creating a version that has had some of its
  // arguments pre-filled, without changing its dynamic `this` context.
  _.partial = function(func) {
    var args = slice.call(arguments, 1);
    return function() {
      return func.apply(this, args.concat(slice.call(arguments)));
    };
  };

  // Bind all of an object's methods to that object. Useful for ensuring that
  // all callbacks defined on an object belong to it.
  _.bindAll = function(obj) {
    var funcs = slice.call(arguments, 1);
    if (funcs.length === 0) throw new Error("bindAll must be passed function names");
    each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
    return obj;
  };

  // Memoize an expensive function by storing its results.
  _.memoize = function(func, hasher) {
    var memo = {};
    hasher || (hasher = _.identity);
    return function() {
      var key = hasher.apply(this, arguments);
      return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
    };
  };

  // 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 = function(func) {
    return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 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;
    options || (options = {});
    var later = function() {
      previous = options.leading === false ? 0 : new Date;
      timeout = null;
      result = func.apply(context, args);
    };
    return function() {
      var now = new Date;
      if (!previous && options.leading === false) previous = now;
      var remaining = wait - (now - previous);
      context = this;
      args = arguments;
      if (remaining <= 0) {
        clearTimeout(timeout);
        timeout = null;
        previous = now;
        result = func.apply(context, args);
      } 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;
    return function() {
      context = this;
      args = arguments;
      timestamp = new Date();
      var later = function() {
        var last = (new Date()) - timestamp;
        if (last < wait) {
          timeout = setTimeout(later, wait - last);
        } else {
          timeout = null;
          if (!immediate) result = func.apply(context, args);
        }
      };
      var callNow = immediate && !timeout;
      if (!timeout) {
        timeout = setTimeout(later, wait);
      }
      if (callNow) result = func.apply(context, args);
      return result;
    };
  };

  // Returns a function that will be executed at most one time, no matter how
  // often you call it. Useful for lazy initialization.
  _.once = function(func) {
    var ran = false, memo;
    return function() {
      if (ran) return memo;
      ran = true;
      memo = func.apply(this, arguments);
      func = null;
      return memo;
    };
  };

  // 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 function() {
      var args = [func];
      push.apply(args, arguments);
      return wrapper.apply(this, args);
    };
  };

  // 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 funcs = arguments;
    return function() {
      var args = arguments;
      for (var i = funcs.length - 1; i >= 0; i--) {
        args = [funcs[i].apply(this, args)];
      }
      return args[0];
    };
  };

  // Returns a function that will only be executed after being called N times.
  _.after = function(times, func) {
    return function() {
      if (--times < 1) {
        return func.apply(this, arguments);
      }
    };
  };

  // Object Functions
  // ----------------

  // Retrieve the names of an object's properties.
  // Delegates to **ECMAScript 5**'s native `Object.keys`
  _.keys = nativeKeys || function(obj) {
    if (obj !== Object(obj)) throw new TypeError('Invalid object');
    var keys = [];
    for (var key in obj) if (_.has(obj, key)) keys.push(key);
    return keys;
  };

  // Retrieve the values of an object's properties.
  _.values = function(obj) {
    var keys = _.keys(obj);
    var length = keys.length;
    var values = new Array(length);
    for (var i = 0; i < length; i++) {
      values[i] = obj[keys[i]];
    }
    return values;
  };

  // Convert an object into a list of `[key, value]` pairs.
  _.pairs = function(obj) {
    var keys = _.keys(obj);
    var length = keys.length;
    var pairs = new 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 = function(obj) {
    each(slice.call(arguments, 1), function(source) {
      if (source) {
        for (var prop in source) {
          obj[prop] = source[prop];
        }
      }
    });
    return obj;
  };

  // Return a copy of the object only containing the whitelisted properties.
  _.pick = function(obj) {
    var copy = {};
    var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
    each(keys, function(key) {
      if (key in obj) copy[key] = obj[key];
    });
    return copy;
  };

   // Return a copy of the object without the blacklisted properties.
  _.omit = function(obj) {
    var copy = {};
    var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
    for (var key in obj) {
      if (!_.contains(keys, key)) copy[key] = obj[key];
    }
    return copy;
  };

  // Fill in a given object with default properties.
  _.defaults = function(obj) {
    each(slice.call(arguments, 1), function(source) {
      if (source) {
        for (var prop in source) {
          if (obj[prop] === void 0) obj[prop] = source[prop];
        }
      }
    });
    return obj;
  };

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

  // 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, dates, and booleans are compared by value.
      case '[object String]':
        // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
        // equivalent to `new String("5")`.
        return a == String(b);
      case '[object Number]':
        // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
        // other numeric values.
        return a != +a ? b != +b : (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;
      // RegExps are compared by their source patterns and flags.
      case '[object RegExp]':
        return a.source == b.source &&
               a.global == b.global &&
               a.multiline == b.multiline &&
               a.ignoreCase == b.ignoreCase;
    }
    if (typeof a != 'object' || typeof b != 'object') 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`.
    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;
    }
    // Objects with different constructors are not equivalent, but `Object`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))) {
      return false;
    }
    // Add the first object to the stack of traversed objects.
    aStack.push(a);
    bStack.push(b);
    var size = 0, result = true;
    // Recursively compare objects and arrays.
    if (className == '[object Array]') {
      // Compare array lengths to determine if a deep comparison is necessary.
      size = a.length;
      result = size == b.length;
      if (result) {
        // Deep compare the contents, ignoring non-numeric properties.
        while (size--) {
          if (!(result = eq(a[size], b[size], aStack, bStack))) break;
        }
      }
    } else {
      // Deep compare objects.
      for (var key in a) {
        if (_.has(a, key)) {
          // Count the expected number of properties.
          size++;
          // Deep compare each member.
          if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
        }
      }
      // Ensure that both objects contain the same number of properties.
      if (result) {
        for (key in b) {
          if (_.has(b, key) && !(size--)) break;
        }
        result = !size;
      }
    }
    // Remove the first object from the stack of traversed objects.
    aStack.pop();
    bStack.pop();
    return result;
  };

  // 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 (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
    for (var key in obj) if (_.has(obj, key)) return false;
    return true;
  };

  // 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) {
    return obj === Object(obj);
  };

  // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
  each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
    _['is' + name] = function(obj) {
      return toString.call(obj) == '[object ' + name + ']';
    };
  });

  // Define a fallback version of the method in browsers (ahem, IE), where
  // there isn't any inspectable "Arguments" type.
  if (!_.isArguments(arguments)) {
    _.isArguments = function(obj) {
      return !!(obj && _.has(obj, 'callee'));
    };
  }

  // Optimize `isFunction` if appropriate.
  if (typeof (/./) !== 'function') {
    _.isFunction = function(obj) {
      return typeof obj === 'function';
    };
  }

  // 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 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 iterators.
  _.identity = function(value) {
    return value;
  };

  // Run a function **n** times.
  _.times = function(n, iterator, context) {
    var accum = Array(Math.max(0, n));
    for (var i = 0; i < n; i++) accum[i] = iterator.call(context, 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));
  };

  // List of HTML entities for escaping.
  var entityMap = {
    escape: {
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;',
      '"': '&quot;',
      "'": '&#x27;'
    }
  };
  entityMap.unescape = _.invert(entityMap.escape);

  // Regexes containing the keys and values listed immediately above.
  var entityRegexes = {
    escape:   new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'),
    unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g')
  };

  // Functions for escaping and unescaping strings to/from HTML interpolation.
  _.each(['escape', 'unescape'], function(method) {
    _[method] = function(string) {
      if (string == null) return '';
      return ('' + string).replace(entityRegexes[method], function(match) {
        return entityMap[method][match];
      });
    };
  });

  // 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) {
    if (object == null) return void 0;
    var value = object[property];
    return _.isFunction(value) ? value.call(object) : value;
  };

  // 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.call(this, func.apply(_, args));
      };
    });
  };

  // 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',
    '\t':     't',
    '\u2028': 'u2028',
    '\u2029': 'u2029'
  };

  var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;

  // JavaScript micro-templating, similar to John Resig's implementation.
  // Underscore templating handles arbitrary delimiters, preserves whitespace,
  // and correctly escapes quotes within interpolated code.
  _.template = function(text, data, settings) {
    var render;
    settings = _.defaults({}, settings, _.templateSettings);

    // Combine delimiters into one regular expression via alternation.
    var matcher = new 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, function(match) { return '\\' + escapes[match]; });

      if (escape) {
        source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
      }
      if (interpolate) {
        source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
      }
      if (evaluate) {
        source += "';\n" + evaluate + "\n__p+='";
      }
      index = offset + match.length;
      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 {
      render = new Function(settings.variable || 'obj', '_', source);
    } catch (e) {
      e.source = source;
      throw e;
    }

    if (data) return render(data, _);
    var template = function(data) {
      return render.call(this, data, _);
    };

    // Provide the compiled function source as a convenience for precompilation.
    template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';

    return template;
  };

  // Add a "chain" function, which will delegate to the wrapper.
  _.chain = function(obj) {
    return _(obj).chain();
  };

  // 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(obj) {
    return this._chain ? _(obj).chain() : obj;
  };

  // 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.call(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.call(this, method.apply(this._wrapped, arguments));
    };
  });

  _.extend(_.prototype, {

    // Start chaining a wrapped Underscore object.
    chain: function() {
      this._chain = true;
      return this;
    },

    // Extracts the result from a wrapped and chained object.
    value: function() {
      return this._wrapped;
    }

  });

  // AMD define happens at the end for compatibility with AMD loaders
  // that don't enforce next-turn semantics on modules.
  if (typeof define === 'function' && define.amd) {
    define('underscore', [],function() {
      return _;
    });
  }

}).call(this);

(function(root) {
define("sprintf", [], function() {
  return (function() {
/*! sprintf.js | Copyright (c) 2007-2013 Alexandru Marasteanu <hello at alexei dot ro> | 3 clause BSD license */

(function(ctx) {
	var sprintf = function() {
		if (!sprintf.cache.hasOwnProperty(arguments[0])) {
			sprintf.cache[arguments[0]] = sprintf.parse(arguments[0]);
		}
		return sprintf.format.call(null, sprintf.cache[arguments[0]], arguments);
	};

	sprintf.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(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 (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
					throw(sprintf('[sprintf] expecting number but found %s', 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 = arg.toString(8); break;
					case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
					case 'u': arg = arg >>> 0; 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('');
	};

	sprintf.cache = {};

	sprintf.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-fosuxX])/.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('[sprintf] huh?');
							}
						}
					}
					else {
						throw('[sprintf] huh?');
					}
					match[2] = field_list;
				}
				else {
					arg_names |= 2;
				}
				if (arg_names === 3) {
					throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
				}
				parse_tree.push(match);
			}
			else {
				throw('[sprintf] huh?');
			}
			_fmt = _fmt.substring(match[0].length);
		}
		return parse_tree;
	};

	var vsprintf = function(fmt, argv, _argv) {
		_argv = argv.slice(0);
		_argv.splice(0, 0, fmt);
		return sprintf.apply(null, _argv);
	};

	/**
	 * helpers
	 */
	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('');
	}

	/**
	 * export to either browser or node.js
	 */
	ctx.sprintf = sprintf;
	ctx.vsprintf = vsprintf;
})(typeof exports != "undefined" ? exports : window);

return root.sprintf = sprintf;
  }).apply(root, arguments);
});
}(this));

/*!
 * numeral.js
 * version : 1.5.3
 * author : Adam Draper
 * license : MIT
 * http://adamwdraper.github.com/Numeral-js/
 */

define('numeral',["underscore"], function(_) {

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

    return {"format": format};
});

(function() {
  define('util/util',["underscore", "sprintf", "numeral"], function(_, sprintf, Numeral) {
    var replace_placeholders, _format_number;
    _format_number = function(number) {
      if (_.isString(number)) {
        return number;
      }
      if (Math.floor(number) === number) {
        return sprintf("%d", number);
      }
      if (Math.abs(number) > 0.1 && Math.abs(number) < 1000) {
        return sprintf("%0.3f", number);
      }
      return sprintf("%0.3e", number);
    };
    replace_placeholders = function(string, data_source, i, special_vars) {
      var _this = this;
      if (special_vars == null) {
        special_vars = {};
      }
      string = string.replace(/(^|[^\$])\$(\w+)/g, function(match, prefix, name) {
        var replacement;
        replacement = (function() {
          switch (name) {
            case "index":
              return "" + i;
            case "x":
              return "" + (_format_number(x));
            case "y":
              return "" + (_format_number(y));
            case "vx":
              return "" + vx;
            case "vy":
              return "" + vy;
            case "sx":
              return "" + sx;
            case "sy":
              return "" + sy;
          }
        })();
        if (replacement != null) {
          return "" + prefix + replacement;
        } else {
          return match;
        }
      });
      string = string.replace(/(^|[^@])@(?:(\$?\w+)|{([^{}]+)})(?:{([^{}]+)})?/g, function(match, prefix, name, long_name, format) {
        var column, replacement, value;
        name = long_name != null ? long_name : name;
        value = name[0] === "$" ? special_vars[name.substring(1)] : (column = data_source.get_column(name), column != null ? column[i] : special_vars[name]);
        replacement = value == null ? "???" : format != null ? Numeral.format(value, format) : _format_number(value);
        return "" + prefix + (_.escape(replacement));
      });
      return string;
    };
    return {
      replace_placeholders: replace_placeholders
    };
  });

}).call(this);

/*
//@ sourceMappingURL=util.js.map
*/;
/*!
 * jQuery JavaScript Library v1.11.1
 * 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: 2014-05-01T17:42Z
 */

(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 inherently posses a window with a document
		// (such as Node.js), expose a jQuery-making 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 ) {

// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//

var deletedIds = [];

var slice = deletedIds.slice;

var concat = deletedIds.concat;

var push = deletedIds.push;

var indexOf = deletedIds.indexOf;

var class2type = {};

var toString = class2type.toString;

var hasOwn = class2type.hasOwnProperty;

var support = {};



var
	version = "1.11.1",

	// 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, IE<9
	// 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: deletedIds.sort,
	splice: deletedIds.splice
};

jQuery.extend = jQuery.fn.extend = function() {
	var src, copyIsArray, copy, name, options, 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() {},

	// See test/unit/core.js for details concerning isFunction.
	// Since version 1.3, DOM methods and functions like alert
	// aren't supported. They return false on IE (#2968).
	isFunction: function( obj ) {
		return jQuery.type(obj) === "function";
	},

	isArray: Array.isArray || function( obj ) {
		return jQuery.type(obj) === "array";
	},

	isWindow: function( obj ) {
		/* jshint eqeqeq: false */
		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
		return !jQuery.isArray( obj ) && obj - parseFloat( obj ) >= 0;
	},

	isEmptyObject: function( obj ) {
		var name;
		for ( name in obj ) {
			return false;
		}
		return true;
	},

	isPlainObject: function( obj ) {
		var key;

		// Must be an Object.
		// Because of IE, we also have to check the presence of the constructor property.
		// Make sure that DOM nodes and window objects don't pass through, as well
		if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
			return false;
		}

		try {
			// Not own constructor property must be Object
			if ( obj.constructor &&
				!hasOwn.call(obj, "constructor") &&
				!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
				return false;
			}
		} catch ( e ) {
			// IE8,9 Will throw exceptions on certain host objects #9897
			return false;
		}

		// Support: IE<9
		// Handle iteration over inherited properties before own properties.
		if ( support.ownLast ) {
			for ( key in obj ) {
				return hasOwn.call( obj, key );
			}
		}

		// Own properties are enumerated firstly, so to speed up,
		// if last one is own, then all properties are own.
		for ( key in obj ) {}

		return key === undefined || hasOwn.call( obj, key );
	},

	type: function( obj ) {
		if ( obj == null ) {
			return obj + "";
		}
		return typeof obj === "object" || typeof obj === "function" ?
			class2type[ toString.call(obj) ] || "object" :
			typeof obj;
	},

	// Evaluates a script in a global context
	// Workarounds based on findings by Jim Driscoll
	// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
	globalEval: function( data ) {
		if ( data && jQuery.trim( data ) ) {
			// We use execScript on Internet Explorer
			// We use an anonymous function so that context is window
			// rather than jQuery in Firefox
			( window.execScript || function( data ) {
				window[ "eval" ].call( window, data );
			} )( data );
		}
	},

	// Convert dashed to camelCase; used by the css and data modules
	// 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, IE<9
	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 ) {
		var len;

		if ( arr ) {
			if ( indexOf ) {
				return indexOf.call( arr, elem, i );
			}

			len = arr.length;
			i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;

			for ( ; i < len; i++ ) {
				// Skip accessing in sparse arrays
				if ( i in arr && arr[ i ] === elem ) {
					return i;
				}
			}
		}

		return -1;
	},

	merge: function( first, second ) {
		var len = +second.length,
			j = 0,
			i = first.length;

		while ( j < len ) {
			first[ i++ ] = second[ j++ ];
		}

		// Support: IE<9
		// Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists)
		if ( len !== len ) {
			while ( second[j] !== undefined ) {
				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 args, proxy, tmp;

		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: function() {
		return +( new Date() );
	},

	// 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 ) {
	var length = 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 v1.10.19
 * http://sizzlejs.com/
 *
 * Copyright 2013 jQuery Foundation, Inc. and other contributors
 * Released under the MIT license
 * http://jquery.org/license
 *
 * Date: 2014-04-18
 */
(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" + -(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
	strundefined = typeof undefined,
	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 if we can't use a native one
	indexOf = arr.indexOf || function( elem ) {
		var i = 0,
			len = this.length;
		for ( ; i < len; i++ ) {
			if ( this[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
	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 );
	};

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

	if ( !selector || typeof selector !== "string" ) {
		return results;
	}

	if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
		return [];
	}

	if ( documentIsHTML && !seed ) {

		// Shortcuts
		if ( (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 && context.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 === 9 && 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 !== strundefined && 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,
		doc = node ? node.ownerDocument || node : preferredDoc,
		parent = doc.defaultView;

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

	// Support tests
	documentIsHTML = !isXML( doc );

	// 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", function() {
				setDocument();
			}, false );
		} else if ( parent.attachEvent ) {
			parent.attachEvent( "onunload", function() {
				setDocument();
			});
		}
	}

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

	// Check if getElementsByClassName can be trusted
	support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) {
		div.innerHTML = "<div class='a'></div><div class='a i'></div>";

		// Support: Safari<4
		// Catch class over-caching
		div.firstChild.className = "i";
		// Support: Opera<10
		// Catch gEBCN failure to find non-leading classes
		return div.getElementsByClassName("i").length === 2;
	});

	// 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 !== strundefined && 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 !== strundefined && elem.getAttributeNode("id");
				return node && node.value === attrId;
			};
		};
	}

	// Tag
	Expr.find["TAG"] = support.getElementsByTagName ?
		function( tag, context ) {
			if ( typeof context.getElementsByTagName !== strundefined ) {
				return context.getElementsByTagName( tag );
			}
		} :
		function( tag, context ) {
			var elem,
				tmp = [],
				i = 0,
				results = context.getElementsByTagName( tag );

			// Filter out possible comments
			if ( tag === "*" ) {
				while ( (elem = results[i++]) ) {
					if ( elem.nodeType === 1 ) {
						tmp.push( elem );
					}
				}

				return tmp;
			}
			return results;
		};

	// Class
	Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
		if ( typeof context.getElementsByClassName !== strundefined && 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
			div.innerHTML = "<select msallowclip=''><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("[msallowclip^='']").length ) {
				rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
			}

			// Support: IE8
			// Boolean attributes and "value" are not treated correctly
			if ( !div.querySelectorAll("[selected]").length ) {
				rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
			}

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

		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.call( sortInput, a ) - indexOf.call( 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.call( sortInput, a ) - indexOf.call( 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 !== strundefined && 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 + " " ).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.call( 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 );
					return !results.pop();
				};
		}),

		"has": markFunction(function( selector ) {
			return function( elem ) {
				return Sizzle( selector, elem ).length > 0;
			};
		}),

		"contains": markFunction(function( text ) {
			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.call( 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.call( checkContext, elem ) > -1;
		}, implicitRelative, true ),
		matchers = [ function( elem, context, xml ) {
			return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
				(checkContext = context).nodeType ?
					matchContext( elem, context, xml ) :
					matchAnyContext( elem, context, xml ) );
		} ];

	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
// 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 ( jQuery.inArray( elem, qualifier ) >= 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,
			ret = [],
			self = this,
			len = self.length;

		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,

	// Use the correct document accordingly with window argument (sandbox)
	document = window.document,

	// 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.charAt(0) === "<" && selector.charAt( 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;

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

					// Check parentNode to catch when Blackberry 4.6 returns
					// nodes that are no longer in the document #6963
					if ( elem && elem.parentNode ) {
						// Handle the case where IE and Opera return items
						// by name instead of ID
						if ( elem.id !== match[2] ) {
							return rootjQuery.find( selector );
						}

						// Otherwise, we 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 = [],
			cur = elem[ dir ];

		while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
			if ( cur.nodeType === 1 ) {
				matched.push( cur );
			}
			cur = cur[dir];
		}
		return matched;
	},

	sibling: function( n, elem ) {
		var r = [];

		for ( ; n; n = n.nextSibling ) {
			if ( n.nodeType === 1 && n !== elem ) {
				r.push( n );
			}
		}

		return r;
	}
});

jQuery.fn.extend({
	has: function( target ) {
		var i,
			targets = jQuery( target, this ),
			len = targets.length;

		return this.filter(function() {
			for ( i = 0; i < len; 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 matched set of elements
	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 jQuery.inArray( this[0], jQuery( elem ) );
		}

		// Locate the position of the desired element
		return jQuery.inArray(
			// If it receives a jQuery object, the first element is used
			elem.jquery ? elem[0] : elem, this );
	},

	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 ) {
	do {
		cur = cur[ dir ];
	} while ( cur && 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 jQuery.nodeName( elem, "iframe" ) ?
			elem.contentDocument || elem.contentWindow.document :
			jQuery.merge( [], elem.childNodes );
	}
}, function( name, fn ) {
	jQuery.fn[ name ] = function( until, selector ) {
		var ret = jQuery.map( this, fn, until );

		if ( name.slice( -5 ) !== "Until" ) {
			selector = until;
		}

		if ( selector && typeof selector === "string" ) {
			ret = jQuery.filter( selector, ret );
		}

		if ( this.length > 1 ) {
			// Remove duplicates
			if ( !guaranteedUnique[ name ] ) {
				ret = jQuery.unique( ret );
			}

			// Reverse order for parents* and prev-derivatives
			if ( rparentsprev.test( name ) ) {
				ret = ret.reverse();
			}
		}

		return this.pushStack( ret );
	};
});
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 // Flag to know if list is currently firing
		firing,
		// Last fire value (for non-forgettable lists)
		memory,
		// Flag to know if list was already fired
		fired,
		// End of the loop when firing
		firingLength,
		// Index of currently firing callback (modified by remove if needed)
		firingIndex,
		// First callback to fire (used internally by add and fireWith)
		firingStart,
		// 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;
		}

		// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
		if ( !document.body ) {
			return setTimeout( jQuery.ready );
		}

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

/**
 * Clean-up method for dom ready events
 */
function detach() {
	if ( document.addEventListener ) {
		document.removeEventListener( "DOMContentLoaded", completed, false );
		window.removeEventListener( "load", completed, false );

	} else {
		document.detachEvent( "onreadystatechange", completed );
		window.detachEvent( "onload", completed );
	}
}

/**
 * The ready event handler and self cleanup method
 */
function completed() {
	// readyState === "complete" is good enough for us to call the dom ready in oldIE
	if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) {
		detach();
		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 );

		// Standards-based browsers support DOMContentLoaded
		} else if ( document.addEventListener ) {
			// Use the handy event callback
			document.addEventListener( "DOMContentLoaded", completed, false );

			// A fallback to window.onload, that will always work
			window.addEventListener( "load", completed, false );

		// If IE event model is used
		} else {
			// Ensure firing before onload, maybe late but safe also for iframes
			document.attachEvent( "onreadystatechange", completed );

			// A fallback to window.onload, that will always work
			window.attachEvent( "onload", completed );

			// If IE and not a frame
			// continually check to see if the document is ready
			var top = false;

			try {
				top = window.frameElement == null && document.documentElement;
			} catch(e) {}

			if ( top && top.doScroll ) {
				(function doScrollCheck() {
					if ( !jQuery.isReady ) {

						try {
							// Use the trick by Diego Perini
							// http://javascript.nwbox.com/IEContentLoaded/
							top.doScroll("left");
						} catch(e) {
							return setTimeout( doScrollCheck, 50 );
						}

						// detach all dom ready events
						detach();

						// and execute any waiting functions
						jQuery.ready();
					}
				})();
			}
		}
	}
	return readyList.promise( obj );
};


var strundefined = typeof undefined;



// Support: IE<9
// Iteration over object's inherited properties before its own
var i;
for ( i in jQuery( support ) ) {
	break;
}
support.ownLast = i !== "0";

// Note: most support tests are defined in their respective modules.
// false until the test is run
support.inlineBlockNeedsLayout = false;

// Execute ASAP in case we need to set body.style.zoom
jQuery(function() {
	// Minified: var a,b,c,d
	var val, div, body, container;

	body = document.getElementsByTagName( "body" )[ 0 ];
	if ( !body || !body.style ) {
		// Return for frameset docs that don't have a body
		return;
	}

	// Setup
	div = document.createElement( "div" );
	container = document.createElement( "div" );
	container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
	body.appendChild( container ).appendChild( div );

	if ( typeof div.style.zoom !== strundefined ) {
		// Support: IE<8
		// Check if natively block-level elements act like inline-block
		// elements when setting their display to 'inline' and giving
		// them layout
		div.style.cssText = "display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1";

		support.inlineBlockNeedsLayout = val = div.offsetWidth === 3;
		if ( val ) {
			// Prevent IE 6 from affecting layout for positioned elements #11048
			// Prevent IE from shrinking the body in IE 7 mode #12869
			// Support: IE<8
			body.style.zoom = 1;
		}
	}

	body.removeChild( container );
});




(function() {
	var div = document.createElement( "div" );

	// Execute the test only if not already executed in another module.
	if (support.deleteExpando == null) {
		// Support: IE<9
		support.deleteExpando = true;
		try {
			delete div.test;
		} catch( e ) {
			support.deleteExpando = false;
		}
	}

	// Null elements to avoid leaks in IE.
	div = null;
})();


/**
 * Determines whether an object can have data
 */
jQuery.acceptData = function( elem ) {
	var noData = jQuery.noData[ (elem.nodeName + " ").toLowerCase() ],
		nodeType = +elem.nodeType || 1;

	// Do not set data on non-element DOM nodes because it will not be cleared (#8335).
	return nodeType !== 1 && nodeType !== 9 ?
		false :

		// Nodes accept data unless otherwise specified; rejection can be conditional
		!noData || noData !== true && elem.getAttribute("classid") === noData;
};


var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
	rmultiDash = /([A-Z])/g;

function dataAttr( elem, key, data ) {
	// If nothing was found internally, try to fetch any
	// data from the HTML5 data-* attribute
	if ( data === undefined && elem.nodeType === 1 ) {

		var 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
			jQuery.data( elem, key, data );

		} else {
			data = undefined;
		}
	}

	return data;
}

// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
	var name;
	for ( name in obj ) {

		// if the public data object is empty, the private is still empty
		if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
			continue;
		}
		if ( name !== "toJSON" ) {
			return false;
		}
	}

	return true;
}

function internalData( elem, name, data, pvt /* Internal Use Only */ ) {
	if ( !jQuery.acceptData( elem ) ) {
		return;
	}

	var ret, thisCache,
		internalKey = jQuery.expando,

		// We have to handle DOM nodes and JS objects differently because IE6-7
		// can't GC object references properly across the DOM-JS boundary
		isNode = elem.nodeType,

		// Only DOM nodes need the global jQuery cache; JS object data is
		// attached directly to the object so GC can occur automatically
		cache = isNode ? jQuery.cache : elem,

		// Only defining an ID for JS objects if its cache already exists allows
		// the code to shortcut on the same path as a DOM node with no cache
		id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;

	// Avoid doing any more work than we need to when trying to get data on an
	// object that has no data at all
	if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) {
		return;
	}

	if ( !id ) {
		// Only DOM nodes need a new unique ID for each element since their data
		// ends up in the global cache
		if ( isNode ) {
			id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++;
		} else {
			id = internalKey;
		}
	}

	if ( !cache[ id ] ) {
		// Avoid exposing jQuery metadata on plain JS objects when the object
		// is serialized using JSON.stringify
		cache[ id ] = isNode ? {} : { toJSON: jQuery.noop };
	}

	// An object can be passed to jQuery.data instead of a key/value pair; this gets
	// shallow copied over onto the existing cache
	if ( typeof name === "object" || typeof name === "function" ) {
		if ( pvt ) {
			cache[ id ] = jQuery.extend( cache[ id ], name );
		} else {
			cache[ id ].data = jQuery.extend( cache[ id ].data, name );
		}
	}

	thisCache = cache[ id ];

	// jQuery data() is stored in a separate object inside the object's internal data
	// cache in order to avoid key collisions between internal data and user-defined
	// data.
	if ( !pvt ) {
		if ( !thisCache.data ) {
			thisCache.data = {};
		}

		thisCache = thisCache.data;
	}

	if ( data !== undefined ) {
		thisCache[ jQuery.camelCase( name ) ] = data;
	}

	// Check for both converted-to-camel and non-converted data property names
	// If a data property was specified
	if ( typeof name === "string" ) {

		// First Try to find as-is property data
		ret = thisCache[ name ];

		// Test for null|undefined property data
		if ( ret == null ) {

			// Try to find the camelCased property
			ret = thisCache[ jQuery.camelCase( name ) ];
		}
	} else {
		ret = thisCache;
	}

	return ret;
}

function internalRemoveData( elem, name, pvt ) {
	if ( !jQuery.acceptData( elem ) ) {
		return;
	}

	var thisCache, i,
		isNode = elem.nodeType,

		// See jQuery.data for more information
		cache = isNode ? jQuery.cache : elem,
		id = isNode ? elem[ jQuery.expando ] : jQuery.expando;

	// If there is already no cache entry for this object, there is no
	// purpose in continuing
	if ( !cache[ id ] ) {
		return;
	}

	if ( name ) {

		thisCache = pvt ? cache[ id ] : cache[ id ].data;

		if ( thisCache ) {

			// Support array or space separated string names for data keys
			if ( !jQuery.isArray( name ) ) {

				// try the string as a key before any manipulation
				if ( name in thisCache ) {
					name = [ name ];
				} else {

					// split the camel cased version by spaces unless a key with the spaces exists
					name = jQuery.camelCase( name );
					if ( name in thisCache ) {
						name = [ name ];
					} else {
						name = name.split(" ");
					}
				}
			} else {
				// 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 = name.concat( jQuery.map( name, jQuery.camelCase ) );
			}

			i = name.length;
			while ( i-- ) {
				delete thisCache[ name[i] ];
			}

			// If there is no data left in the cache, we want to continue
			// and let the cache object itself get destroyed
			if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) {
				return;
			}
		}
	}

	// See jQuery.data for more information
	if ( !pvt ) {
		delete cache[ id ].data;

		// Don't destroy the parent cache unless the internal data object
		// had been the only thing left in it
		if ( !isEmptyDataObject( cache[ id ] ) ) {
			return;
		}
	}

	// Destroy the cache
	if ( isNode ) {
		jQuery.cleanData( [ elem ], true );

	// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
	/* jshint eqeqeq: false */
	} else if ( support.deleteExpando || cache != cache.window ) {
		/* jshint eqeqeq: true */
		delete cache[ id ];

	// When all else fails, null
	} else {
		cache[ id ] = null;
	}
}

jQuery.extend({
	cache: {},

	// The following elements (space-suffixed to avoid Object.prototype collisions)
	// throw uncatchable exceptions if you attempt to set expando properties
	noData: {
		"applet ": true,
		"embed ": true,
		// ...but Flash objects (which have this classid) *can* handle expandos
		"object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
	},

	hasData: function( elem ) {
		elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
		return !!elem && !isEmptyDataObject( elem );
	},

	data: function( elem, name, data ) {
		return internalData( elem, name, data );
	},

	removeData: function( elem, name ) {
		return internalRemoveData( elem, name );
	},

	// For internal use only.
	_data: function( elem, name, data ) {
		return internalData( elem, name, data, true );
	},

	_removeData: function( elem, name ) {
		return internalRemoveData( elem, name, true );
	}
});

jQuery.fn.extend({
	data: function( key, value ) {
		var i, name, data,
			elem = this[0],
			attrs = elem && elem.attributes;

		// Special expections of .data basically thwart jQuery.access,
		// so implement the relevant behavior ourselves

		// Gets all values
		if ( key === undefined ) {
			if ( this.length ) {
				data = jQuery.data( elem );

				if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
					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 ] );
							}
						}
					}
					jQuery._data( elem, "parsedAttrs", true );
				}
			}

			return data;
		}

		// Sets multiple values
		if ( typeof key === "object" ) {
			return this.each(function() {
				jQuery.data( this, key );
			});
		}

		return arguments.length > 1 ?

			// Sets one value
			this.each(function() {
				jQuery.data( this, key, value );
			}) :

			// Gets one value
			// Try to fetch any internally stored data first
			elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : undefined;
	},

	removeData: function( key ) {
		return this.each(function() {
			jQuery.removeData( this, key );
		});
	}
});


jQuery.extend({
	queue: function( elem, type, data ) {
		var queue;

		if ( elem ) {
			type = ( type || "fx" ) + "queue";
			queue = jQuery._data( elem, type );

			// Speed up dequeue by getting out quickly if this is just a lookup
			if ( data ) {
				if ( !queue || jQuery.isArray(data) ) {
					queue = jQuery._data( 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 intended for public consumption - generates a queueHooks object, or returns the current one
	_queueHooks: function( elem, type ) {
		var key = type + "queueHooks";
		return jQuery._data( elem, key ) || jQuery._data( elem, key, {
			empty: jQuery.Callbacks("once memory").add(function() {
				jQuery._removeData( elem, type + "queue" );
				jQuery._removeData( elem, 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 = jQuery._data( 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 );
	};



// 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,
		length = 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 < length; i++ ) {
				fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
			}
		}
	}

	return chainable ?
		elems :

		// Gets
		bulk ?
			fn.call( elems ) :
			length ? fn( elems[0], key ) : emptyGet;
};
var rcheckableType = (/^(?:checkbox|radio)$/i);



(function() {
	// Minified: var a,b,c
	var input = document.createElement( "input" ),
		div = document.createElement( "div" ),
		fragment = document.createDocumentFragment();

	// Setup
	div.innerHTML = "  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";

	// IE strips leading whitespace when .innerHTML is used
	support.leadingWhitespace = div.firstChild.nodeType === 3;

	// Make sure that tbody elements aren't automatically inserted
	// IE will insert them into empty tables
	support.tbody = !div.getElementsByTagName( "tbody" ).length;

	// Make sure that link elements get serialized correctly by innerHTML
	// This requires a wrapper element in IE
	support.htmlSerialize = !!div.getElementsByTagName( "link" ).length;

	// Makes sure cloning an html5 element does not cause problems
	// Where outerHTML is undefined, this still works
	support.html5Clone =
		document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav></:nav>";

	// Check if a disconnected checkbox will retain its checked
	// value of true after appended to the DOM (IE6/7)
	input.type = "checkbox";
	input.checked = true;
	fragment.appendChild( input );
	support.appendChecked = input.checked;

	// Make sure textarea (and checkbox) defaultValue is properly cloned
	// Support: IE6-IE11+
	div.innerHTML = "<textarea>x</textarea>";
	support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;

	// #11217 - WebKit loses check when the name is after the checked attribute
	fragment.appendChild( div );
	div.innerHTML = "<input type='radio' checked='checked' name='t'/>";

	// Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
	// old WebKit doesn't clone checked state correctly in fragments
	support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;

	// Support: IE<9
	// Opera does not clone events (and typeof div.attachEvent === undefined).
	// IE9-10 clones events bound via attachEvent, but they don't trigger with .click()
	support.noCloneEvent = true;
	if ( div.attachEvent ) {
		div.attachEvent( "onclick", function() {
			support.noCloneEvent = false;
		});

		div.cloneNode( true ).click();
	}

	// Execute the test only if not already executed in another module.
	if (support.deleteExpando == null) {
		// Support: IE<9
		support.deleteExpando = true;
		try {
			delete div.test;
		} catch( e ) {
			support.deleteExpando = false;
		}
	}
})();


(function() {
	var i, eventName,
		div = document.createElement( "div" );

	// Support: IE<9 (lack submit/change bubble), Firefox 23+ (lack focusin event)
	for ( i in { submit: true, change: true, focusin: true }) {
		eventName = "on" + i;

		if ( !(support[ i + "Bubbles" ] = eventName in window) ) {
			// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
			div.setAttribute( eventName, "t" );
			support[ i + "Bubbles" ] = div.attributes[ eventName ].expando === false;
		}
	}

	// Null elements to avoid leaks in IE.
	div = null;
})();


var rformElems = /^(?:input|select|textarea)$/i,
	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 tmp, events, t, handleObjIn,
			special, eventHandle, handleObj,
			handlers, type, namespaces, origType,
			elemData = jQuery._data( 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 && (!e || jQuery.event.triggered !== e.type) ?
					jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
					undefined;
			};
			// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
			eventHandle.elem = elem;
		}

		// 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/attachEvent if the special events handler returns false
				if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
					// Bind the global event handler to the element
					if ( elem.addEventListener ) {
						elem.addEventListener( type, eventHandle, false );

					} else if ( elem.attachEvent ) {
						elem.attachEvent( "on" + type, eventHandle );
					}
				}
			}

			if ( special.add ) {
				special.add.call( elem, handleObj );

				if ( !handleObj.handler.guid ) {
					handleObj.handler.guid = handler.guid;
				}
			}

			// Add to the element's handler list, delegates in front
			if ( selector ) {
				handlers.splice( handlers.delegateCount++, 0, handleObj );
			} else {
				handlers.push( handleObj );
			}

			// Keep track of which events have ever been used, for event optimization
			jQuery.event.global[ type ] = true;
		}

		// Nullify elem to prevent memory leaks in IE
		elem = null;
	},

	// Detach an event or set of events from an element
	remove: function( elem, types, handler, selector, mappedTypes ) {
		var j, handleObj, tmp,
			origCount, t, events,
			special, handlers, type,
			namespaces, origType,
			elemData = jQuery.hasData( elem ) && jQuery._data( 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;

			// removeData also checks for emptiness and clears the expando if empty
			// so use it instead of delete
			jQuery._removeData( elem, "events" );
		}
	},

	trigger: function( event, data, elem, onlyHandlers ) {
		var handle, ontype, cur,
			bubbleType, special, tmp, i,
			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 = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( 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.
				// Can't use an .isFunction() check here because IE6/7 fails that test.
				// Don't do default actions on window, that's where global variables be (#6170)
				if ( ontype && 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;
					try {
						elem[ type ]();
					} catch ( e ) {
						// IE<9 dies on focus/blur to hidden element (#1486,#12518)
						// only reproducible on winXP IE8 native, not IE9 in IE8 mode
					}
					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, ret, handleObj, matched, j,
			handlerQueue = [],
			args = slice.call( arguments ),
			handlers = ( jQuery._data( 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 sel, handleObj, matches, i,
			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") ) {

			/* jshint eqeqeq: false */
			for ( ; cur != this; cur = cur.parentNode || this ) {
				/* jshint eqeqeq: true */

				// Don't check non-elements (#13208)
				// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
				if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) {
					matches = [];
					for ( i = 0; i < delegateCount; i++ ) {
						handleObj = handlers[ i ];

						// Don't conflict with Object.prototype properties (#13203)
						sel = handleObj.selector + " ";

						if ( matches[ sel ] === undefined ) {
							matches[ sel ] = handleObj.needsContext ?
								jQuery( sel, this ).index( cur ) >= 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;
	},

	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: IE<9
		// Fix target property (#1925)
		if ( !event.target ) {
			event.target = originalEvent.srcElement || document;
		}

		// Support: Chrome 23+, Safari?
		// Target should not be a text node (#504, #13143)
		if ( event.target.nodeType === 3 ) {
			event.target = event.target.parentNode;
		}

		// Support: IE<9
		// For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
		event.metaKey = !!event.metaKey;

		return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
	},

	// 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 fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
		filter: function( event, original ) {
			var body, eventDoc, doc,
				button = original.button,
				fromElement = original.fromElement;

			// 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 relatedTarget, if necessary
			if ( !event.relatedTarget && fromElement ) {
				event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
			}

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

	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 ) {
					try {
						this.focus();
						return false;
					} catch ( e ) {
						// Support: IE<9
						// If we error on focus to hidden element (#1486, #12518),
						// let .trigger() run the handlers
					}
				}
			},
			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 ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
					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 = document.removeEventListener ?
	function( elem, type, handle ) {
		if ( elem.removeEventListener ) {
			elem.removeEventListener( type, handle, false );
		}
	} :
	function( elem, type, handle ) {
		var name = "on" + type;

		if ( elem.detachEvent ) {

			// #8545, #7054, preventing memory leaks for custom events in IE6-8
			// detachEvent needed property on element, by name of that event, to properly expose it to GC
			if ( typeof elem[ name ] === strundefined ) {
				elem[ name ] = null;
			}

			elem.detachEvent( name, handle );
		}
	};

jQuery.Event = function( src, props ) {
	// Allow instantiation without the 'new' keyword
	if ( !(this instanceof jQuery.Event) ) {
		return new jQuery.Event( src, props );
	}

	// Event object
	if ( src && src.type ) {
		this.originalEvent = src;
		this.type = src.type;

		// Events bubbling up the document may have been marked as prevented
		// by a handler lower down the tree; reflect the correct value.
		this.isDefaultPrevented = src.defaultPrevented ||
				src.defaultPrevented === undefined &&
				// Support: IE < 9, 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 ) {
			return;
		}

		// If preventDefault exists, run it on the original event
		if ( e.preventDefault ) {
			e.preventDefault();

		// Support: IE
		// Otherwise set the returnValue property of the original event to false
		} else {
			e.returnValue = false;
		}
	},
	stopPropagation: function() {
		var e = this.originalEvent;

		this.isPropagationStopped = returnTrue;
		if ( !e ) {
			return;
		}
		// If stopPropagation exists, run it on the original event
		if ( e.stopPropagation ) {
			e.stopPropagation();
		}

		// Support: IE
		// Set the cancelBubble property of the original event to true
		e.cancelBubble = true;
	},
	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
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;
		}
	};
});

// IE submit delegation
if ( !support.submitBubbles ) {

	jQuery.event.special.submit = {
		setup: function() {
			// Only need this for delegated form submit events
			if ( jQuery.nodeName( this, "form" ) ) {
				return false;
			}

			// Lazy-add a submit handler when a descendant form may potentially be submitted
			jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
				// Node name check avoids a VML-related crash in IE (#9807)
				var elem = e.target,
					form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
				if ( form && !jQuery._data( form, "submitBubbles" ) ) {
					jQuery.event.add( form, "submit._submit", function( event ) {
						event._submit_bubble = true;
					});
					jQuery._data( form, "submitBubbles", true );
				}
			});
			// return undefined since we don't need an event listener
		},

		postDispatch: function( event ) {
			// If form was submitted by the user, bubble the event up the tree
			if ( event._submit_bubble ) {
				delete event._submit_bubble;
				if ( this.parentNode && !event.isTrigger ) {
					jQuery.event.simulate( "submit", this.parentNode, event, true );
				}
			}
		},

		teardown: function() {
			// Only need this for delegated form submit events
			if ( jQuery.nodeName( this, "form" ) ) {
				return false;
			}

			// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
			jQuery.event.remove( this, "._submit" );
		}
	};
}

// IE change delegation and checkbox/radio fix
if ( !support.changeBubbles ) {

	jQuery.event.special.change = {

		setup: function() {

			if ( rformElems.test( this.nodeName ) ) {
				// IE doesn't fire change on a check/radio until blur; trigger it on click
				// after a propertychange. Eat the blur-change in special.change.handle.
				// This still fires onchange a second time for check/radio after blur.
				if ( this.type === "checkbox" || this.type === "radio" ) {
					jQuery.event.add( this, "propertychange._change", function( event ) {
						if ( event.originalEvent.propertyName === "checked" ) {
							this._just_changed = true;
						}
					});
					jQuery.event.add( this, "click._change", function( event ) {
						if ( this._just_changed && !event.isTrigger ) {
							this._just_changed = false;
						}
						// Allow triggered, simulated change events (#11500)
						jQuery.event.simulate( "change", this, event, true );
					});
				}
				return false;
			}
			// Delegated event; lazy-add a change handler on descendant inputs
			jQuery.event.add( this, "beforeactivate._change", function( e ) {
				var elem = e.target;

				if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) {
					jQuery.event.add( elem, "change._change", function( event ) {
						if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
							jQuery.event.simulate( "change", this.parentNode, event, true );
						}
					});
					jQuery._data( elem, "changeBubbles", true );
				}
			});
		},

		handle: function( event ) {
			var elem = event.target;

			// Swallow native change events from checkbox/radio, we already triggered them above
			if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
				return event.handleObj.handler.apply( this, arguments );
			}
		},

		teardown: function() {
			jQuery.event.remove( this, "._change" );

			return !rformElems.test( this.nodeName );
		}
	};
}

// 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 = jQuery._data( doc, fix );

				if ( !attaches ) {
					doc.addEventListener( orig, handler, true );
				}
				jQuery._data( doc, fix, ( attaches || 0 ) + 1 );
			},
			teardown: function() {
				var doc = this.ownerDocument || this,
					attaches = jQuery._data( doc, fix ) - 1;

				if ( !attaches ) {
					doc.removeEventListener( orig, handler, true );
					jQuery._removeData( doc, fix );
				} else {
					jQuery._data( doc, fix, attaches );
				}
			}
		};
	});
}

jQuery.fn.extend({

	on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
		var type, origFn;

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


function createSafeFragment( document ) {
	var list = nodeNames.split( "|" ),
		safeFrag = document.createDocumentFragment();

	if ( safeFrag.createElement ) {
		while ( list.length ) {
			safeFrag.createElement(
				list.pop()
			);
		}
	}
	return safeFrag;
}

var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
		"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
	rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
	rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
	rleadingWhitespace = /^\s+/,
	rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
	rtagName = /<([\w:]+)/,
	rtbody = /<tbody/i,
	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 = {
		option: [ 1, "<select multiple='multiple'>", "</select>" ],
		legend: [ 1, "<fieldset>", "</fieldset>" ],
		area: [ 1, "<map>", "</map>" ],
		param: [ 1, "<object>", "</object>" ],
		thead: [ 1, "<table>", "</table>" ],
		tr: [ 2, "<table><tbody>", "</tbody></table>" ],
		col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
		td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],

		// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
		// unless wrapped in a div with non-breaking characters in front of it.
		_default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>"  ]
	},
	safeFragment = createSafeFragment( document ),
	fragmentDiv = safeFragment.appendChild( document.createElement("div") );

wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;

function getAll( context, tag ) {
	var elems, elem,
		i = 0,
		found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) :
			typeof context.querySelectorAll !== strundefined ? context.querySelectorAll( tag || "*" ) :
			undefined;

	if ( !found ) {
		for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) {
			if ( !tag || jQuery.nodeName( elem, tag ) ) {
				found.push( elem );
			} else {
				jQuery.merge( found, getAll( elem, tag ) );
			}
		}
	}

	return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
		jQuery.merge( [ context ], found ) :
		found;
}

// Used in buildFragment, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
	if ( rcheckableType.test( elem.type ) ) {
		elem.defaultChecked = elem.checked;
	}
}

// Support: IE<8
// 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 = (jQuery.find.attr( elem, "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 elem,
		i = 0;
	for ( ; (elem = elems[i]) != null; i++ ) {
		jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) );
	}
}

function cloneCopyEvent( src, dest ) {

	if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
		return;
	}

	var type, i, l,
		oldData = jQuery._data( src ),
		curData = jQuery._data( dest, oldData ),
		events = oldData.events;

	if ( events ) {
		delete curData.handle;
		curData.events = {};

		for ( type in events ) {
			for ( i = 0, l = events[ type ].length; i < l; i++ ) {
				jQuery.event.add( dest, type, events[ type ][ i ] );
			}
		}
	}

	// make the cloned public data object a copy from the original
	if ( curData.data ) {
		curData.data = jQuery.extend( {}, curData.data );
	}
}

function fixCloneNodeIssues( src, dest ) {
	var nodeName, e, data;

	// We do not need to do anything for non-Elements
	if ( dest.nodeType !== 1 ) {
		return;
	}

	nodeName = dest.nodeName.toLowerCase();

	// IE6-8 copies events bound via attachEvent when using cloneNode.
	if ( !support.noCloneEvent && dest[ jQuery.expando ] ) {
		data = jQuery._data( dest );

		for ( e in data.events ) {
			jQuery.removeEvent( dest, e, data.handle );
		}

		// Event data gets referenced instead of copied if the expando gets copied too
		dest.removeAttribute( jQuery.expando );
	}

	// IE blanks contents when cloning scripts, and tries to evaluate newly-set text
	if ( nodeName === "script" && dest.text !== src.text ) {
		disableScript( dest ).text = src.text;
		restoreScript( dest );

	// IE6-10 improperly clones children of object elements using classid.
	// IE10 throws NoModificationAllowedError if parent is null, #12132.
	} else if ( nodeName === "object" ) {
		if ( dest.parentNode ) {
			dest.outerHTML = src.outerHTML;
		}

		// This path appears unavoidable for IE9. When cloning an object
		// element in IE9, the outerHTML strategy above is not sufficient.
		// If the src has innerHTML and the destination does not,
		// copy the src.innerHTML into the dest.innerHTML. #10324
		if ( support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) {
			dest.innerHTML = src.innerHTML;
		}

	} else if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
		// IE6-8 fails to persist the checked state of a cloned checkbox
		// or radio button. Worse, IE6-7 fail to give the cloned element
		// a checked appearance if the defaultChecked value isn't also set

		dest.defaultChecked = dest.checked = src.checked;

		// IE6-7 get confused and end up setting the value of a cloned
		// checkbox/radio button to an empty string instead of "on"
		if ( dest.value !== src.value ) {
			dest.value = src.value;
		}

	// IE6-8 fails to return the selected option to the default selected
	// state when cloning options
	} else if ( nodeName === "option" ) {
		dest.defaultSelected = dest.selected = src.defaultSelected;

	// IE6-8 fails to set the defaultValue to the correct value when
	// cloning other types of input fields
	} else if ( nodeName === "input" || nodeName === "textarea" ) {
		dest.defaultValue = src.defaultValue;
	}
}

jQuery.extend({
	clone: function( elem, dataAndEvents, deepDataAndEvents ) {
		var destElements, node, clone, i, srcElements,
			inPage = jQuery.contains( elem.ownerDocument, elem );

		if ( support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
			clone = elem.cloneNode( true );

		// IE<=8 does not properly clone detached, unknown element nodes
		} else {
			fragmentDiv.innerHTML = elem.outerHTML;
			fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
		}

		if ( (!support.noCloneEvent || !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 );

			// Fix all IE cloning issues
			for ( i = 0; (node = srcElements[i]) != null; ++i ) {
				// Ensure that the destination node is not null; Fixes #9587
				if ( destElements[i] ) {
					fixCloneNodeIssues( node, 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; (node = srcElements[i]) != null; i++ ) {
					cloneCopyEvent( node, destElements[i] );
				}
			} else {
				cloneCopyEvent( elem, clone );
			}
		}

		// Preserve script evaluation history
		destElements = getAll( clone, "script" );
		if ( destElements.length > 0 ) {
			setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
		}

		destElements = srcElements = node = null;

		// Return the cloned set
		return clone;
	},

	buildFragment: function( elems, context, scripts, selection ) {
		var j, elem, contains,
			tmp, tag, tbody, wrap,
			l = elems.length,

			// Ensure a safe fragment
			safe = createSafeFragment( context ),

			nodes = [],
			i = 0;

		for ( ; i < l; i++ ) {
			elem = elems[ i ];

			if ( elem || elem === 0 ) {

				// Add nodes directly
				if ( jQuery.type( elem ) === "object" ) {
					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 || safe.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;
					}

					// Manually add leading whitespace removed by IE
					if ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
						nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) );
					}

					// Remove IE's autoinserted <tbody> from table fragments
					if ( !support.tbody ) {

						// String was a <table>, *may* have spurious <tbody>
						elem = tag === "table" && !rtbody.test( elem ) ?
							tmp.firstChild :

							// String was a bare <thead> or <tfoot>
							wrap[1] === "<table>" && !rtbody.test( elem ) ?
								tmp :
								0;

						j = elem && elem.childNodes.length;
						while ( j-- ) {
							if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) {
								elem.removeChild( tbody );
							}
						}
					}

					jQuery.merge( nodes, tmp.childNodes );

					// Fix #12392 for WebKit and IE > 9
					tmp.textContent = "";

					// Fix #12392 for oldIE
					while ( tmp.firstChild ) {
						tmp.removeChild( tmp.firstChild );
					}

					// Remember the top-level container for proper cleanup
					tmp = safe.lastChild;
				}
			}
		}

		// Fix #11356: Clear elements from fragment
		if ( tmp ) {
			safe.removeChild( tmp );
		}

		// Reset defaultChecked for any radios and checkboxes
		// about to be appended to the DOM in IE 6/7 (#8060)
		if ( !support.appendChecked ) {
			jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
		}

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

		tmp = null;

		return safe;
	},

	cleanData: function( elems, /* internal */ acceptData ) {
		var elem, type, id, data,
			i = 0,
			internalKey = jQuery.expando,
			cache = jQuery.cache,
			deleteExpando = support.deleteExpando,
			special = jQuery.event.special;

		for ( ; (elem = elems[i]) != null; i++ ) {
			if ( acceptData || jQuery.acceptData( elem ) ) {

				id = elem[ internalKey ];
				data = id && cache[ id ];

				if ( data ) {
					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 );
							}
						}
					}

					// Remove cache only if it was not already removed by jQuery.event.remove
					if ( cache[ id ] ) {

						delete cache[ id ];

						// IE does not allow us to delete expando properties from nodes,
						// nor does it have a removeAttribute function on Document nodes;
						// we must handle all of these cases
						if ( deleteExpando ) {
							delete elem[ internalKey ];

						} else if ( typeof elem.removeAttribute !== strundefined ) {
							elem.removeAttribute( internalKey );

						} else {
							elem[ internalKey ] = null;
						}

						deletedIds.push( id );
					}
				}
			}
		}
	}
});

jQuery.fn.extend({
	text: function( value ) {
		return access( this, function( value ) {
			return value === undefined ?
				jQuery.text( this ) :
				this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( 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++ ) {
			// Remove element nodes and prevent memory leaks
			if ( elem.nodeType === 1 ) {
				jQuery.cleanData( getAll( elem, false ) );
			}

			// Remove any remaining nodes
			while ( elem.firstChild ) {
				elem.removeChild( elem.firstChild );
			}

			// If this is a select, ensure that it displays empty (#12336)
			// Support: IE<9
			if ( elem.options && jQuery.nodeName( elem, "select" ) ) {
				elem.options.length = 0;
			}
		}

		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 ) {
				return elem.nodeType === 1 ?
					elem.innerHTML.replace( rinlinejQuery, "" ) :
					undefined;
			}

			// See if we can take a shortcut and just use innerHTML
			if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
				( support.htmlSerialize || !rnoshimcache.test( value )  ) &&
				( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
				!wrapMap[ (rtagName.exec( value ) || [ "", "" ])[ 1 ].toLowerCase() ] ) {

				value = value.replace( rxhtmlTag, "<$1></$2>" );

				try {
					for (; i < l; i++ ) {
						// Remove element nodes and prevent memory leaks
						elem = this[i] || {};
						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 first, node, hasScripts,
			scripts, doc, fragment,
			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 ) {
							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 || "" ) &&
							!jQuery._data( 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.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) );
							}
						}
					}
				}

				// Fix #11809: Avoid leaking memory
				fragment = first = null;
			}
		}

		return this;
	}
});

jQuery.each({
	appendTo: "append",
	prependTo: "prepend",
	insertBefore: "before",
	insertAfter: "after",
	replaceAll: "replaceWith"
}, function( name, original ) {
	jQuery.fn[ name ] = function( selector ) {
		var elems,
			i = 0,
			ret = [],
			insert = jQuery( selector ),
			last = insert.length - 1;

		for ( ; i <= last; i++ ) {
			elems = i === last ? this : this.clone(true);
			jQuery( insert[i] )[ original ]( elems );

			// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
			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 optmization) 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 ].contentWindow || iframe[ 0 ].contentDocument ).document;

			// Support: IE
			doc.write();
			doc.close();

			display = actualDisplay( nodeName, doc );
			iframe.detach();
		}

		// Store the correct default display
		elemdisplay[ nodeName ] = display;
	}

	return display;
}


(function() {
	var shrinkWrapBlocksVal;

	support.shrinkWrapBlocks = function() {
		if ( shrinkWrapBlocksVal != null ) {
			return shrinkWrapBlocksVal;
		}

		// Will be changed later if needed.
		shrinkWrapBlocksVal = false;

		// Minified: var b,c,d
		var div, body, container;

		body = document.getElementsByTagName( "body" )[ 0 ];
		if ( !body || !body.style ) {
			// Test fired too early or in an unsupported environment, exit.
			return;
		}

		// Setup
		div = document.createElement( "div" );
		container = document.createElement( "div" );
		container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
		body.appendChild( container ).appendChild( div );

		// Support: IE6
		// Check if elements with layout shrink-wrap their children
		if ( typeof div.style.zoom !== strundefined ) {
			// Reset CSS: box-sizing; display; margin; border
			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:1px;width:1px;zoom:1";
			div.appendChild( document.createElement( "div" ) ).style.width = "5px";
			shrinkWrapBlocksVal = div.offsetWidth !== 3;
		}

		body.removeChild( container );

		return shrinkWrapBlocksVal;
	};

})();
var rmargin = (/^margin/);

var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );



var getStyles, curCSS,
	rposition = /^(top|right|bottom|left)$/;

if ( window.getComputedStyle ) {
	getStyles = function( elem ) {
		return elem.ownerDocument.defaultView.getComputedStyle( elem, null );
	};

	curCSS = function( elem, name, computed ) {
		var width, minWidth, maxWidth, ret,
			style = elem.style;

		computed = computed || getStyles( elem );

		// getPropertyValue is only needed for .css('filter') in IE9, see #12537
		ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined;

		if ( computed ) {

			if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
				ret = jQuery.style( elem, name );
			}

			// A tribute to the "awesome hack by Dean Edwards"
			// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
			// Safari 5.1.7 (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;
			}
		}

		// Support: IE
		// IE returns zIndex value as an integer.
		return ret === undefined ?
			ret :
			ret + "";
	};
} else if ( document.documentElement.currentStyle ) {
	getStyles = function( elem ) {
		return elem.currentStyle;
	};

	curCSS = function( elem, name, computed ) {
		var left, rs, rsLeft, ret,
			style = elem.style;

		computed = computed || getStyles( elem );
		ret = computed ? computed[ name ] : undefined;

		// Avoid setting ret to empty string here
		// so we don't default to auto
		if ( ret == null && style && style[ name ] ) {
			ret = style[ name ];
		}

		// From the awesome hack by Dean Edwards
		// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291

		// If we're not dealing with a regular pixel number
		// but a number that has a weird ending, we need to convert it to pixels
		// but not position css attributes, as those are proportional to the parent element instead
		// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
		if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {

			// Remember the original values
			left = style.left;
			rs = elem.runtimeStyle;
			rsLeft = rs && rs.left;

			// Put in the new values to get a computed value out
			if ( rsLeft ) {
				rs.left = elem.currentStyle.left;
			}
			style.left = name === "fontSize" ? "1em" : ret;
			ret = style.pixelLeft + "px";

			// Revert the changed values
			style.left = left;
			if ( rsLeft ) {
				rs.left = rsLeft;
			}
		}

		// Support: IE
		// IE returns zIndex value as an integer.
		return ret === undefined ?
			ret :
			ret + "" || "auto";
	};
}




function addGetHookIf( conditionFn, hookFn ) {
	// Define the hook, we'll check on the first run if it's really needed.
	return {
		get: function() {
			var condition = conditionFn();

			if ( condition == null ) {
				// The test was not ready at this point; screw the hook this time
				// but check again when needed next time.
				return;
			}

			if ( condition ) {
				// Hook not needed (or it's not possible to use it due to missing dependency),
				// remove it.
				// Since there are no other hooks for marginRight, remove the whole object.
				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() {
	// Minified: var b,c,d,e,f,g, h,i
	var div, style, a, pixelPositionVal, boxSizingReliableVal,
		reliableHiddenOffsetsVal, reliableMarginRightVal;

	// Setup
	div = document.createElement( "div" );
	div.innerHTML = "  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
	a = div.getElementsByTagName( "a" )[ 0 ];
	style = a && a.style;

	// Finish early in limited (non-browser) environments
	if ( !style ) {
		return;
	}

	style.cssText = "float:left;opacity:.5";

	// Support: IE<9
	// Make sure that element opacity exists (as opposed to filter)
	support.opacity = style.opacity === "0.5";

	// Verify style float existence
	// (IE uses styleFloat instead of cssFloat)
	support.cssFloat = !!style.cssFloat;

	div.style.backgroundClip = "content-box";
	div.cloneNode( true ).style.backgroundClip = "";
	support.clearCloneStyle = div.style.backgroundClip === "content-box";

	// Support: Firefox<29, Android 2.3
	// Vendor-prefix box-sizing
	support.boxSizing = style.boxSizing === "" || style.MozBoxSizing === "" ||
		style.WebkitBoxSizing === "";

	jQuery.extend(support, {
		reliableHiddenOffsets: function() {
			if ( reliableHiddenOffsetsVal == null ) {
				computeStyleTests();
			}
			return reliableHiddenOffsetsVal;
		},

		boxSizingReliable: function() {
			if ( boxSizingReliableVal == null ) {
				computeStyleTests();
			}
			return boxSizingReliableVal;
		},

		pixelPosition: function() {
			if ( pixelPositionVal == null ) {
				computeStyleTests();
			}
			return pixelPositionVal;
		},

		// Support: Android 2.3
		reliableMarginRight: function() {
			if ( reliableMarginRightVal == null ) {
				computeStyleTests();
			}
			return reliableMarginRightVal;
		}
	});

	function computeStyleTests() {
		// Minified: var b,c,d,j
		var div, body, container, contents;

		body = document.getElementsByTagName( "body" )[ 0 ];
		if ( !body || !body.style ) {
			// Test fired too early or in an unsupported environment, exit.
			return;
		}

		// Setup
		div = document.createElement( "div" );
		container = document.createElement( "div" );
		container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
		body.appendChild( container ).appendChild( div );

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

		// Support: IE<9
		// Assume reasonable values in the absence of getComputedStyle
		pixelPositionVal = boxSizingReliableVal = false;
		reliableMarginRightVal = true;

		// Check for getComputedStyle so that this code is not run in IE<9.
		if ( window.getComputedStyle ) {
			pixelPositionVal = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
			boxSizingReliableVal =
				( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";

			// Support: Android 2.3
			// 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
			contents = div.appendChild( document.createElement( "div" ) );

			// Reset CSS: box-sizing; display; margin; border; padding
			contents.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";
			contents.style.marginRight = contents.style.width = "0";
			div.style.width = "1px";

			reliableMarginRightVal =
				!parseFloat( ( window.getComputedStyle( contents, null ) || {} ).marginRight );
		}

		// Support: IE8
		// Check if table cells still have offsetWidth/Height when they are set
		// to display:none and there are still other visible table cells in a
		// table row; if so, offsetWidth/Height are not reliable for use when
		// determining if an element has been hidden directly using
		// display:none (it is still safe to use offsets if a parent element is
		// hidden; don safety goggles and see bug #4512 for more information).
		div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
		contents = div.getElementsByTagName( "td" );
		contents[ 0 ].style.cssText = "margin:0;border:0;padding:0;display:none";
		reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0;
		if ( reliableHiddenOffsetsVal ) {
			contents[ 0 ].style.display = "";
			contents[ 1 ].style.display = "none";
			reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0;
		}

		body.removeChild( container );
	}

})();


// 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
		ralpha = /alpha\([^)]*\)/i,
	ropacity = /opacity\s*=\s*([^)]*)/,

	// 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.charAt(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 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 ] = jQuery._data( 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 ] = jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) );
			}
		} else {
			hidden = isHidden( elem );

			if ( display && display !== "none" || !hidden ) {
				jQuery._data( 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;
}

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 = support.boxSizing && 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;
		}

		// we need the 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";
}

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: {
		// normalize float css property
		"float": support.cssFloat ? "cssFloat" : "styleFloat"
	},

	// 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
		// followed by the unprefixed version
		hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];

		// Check if we're setting a value
		if ( value !== undefined ) {
			type = typeof value;

			// convert relative number strings (+= 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. See: #7116
			if ( value == null || value !== value ) {
				return;
			}

			// If a number was passed in, add 'px' to the (except for certain CSS properties)
			if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
				value += "px";
			}

			// Fixes #8908, it can be done more correctly by specifing setters in cssHooks,
			// but it would mean to define eight (for every problematic property) identical functions
			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 ) {

				// Support: IE
				// Swallow errors from 'invalid' CSS values (#5509)
				try {
					style[ name ] = value;
				} catch(e) {}
			}

		} 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 num, val, 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 ) );

		// gets hook for the prefixed version
		// followed by the unprefixed version
		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 ];
		}

		// Return, converting to number 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
				// however, it must have a current display style that would benefit from this
				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,
					support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
					styles
				) : 0
			);
		}
	};
});

if ( !support.opacity ) {
	jQuery.cssHooks.opacity = {
		get: function( elem, computed ) {
			// IE uses filters for opacity
			return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
				( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
				computed ? "1" : "";
		},

		set: function( elem, value ) {
			var style = elem.style,
				currentStyle = elem.currentStyle,
				opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
				filter = currentStyle && currentStyle.filter || style.filter || "";

			// IE has trouble with opacity if it does not have layout
			// Force it by setting the zoom level
			style.zoom = 1;

			// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
			// if value === "", then remove inline opacity #12685
			if ( ( value >= 1 || value === "" ) &&
					jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
					style.removeAttribute ) {

				// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
				// if "filter:" is present at all, clearType is disabled, we want to avoid this
				// style.removeAttribute is IE Only, but so apparently is this code path...
				style.removeAttribute( "filter" );

				// if there is no filter style applied in a css rule or unset inline opacity, we are done
				if ( value === "" || currentStyle && !currentStyle.filter ) {
					return;
				}
			}

			// otherwise, set new filter values
			style.filter = ralpha.test( filter ) ?
				filter.replace( ralpha, opacity ) :
				filter + " " + opacity;
		}
	};
}

jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight,
	function( elem, computed ) {
		if ( computed ) {
			// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
			// Work around by temporarily setting element display to inline-block
			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
			// so, 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 its
			// 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: IE <=9
// 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 a string for doubling factor 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()
				// And breaking 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,
		attrs = { height: type },
		i = 0;

	// if we include width, step value is 1 to do all cssExpand values,
	// if we don't include width, 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 = jQuery._data( 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() {
			// doing this makes sure that the complete handler will be 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 IE does 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" ?
			jQuery._data( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display;

		if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) {

			// inline-level elements accept inline-block;
			// block-level elements need to be inline with layout
			if ( !support.inlineBlockNeedsLayout || defaultDisplay( elem.nodeName ) === "inline" ) {
				style.display = "inline-block";
			} else {
				style.zoom = 1;
			}
		}
	}

	if ( opts.overflow ) {
		style.overflow = "hidden";
		if ( !support.shrinkWrapBlocks() ) {
			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 = jQuery._data( 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;
			jQuery._removeData( 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 wont overwrite keys already present.
			// also - reusing 'index' from above 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 ),
				// 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 || jQuery._data( 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 = jQuery._data( 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 = jQuery._data( 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,
		timers = jQuery.timers,
		i = 0;

	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() {
	// Minified: var a,b,c,d,e
	var input, div, select, a, opt;

	// Setup
	div = document.createElement( "div" );
	div.setAttribute( "className", "t" );
	div.innerHTML = "  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
	a = div.getElementsByTagName("a")[ 0 ];

	// First batch of tests.
	select = document.createElement("select");
	opt = select.appendChild( document.createElement("option") );
	input = div.getElementsByTagName("input")[ 0 ];

	a.style.cssText = "top:1px";

	// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
	support.getSetAttribute = div.className !== "t";

	// Get the style information from getAttribute
	// (IE uses .cssText instead)
	support.style = /top/.test( a.getAttribute("style") );

	// Make sure that URLs aren't manipulated
	// (IE normalizes it by default)
	support.hrefNormalized = a.getAttribute("href") === "/a";

	// Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
	support.checkOn = !!input.value;

	// Make sure that a selected-by-default option has a working selected property.
	// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
	support.optSelected = opt.selected;

	// Tests for enctype support on a form (#6743)
	support.enctype = !!document.createElement("form").enctype;

	// Make sure that the options inside disabled selects aren't marked as disabled
	// (WebKit marks them as disabled)
	select.disabled = true;
	support.optDisabled = !opt.disabled;

	// Support: IE8 only
	// Check if we can trust getAttribute("value")
	input = document.createElement( "input" );
	input.setAttribute( "value", "" );
	support.input = input.getAttribute( "value" ) === "";

	// Check if an input maintains its value after becoming a radio
	input.value = "t";
	input.setAttribute( "type", "radio" );
	support.radioValue = input.value === "t";
})();


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

					// oldIE 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 ( jQuery.inArray( jQuery.valHooks.option.get( option ), values ) >= 0 ) {

						// Support: IE6
						// When new option element is added to select box we need to
						// force reflow of newly added node in order to workaround delay
						// of initialization properties
						try {
							option.selected = optionSet = true;

						} catch ( _ ) {

							// Will be executed only in IE6
							option.scrollHeight;
						}

					} else {
						option.selected = false;
					}
				}

				// Force browsers to behave consistently when non-matching value is set
				if ( !optionSet ) {
					elem.selectedIndex = -1;
				}

				return options;
			}
		}
	}
});

// 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 ) {
			// Support: Webkit
			// "" is returned instead of "on" if a value isn't specified
			return elem.getAttribute("value") === null ? "on" : elem.value;
		};
	}
});




var nodeHook, boolHook,
	attrHandle = jQuery.expr.attrHandle,
	ruseDefault = /^(?:checked|selected)$/i,
	getSetAttribute = support.getSetAttribute,
	getSetInput = support.input;

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
					if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
						elem[ propName ] = false;
					// Support: IE<9
					// Also clear defaultChecked/defaultSelected (if appropriate)
					} else {
						elem[ jQuery.camelCase( "default-" + name ) ] =
							elem[ propName ] = false;
					}

				// See #9699 for explanation of this approach (setting first, then removal)
				} else {
					jQuery.attr( elem, name, "" );
				}

				elem.removeAttribute( getSetAttribute ? name : propName );
			}
		}
	},

	attrHooks: {
		type: {
			set: function( elem, value ) {
				if ( !support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
					// Setting the type on a radio button after the value resets the value in IE6-9
					// Reset value to default in case type is set after value during creation
					var val = elem.value;
					elem.setAttribute( "type", value );
					if ( val ) {
						elem.value = val;
					}
					return value;
				}
			}
		}
	}
});

// Hook for boolean attributes
boolHook = {
	set: function( elem, value, name ) {
		if ( value === false ) {
			// Remove boolean attributes when set to false
			jQuery.removeAttr( elem, name );
		} else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
			// IE<8 needs the *property* name
			elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name );

		// Use defaultChecked and defaultSelected for oldIE
		} else {
			elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
		}

		return name;
	}
};

// Retrieve booleans specially
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {

	var getter = attrHandle[ name ] || jQuery.find.attr;

	attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( 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;
		} :
		function( elem, name, isXML ) {
			if ( !isXML ) {
				return elem[ jQuery.camelCase( "default-" + name ) ] ?
					name.toLowerCase() :
					null;
			}
		};
});

// fix oldIE attroperties
if ( !getSetInput || !getSetAttribute ) {
	jQuery.attrHooks.value = {
		set: function( elem, value, name ) {
			if ( jQuery.nodeName( elem, "input" ) ) {
				// Does not return so that setAttribute is also used
				elem.defaultValue = value;
			} else {
				// Use nodeHook if defined (#1954); otherwise setAttribute is fine
				return nodeHook && nodeHook.set( elem, value, name );
			}
		}
	};
}

// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {

	// Use this for any attribute in IE6/7
	// This fixes almost every IE6/7 issue
	nodeHook = {
		set: function( elem, value, name ) {
			// Set the existing or create a new attribute node
			var ret = elem.getAttributeNode( name );
			if ( !ret ) {
				elem.setAttributeNode(
					(ret = elem.ownerDocument.createAttribute( name ))
				);
			}

			ret.value = value += "";

			// Break association with cloned elements by also using setAttribute (#9646)
			if ( name === "value" || value === elem.getAttribute( name ) ) {
				return value;
			}
		}
	};

	// Some attributes are constructed with empty-string values when not defined
	attrHandle.id = attrHandle.name = attrHandle.coords =
		function( elem, name, isXML ) {
			var ret;
			if ( !isXML ) {
				return (ret = elem.getAttributeNode( name )) && ret.value !== "" ?
					ret.value :
					null;
			}
		};

	// Fixing value retrieval on a button requires this module
	jQuery.valHooks.button = {
		get: function( elem, name ) {
			var ret = elem.getAttributeNode( name );
			if ( ret && ret.specified ) {
				return ret.value;
			}
		},
		set: nodeHook.set
	};

	// Set contenteditable to false on removals(#10429)
	// Setting to empty string throws an error as an invalid value
	jQuery.attrHooks.contenteditable = {
		set: function( elem, value, name ) {
			nodeHook.set( elem, value === "" ? false : value, name );
		}
	};

	// Set width and height to auto instead of 0 on empty string( Bug #8150 )
	// This is for removals
	jQuery.each([ "width", "height" ], function( i, name ) {
		jQuery.attrHooks[ name ] = {
			set: function( elem, value ) {
				if ( value === "" ) {
					elem.setAttribute( name, "auto" );
					return value;
				}
			}
		};
	});
}

if ( !support.style ) {
	jQuery.attrHooks.style = {
		get: function( elem ) {
			// Return undefined in the case of empty string
			// Note: IE uppercases css property names, but if we were to .toLowerCase()
			// .cssText, that would destroy case senstitivity in URL's, like in "background"
			return elem.style.cssText || undefined;
		},
		set: function( elem, value ) {
			return ( elem.style.cssText = value + "" );
		}
	};
}




var rfocusable = /^(?:input|select|textarea|button|object)$/i,
	rclickable = /^(?:a|area)$/i;

jQuery.fn.extend({
	prop: function( name, value ) {
		return access( this, jQuery.prop, name, value, arguments.length > 1 );
	},

	removeProp: function( name ) {
		name = jQuery.propFix[ name ] || name;
		return this.each(function() {
			// try/catch handles cases where IE balks (such as removing a property on window)
			try {
				this[ name ] = undefined;
				delete this[ name ];
			} catch( e ) {}
		});
	}
});

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 ) {
				// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
				// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
				// Use proper attribute retrieval(#12072)
				var tabindex = jQuery.find.attr( elem, "tabindex" );

				return tabindex ?
					parseInt( tabindex, 10 ) :
					rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
						0 :
						-1;
			}
		}
	}
});

// Some attributes require a special call on IE
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !support.hrefNormalized ) {
	// href/src property should get the full normalized URL (#10299/#12915)
	jQuery.each([ "href", "src" ], function( i, name ) {
		jQuery.propHooks[ name ] = {
			get: function( elem ) {
				return elem.getAttribute( name, 4 );
			}
		};
	});
}

// Support: Safari, IE9+
// mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !support.optSelected ) {
	jQuery.propHooks.selected = {
		get: function( elem ) {
			var parent = elem.parentNode;

			if ( parent ) {
				parent.selectedIndex;

				// Make sure that it also works with optgroups, see #5701
				if ( 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;
});

// IE6/7 call enctype encoding
if ( !support.enctype ) {
	jQuery.propFix.enctype = "encoding";
}




var rclass = /[\t\r\n\f]/g;

jQuery.fn.extend({
	addClass: function( value ) {
		var classes, elem, cur, clazz, j, finalValue,
			i = 0,
			len = this.length,
			proceed = typeof value === "string" && value;

		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,
			i = 0,
			len = this.length,
			proceed = arguments.length === 0 || typeof value === "string" && value;

		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
					jQuery._data( 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 ? "" : jQuery._data( 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;
	}
});




// 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 = (/\?/);



var rvalidtokens = /(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;

jQuery.parseJSON = function( data ) {
	// Attempt to parse using the native JSON parser first
	if ( window.JSON && window.JSON.parse ) {
		// Support: Android 2.3
		// Workaround failure to string-cast null input
		return window.JSON.parse( data + "" );
	}

	var requireNonComma,
		depth = null,
		str = jQuery.trim( data + "" );

	// Guard against invalid (and possibly dangerous) input by ensuring that nothing remains
	// after removing valid tokens
	return str && !jQuery.trim( str.replace( rvalidtokens, function( token, comma, open, close ) {

		// Force termination if we see a misplaced comma
		if ( requireNonComma && comma ) {
			depth = 0;
		}

		// Perform no more replacements after returning to outermost depth
		if ( depth === 0 ) {
			return token;
		}

		// Commas must not follow "[", "{", or ","
		requireNonComma = open || comma;

		// Determine new depth
		// array/object open ("[" or "{"): depth += true - false (increment)
		// array/object close ("]" or "}"): depth += false - true (decrement)
		// other cases ("," or primitive): depth += true - true (numeric cast)
		depth += !close - !open;

		// Remove this token
		return "";
	}) ) ?
		( Function( "return " + str ) )() :
		jQuery.error( "Invalid JSON: " + data );
};


// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
	var xml, tmp;
	if ( !data || typeof data !== "string" ) {
		return null;
	}
	try {
		if ( window.DOMParser ) { // Standard
			tmp = new DOMParser();
			xml = tmp.parseFromString( data, "text/xml" );
		} else { // IE
			xml = new ActiveXObject( "Microsoft.XMLDOM" );
			xml.async = "false";
			xml.loadXML( data );
		}
	} catch( e ) {
		xml = undefined;
	}
	if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
		jQuery.error( "Invalid XML: " + data );
	}
	return xml;
};


var
	// Document location
	ajaxLocParts,
	ajaxLocation,

	rhash = /#.*$/,
	rts = /([?&])_=[^&]*/,
	rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
	// #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("*");

// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
	ajaxLocation = location.href;
} catch( e ) {
	// Use the href attribute of an A element
	// since IE will modify it given document.location
	ajaxLocation = document.createElement( "a" );
	ajaxLocation.href = "";
	ajaxLocation = ajaxLocation.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.charAt( 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 deep, key,
		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 firstDataType, ct, finalDataType, type,
		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 // Cross-domain detection vars
			parts,
			// Loop variable
			i,
			// URL without anti-cache param
			cacheURL,
			// Response headers as string
			responseHeadersString,
			// timeout handle
			timeoutTimer,

			// To know if global events are to be dispatched
			fireGlobals,

			transport,
			// Response headers
			responseHeaders,
			// 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 (#5866: IE7 issue with protocol-less urls)
		// 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
		fireGlobals = 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 {
				// We extract error from statusText
				// then normalize statusText and status 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
		});
	};
});

// 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._evalUrl = function( url ) {
	return jQuery.ajax({
		url: url,
		type: "GET",
		dataType: "script",
		async: false,
		global: false,
		"throws": true
	});
};


jQuery.fn.extend({
	wrapAll: function( html ) {
		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
			var 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.firstChild && elem.firstChild.nodeType === 1 ) {
					elem = elem.firstChild;
				}

				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 ||
		(!support.reliableHiddenOffsets() &&
			((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};

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


// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject !== undefined ?
	// Support: IE6+
	function() {

		// XHR cannot access local files, always use ActiveX for that case
		return !this.isLocal &&

			// Support: IE7-8
			// oldIE XHR does not support non-RFC2616 methods (#13240)
			// See http://msdn.microsoft.com/en-us/library/ie/ms536648(v=vs.85).aspx
			// and http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9
			// Although this check for six methods instead of eight
			// since IE also does not support "trace" and "connect"
			/^(get|post|head|put|delete|options)$/i.test( this.type ) &&

			createStandardXHR() || createActiveXHR();
	} :
	// For all other browsers, use the standard XMLHttpRequest object
	createStandardXHR;

var xhrId = 0,
	xhrCallbacks = {},
	xhrSupported = jQuery.ajaxSettings.xhr();

// Support: IE<10
// Open requests must be manually aborted on unload (#5280)
if ( window.ActiveXObject ) {
	jQuery( window ).on( "unload", function() {
		for ( var key in xhrCallbacks ) {
			xhrCallbacks[ key ]( undefined, true );
		}
	});
}

// Determine support properties
support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
xhrSupported = support.ajax = !!xhrSupported;

// Create transport if the browser can provide an xhr
if ( xhrSupported ) {

	jQuery.ajaxTransport(function( options ) {
		// Cross domain only allowed if supported through XMLHttpRequest
		if ( !options.crossDomain || support.cors ) {

			var callback;

			return {
				send: function( headers, complete ) {
					var i,
						xhr = options.xhr(),
						id = ++xhrId;

					// Open the socket
					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 ) {
						// Support: IE<9
						// IE's ActiveXObject throws a 'Type Mismatch' exception when setting
						// request header to a null-value.
						//
						// To keep consistent with other XHR implementations, cast the value
						// to string and ignore `undefined`.
						if ( headers[ i ] !== undefined ) {
							xhr.setRequestHeader( i, headers[ i ] + "" );
						}
					}

					// Do send the request
					// This may raise an exception which is actually
					// handled in jQuery.ajax (so no try/catch here)
					xhr.send( ( options.hasContent && options.data ) || null );

					// Listener
					callback = function( _, isAbort ) {
						var status, statusText, responses;

						// Was never called and is aborted or complete
						if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
							// Clean up
							delete xhrCallbacks[ id ];
							callback = undefined;
							xhr.onreadystatechange = jQuery.noop;

							// Abort manually if needed
							if ( isAbort ) {
								if ( xhr.readyState !== 4 ) {
									xhr.abort();
								}
							} else {
								responses = {};
								status = xhr.status;

								// Support: IE<10
								// Accessing binary-data responseText throws an exception
								// (#11426)
								if ( typeof xhr.responseText === "string" ) {
									responses.text = xhr.responseText;
								}

								// Firefox throws an exception when accessing
								// statusText for faulty cross-domain requests
								try {
									statusText = xhr.statusText;
								} catch( e ) {
									// We normalize with Webkit giving an empty statusText
									statusText = "";
								}

								// Filter status for non standard behaviors

								// If the request is local and we have data: assume a success
								// (success with no data won't get notified, that's the best we
								// can do given current implementations)
								if ( !status && options.isLocal && !options.crossDomain ) {
									status = responses.text ? 200 : 404;
								// IE - #1450: sometimes returns 1223 when it should be 204
								} else if ( status === 1223 ) {
									status = 204;
								}
							}
						}

						// Call complete if needed
						if ( responses ) {
							complete( status, statusText, responses, xhr.getAllResponseHeaders() );
						}
					};

					if ( !options.async ) {
						// if we're in sync mode we fire the callback
						callback();
					} else if ( xhr.readyState === 4 ) {
						// (IE6 & IE7) if it's in cache and has been
						// retrieved directly we need to fire the callback
						setTimeout( callback );
					} else {
						// Add to the list of active xhr callbacks
						xhr.onreadystatechange = xhrCallbacks[ id ] = callback;
					}
				},

				abort: function() {
					if ( callback ) {
						callback( undefined, true );
					}
				}
			};
		}
	});
}

// Functions to create xhrs
function createStandardXHR() {
	try {
		return new window.XMLHttpRequest();
	} catch( e ) {}
}

function createActiveXHR() {
	try {
		return new window.ActiveXObject( "Microsoft.XMLHTTP" );
	} catch( e ) {}
}




// 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 global
jQuery.ajaxPrefilter( "script", function( s ) {
	if ( s.cache === undefined ) {
		s.cache = false;
	}
	if ( s.crossDomain ) {
		s.type = "GET";
		s.global = false;
	}
});

// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {

	// This transport only deals with cross domain requests
	if ( s.crossDomain ) {

		var script,
			head = document.head || jQuery("head")[0] || document.documentElement;

		return {

			send: function( _, callback ) {

				script = document.createElement("script");

				script.async = true;

				if ( s.scriptCharset ) {
					script.charset = s.scriptCharset;
				}

				script.src = s.url;

				// Attach handlers for all browsers
				script.onload = script.onreadystatechange = function( _, isAbort ) {

					if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {

						// Handle memory leak in IE
						script.onload = script.onreadystatechange = null;

						// Remove the script
						if ( script.parentNode ) {
							script.parentNode.removeChild( script );
						}

						// Dereference the script
						script = null;

						// Callback if not abort
						if ( !isAbort ) {
							callback( 200, "success" );
						}
					}
				};

				// Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
				// Use native DOM manipulation to avoid our domManip AJAX trickery
				head.insertBefore( script, head.firstChild );
			},

			abort: function() {
				if ( script ) {
					script.onload( undefined, true );
				}
			}
		};
	}
});




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, response, type,
		self = this,
		off = url.indexOf(" ");

	if ( off >= 0 ) {
		selector = jQuery.trim( url.slice( off, url.length ) );
		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;
};




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 || elem.parentWindow :
			false;
}

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" ) &&
			jQuery.inArray("auto", [ curCSSTop, curCSSLeft ] ) > -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,
			box = { top: 0, left: 0 },
			elem = this[ 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;
		}

		// If we don't have gBCR, just use 0,0 rather than error
		// BlackBerry 5, iOS 3 (original iPhone)
		if ( typeof elem.getBoundingClientRect !== strundefined ) {
			box = elem.getBoundingClientRect();
		}
		win = getWindow( doc );
		return {
			top: box.top  + ( win.pageYOffset || docElem.scrollTop )  - ( docElem.clientTop  || 0 ),
			left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
		};
	},

	position: function() {
		if ( !this[ 0 ] ) {
			return;
		}

		var offsetParent, offset,
			parentOffset = { top: 0, left: 0 },
			elem = this[ 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" ) {
			// we assume that getBoundingClientRect is available 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
		// note: when an element has margin: auto the offsetLeft and marginLeft
		// are the same in Safari causing offset.left to incorrectly be 0
		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 = /Y/.test( prop );

	jQuery.fn[ method ] = function( val ) {
		return access( this, function( elem, method, val ) {
			var win = getWindow( elem );

			if ( val === undefined ) {
				return win ? (prop in win) ? win[ prop ] :
					win.document.documentElement[ method ] :
					elem[ method ];
			}

			if ( win ) {
				win.scrollTo(
					!top ? val : jQuery( win ).scrollLeft(),
					top ? val : jQuery( win ).scrollTop()
				);

			} else {
				elem[ method ] = val;
			}
		}, method, val, arguments.length, null );
	};
});

// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we 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
					// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
					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;

}));

//     Backbone.js 1.1.0

//     (c) 2010-2011 Jeremy Ashkenas, DocumentCloud Inc.
//     (c) 2011-2013 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(root, factory) {
  // Set up Backbone appropriately for the environment.
  if (typeof exports !== 'undefined') {
    // Node/CommonJS, no need for jQuery in that case.
    factory(root, exports, require('underscore'));
  } else if (typeof define === 'function' && define.amd) {
    // AMD
    define('backbone',['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, _, $);
    });
  } else {
    // Browser globals
    root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$));
  }
}(this, 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 local references to array methods we'll want to use later.
  var array = [];
  var push = array.push;
  var slice = array.slice;
  var splice = array.splice;

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

  // For Backbone's purposes, jQuery, Zepto, or Ender 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 ... 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;

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

  // A module that can be mixed in to *any object* in order to provide it with
  // custom events. You may bind with `on` or remove with `off` callback
  // functions to an event; `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 = {

    // Bind an event to a `callback` function. Passing `"all"` will bind
    // the callback to all events fired.
    on: function(name, callback, context) {
      if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this;
      this._events || (this._events = {});
      var events = this._events[name] || (this._events[name] = []);
      events.push({callback: callback, context: context, ctx: context || this});
      return this;
    },

    // Bind an event to only be triggered a single time. After the first time
    // the callback is invoked, it will be removed.
    once: function(name, callback, context) {
      if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this;
      var self = this;
      var once = _.once(function() {
        self.off(name, once);
        callback.apply(this, arguments);
      });
      once._callback = callback;
      return this.on(name, once, context);
    },

    // 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.
    off: function(name, callback, context) {
      var retain, ev, events, names, i, l, j, k;
      if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this;
      if (!name && !callback && !context) {
        this._events = {};
        return this;
      }
      names = name ? [name] : _.keys(this._events);
      for (i = 0, l = names.length; i < l; i++) {
        name = names[i];
        if (events = this._events[name]) {
          this._events[name] = retain = [];
          if (callback || context) {
            for (j = 0, k = events.length; j < k; j++) {
              ev = events[j];
              if ((callback && callback !== ev.callback && callback !== ev.callback._callback) ||
                  (context && context !== ev.context)) {
                retain.push(ev);
              }
            }
          }
          if (!retain.length) delete this._events[name];
        }
      }

      return this;
    },

    // 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).
    trigger: function(name) {
      if (!this._events) return this;
      var args = slice.call(arguments, 1);
      if (!eventsApi(this, 'trigger', name, args)) return this;
      var events = this._events[name];
      var allEvents = this._events.all;
      if (events) triggerEvents(events, args);
      if (allEvents) triggerEvents(allEvents, arguments);
      return this;
    },

    // Tell this object to stop listening to either specific events ... or
    // to every object it's currently listening to.
    stopListening: function(obj, name, callback) {
      var listeningTo = this._listeningTo;
      if (!listeningTo) return this;
      var remove = !name && !callback;
      if (!callback && typeof name === 'object') callback = this;
      if (obj) (listeningTo = {})[obj._listenId] = obj;
      for (var id in listeningTo) {
        obj = listeningTo[id];
        obj.off(name, callback, this);
        if (remove || _.isEmpty(obj._events)) delete this._listeningTo[id];
      }
      return this;
    }

  };

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

  // Implement fancy features of the Events API such as multiple event
  // names `"change blur"` and jQuery-style event maps `{change: action}`
  // in terms of the existing API.
  var eventsApi = function(obj, action, name, rest) {
    if (!name) return true;

    // Handle event maps.
    if (typeof name === 'object') {
      for (var key in name) {
        obj[action].apply(obj, [key, name[key]].concat(rest));
      }
      return false;
    }

    // Handle space separated event names.
    if (eventSplitter.test(name)) {
      var names = name.split(eventSplitter);
      for (var i = 0, l = names.length; i < l; i++) {
        obj[action].apply(obj, [names[i]].concat(rest));
      }
      return false;
    }

    return true;
  };

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

  var listenMethods = {listenTo: 'on', listenToOnce: 'once'};

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

  // 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('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.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',

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

    // 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) {
      var attr, attrs, unset, changes, silent, changing, prev, current;
      if (key == null) return this;

      // Handle both `"key", value` and `{key: value}` -style arguments.
      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.
      unset           = options.unset;
      silent          = options.silent;
      changes         = [];
      changing        = this._changing;
      this._changing  = true;

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

      // Check for changes of `id`.
      if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];

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

      // Trigger all relevant attribute changes.
      if (!silent) {
        if (changes.length) this._pending = true;
        for (var i = 0, l = changes.length; i < l; 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) {
          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 val, changed = false;
      var old = this._changing ? this._previousAttributes : this.attributes;
      for (var attr in diff) {
        if (_.isEqual(old[attr], (val = diff[attr]))) continue;
        (changed || (changed = {}))[attr] = val;
      }
      return changed;
    },

    // 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. If the server's representation of the
    // model differs from its current attributes, they will be overridden,
    // triggering a `"change"` event.
    fetch: function(options) {
      options = options ? _.clone(options) : {};
      if (options.parse === void 0) options.parse = true;
      var model = this;
      var success = options.success;
      options.success = function(resp) {
        if (!model.set(model.parse(resp, options), options)) return false;
        if (success) success(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) {
      var attrs, method, xhr, attributes = this.attributes;

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

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

      // 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 && !options.wait) {
        if (!this.set(attrs, options)) return false;
      } else {
        if (!this._validate(attrs, options)) return false;
      }

      // Set temporary attributes if `{wait: true}`.
      if (attrs && options.wait) {
        this.attributes = _.extend({}, attributes, attrs);
      }

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

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

      // Restore attributes.
      if (attrs && options.wait) 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 destroy = function() {
        model.trigger('destroy', model, model.collection, options);
      };

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

      if (this.isNew()) {
        options.success();
        return false;
      }
      wrapError(this, options);

      var xhr = this.sync('delete', this, options);
      if (!options.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;
      return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.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.id == null;
    },

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

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

  });

  // Underscore methods that we want to implement on the Model.
  var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit'];

  // Mix in each Underscore method as a proxy to `Model#attributes`.
  _.each(modelMethods, function(method) {
    Model.prototype[method] = function() {
      var args = slice.call(arguments);
      args.unshift(this.attributes);
      return _[method].apply(_, args);
    };
  });

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

  // If models tend to represent a single row of data, a Backbone Collection is
  // more analagous 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};

  // 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.
    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) {
      var singular = !_.isArray(models);
      models = singular ? [models] : _.clone(models);
      options || (options = {});
      var i, l, index, model;
      for (i = 0, l = models.length; i < l; i++) {
        model = models[i] = this.get(models[i]);
        if (!model) continue;
        delete this._byId[model.id];
        delete this._byId[model.cid];
        index = this.indexOf(model);
        this.models.splice(index, 1);
        this.length--;
        if (!options.silent) {
          options.index = index;
          model.trigger('remove', model, this, options);
        }
        this._removeReference(model);
      }
      return singular ? models[0] : models;
    },

    // 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) {
      options = _.defaults({}, options, setOptions);
      if (options.parse) models = this.parse(models, options);
      var singular = !_.isArray(models);
      models = singular ? (models ? [models] : []) : _.clone(models);
      var i, l, id, model, attrs, existing, sort;
      var at = options.at;
      var targetModel = this.model;
      var sortable = this.comparator && (at == null) && options.sort !== false;
      var sortAttr = _.isString(this.comparator) ? this.comparator : null;
      var toAdd = [], toRemove = [], modelMap = {};
      var add = options.add, merge = options.merge, remove = options.remove;
      var order = !sortable && add && remove ? [] : false;

      // Turn bare objects into model references, and prevent invalid models
      // from being added.
      for (i = 0, l = models.length; i < l; i++) {
        attrs = models[i];
        if (attrs instanceof Model) {
          id = model = attrs;
        } else {
          id = attrs[targetModel.prototype.idAttribute];
        }

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

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

          // Listen to added models' events, and index models for lookup by
          // `id` and by `cid`.
          model.on('all', this._onModelEvent, this);
          this._byId[model.cid] = model;
          if (model.id != null) this._byId[model.id] = model;
        }
        if (order) order.push(existing || model);
      }

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

      // See if sorting is needed, update `length` and splice in new models.
      if (toAdd.length || (order && order.length)) {
        if (sortable) sort = true;
        this.length += toAdd.length;
        if (at != null) {
          for (i = 0, l = toAdd.length; i < l; i++) {
            this.models.splice(at + i, 0, toAdd[i]);
          }
        } else {
          if (order) this.models.length = 0;
          var orderedModels = order || toAdd;
          for (i = 0, l = orderedModels.length; i < l; i++) {
            this.models.push(orderedModels[i]);
          }
        }
      }

      // 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, l = toAdd.length; i < l; i++) {
          (model = toAdd[i]).trigger('add', model, this, options);
        }
        if (sort || (order && order.length)) this.trigger('sort', 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 = {});
      for (var i = 0, l = this.models.length; i < l; i++) {
        this._removeReference(this.models[i]);
      }
      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);
      this.remove(model, options);
      return model;
    },

    // 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);
      this.remove(model, options);
      return model;
    },

    // 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;
      return this._byId[obj.id] || this._byId[obj.cid] || this._byId[obj];
    },

    // Get the model at the given index.
    at: function(index) {
      return this.models[index];
    },

    // Return models with matching attributes. Useful for simple cases of
    // `filter`.
    where: function(attrs, first) {
      if (_.isEmpty(attrs)) return first ? void 0 : [];
      return this[first ? 'find' : 'filter'](function(model) {
        for (var key in attrs) {
          if (attrs[key] !== model.get(key)) return false;
        }
        return true;
      });
    },

    // 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) {
      if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
      options || (options = {});

      // Run sort based on type of `comparator`.
      if (_.isString(this.comparator) || this.comparator.length === 1) {
        this.models = this.sortBy(this.comparator, this);
      } else {
        this.models.sort(_.bind(this.comparator, this));
      }

      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 = options ? _.clone(options) : {};
      if (options.parse === void 0) options.parse = true;
      var success = options.success;
      var collection = this;
      options.success = function(resp) {
        var method = options.reset ? 'reset' : 'set';
        collection[method](resp, options);
        if (success) success(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) : {};
      if (!(model = this._prepareModel(model, options))) return false;
      if (!options.wait) this.add(model, options);
      var collection = this;
      var success = options.success;
      options.success = function(model, resp, options) {
        if (options.wait) collection.add(model, options);
        if (success) success(model, resp, options);
      };
      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);
    },

    // 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 (attrs instanceof Model) {
        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 to sever a model's ties to a collection.
    _removeReference: function(model) {
      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 (model && event === 'change:' + model.idAttribute) {
        delete this._byId[model.previous(model.idAttribute)];
        if (model.id != null) this._byId[model.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 methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl',
    'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select',
    'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke',
    'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest',
    'tail', 'drop', 'last', 'without', 'difference', 'indexOf', 'shuffle',
    'lastIndexOf', 'isEmpty', 'chain'];

  // Mix in each Underscore method as a proxy to `Collection#models`.
  _.each(methods, function(method) {
    Collection.prototype[method] = function() {
      var args = slice.call(arguments);
      args.unshift(this.models);
      return _[method].apply(_, args);
    };
  });

  // Underscore methods that take a property name as an argument.
  var attributeMethods = ['groupBy', 'countBy', 'sortBy'];

  // Use attributes instead of properties.
  _.each(attributeMethods, function(method) {
    Collection.prototype[method] = function(value, context) {
      var iterator = _.isFunction(value) ? value : function(model) {
        return model.get(value);
      };
      return _[method](this.models, iterator, context);
    };
  });

  // 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');
    options || (options = {});
    _.extend(this, _.pick(options, viewOptions));
    this._ensureElement();
    this.initialize.apply(this, arguments);
    this.delegateEvents();
  };

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

  // List of view options to be merged 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.$el.remove();
      this.stopListening();
      return this;
    },

    // Change the view's element (`this.el` property), including event
    // re-delegation.
    setElement: function(element, delegate) {
      if (this.$el) this.undelegateEvents();
      this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
      this.el = this.$el[0];
      if (delegate !== false) this.delegateEvents();
      return this;
    },

    // 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`.
    // This only works for delegate-able events: not `focus`, `blur`, and
    // not `change`, `submit`, and `reset` in Internet Explorer.
    delegateEvents: function(events) {
      if (!(events || (events = _.result(this, 'events')))) return this;
      this.undelegateEvents();
      for (var key in events) {
        var method = events[key];
        if (!_.isFunction(method)) method = this[events[key]];
        if (!method) continue;

        var match = key.match(delegateEventSplitter);
        var eventName = match[1], selector = match[2];
        method = _.bind(method, this);
        eventName += '.delegateEvents' + this.cid;
        if (selector === '') {
          this.$el.on(eventName, method);
        } else {
          this.$el.on(eventName, selector, method);
        }
      }
      return this;
    },

    // Clears all callbacks previously bound to the view with `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() {
      this.$el.off('.delegateEvents' + this.cid);
      return this;
    },

    // 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');
        var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
        this.setElement($el, false);
      } else {
        this.setElement(_.result(this, 'el'), false);
      }
    }

  });

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

    // If we're sending a `PATCH` request, and we're in an old Internet Explorer
    // that still has ActiveX enabled by default, override jQuery to use that
    // for XHR instead. Remove this line when jQuery supports `PATCH` on IE8.
    if (params.type === 'PATCH' && noXhrPatch) {
      params.xhr = function() {
        return new ActiveXObject("Microsoft.XMLHTTP");
      };
    }

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

  var noXhrPatch = typeof window !== 'undefined' && !!window.ActiveXObject && !(window.XMLHttpRequest && (new XMLHttpRequest).dispatchEvent);

  // 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);
        callback && callback.apply(router, args);
        router.trigger.apply(router, ['route:' + name].concat(args));
        router.trigger('route', name, args);
        Backbone.history.trigger('route', router, name, args);
      });
      return this;
    },

    // 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 + '$');
    },

    // 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) {
        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 = [];
    _.bindAll(this, 'checkUrl');

    // 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 detecting MSIE.
  var isExplorer = /msie [\w.]+/;

  // Cached regex for removing a trailing slash.
  var trailingSlash = /\/$/;

  // Cached regex for stripping urls of hash and query.
  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,

    // 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 cross-browser normalized URL fragment, either from the URL,
    // the hash, or the override.
    getFragment: function(fragment, forcePushState) {
      if (fragment == null) {
        if (this._hasPushState || !this._wantsHashChange || forcePushState) {
          fragment = this.location.pathname;
          var root = this.root.replace(trailingSlash, '');
          if (!fragment.indexOf(root)) fragment = fragment.slice(root.length);
        } 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._wantsPushState  = !!this.options.pushState;
      this._hasPushState    = !!(this.options.pushState && this.history && this.history.pushState);
      var fragment          = this.getFragment();
      var docMode           = document.documentMode;
      var oldIE             = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));

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

      if (oldIE && this._wantsHashChange) {
        this.iframe = Backbone.$('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow;
        this.navigate(fragment);
      }

      // Depending on whether we're using pushState or hashes, and whether
      // 'onhashchange' is supported, determine how we check the URL state.
      if (this._hasPushState) {
        Backbone.$(window).on('popstate', this.checkUrl);
      } else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
        Backbone.$(window).on('hashchange', this.checkUrl);
      } else if (this._wantsHashChange) {
        this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
      }

      // Determine if we need to change the base url, for a pushState link
      // opened by a non-pushState browser.
      this.fragment = fragment;
      var loc = this.location;
      var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root;

      // 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 && !atRoot) {
          this.fragment = this.getFragment(null, true);
          this.location.replace(this.root + this.location.search + '#' + this.fragment);
          // 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 && atRoot && loc.hash) {
          this.fragment = this.getHash().replace(routeStripper, '');
          this.history.replaceState({}, document.title, this.root + this.fragment + loc.search);
        }

      }

      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() {
      Backbone.$(window).off('popstate', this.checkUrl).off('hashchange', this.checkUrl);
      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 (current === this.fragment && this.iframe) {
        current = this.getFragment(this.getHash(this.iframe));
      }
      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) {
      fragment = this.fragment = this.getFragment(fragment);
      return _.any(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};

      var url = this.root + (fragment = this.getFragment(fragment || ''));

      // Strip the fragment of the query and hash for matching.
      fragment = fragment.replace(pathStripper, '');

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

      // Don't include a trailing slash on the root.
      if (fragment === '' && url !== '/') url = url.slice(0, -1);

      // If pushState is available, we use it to set the fragment as a real URL.
      if (this._hasPushState) {
        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.getFragment(this.getHash(this.iframe)))) {
          // 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) this.iframe.document.open().close();
          this._updateHash(this.iframe.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's constructor.
    if (protoProps && _.has(protoProps, 'constructor')) {
      child = protoProps.constructor;
    } else {
      child = function(){ return parent.apply(this, arguments); };
    }

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

    // Set the prototype chain to inherit from `parent`, without calling
    // `parent`'s constructor function.
    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(model, resp, options);
      model.trigger('error', model, resp, options);
    };
  };

  return Backbone;
}));

(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('common/collection',["underscore", "backbone"], function(_, Backbone) {
    var Collection, _ref;
    return Collection = (function(_super) {
      __extends(Collection, _super);

      function Collection() {
        _ref = Collection.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      return Collection;

    })(Backbone.Collection);
  });

}).call(this);

/*
//@ sourceMappingURL=collection.js.map
*/;
/// <reference path="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;

    // 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");
            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);
        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);
            _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 = new XMLHttpRequest();
                xhr.open('POST', ajaxUrl);

                xhr.setRequestHeader('Content-Type', 'application/json');
                xhr.setRequestHeader('JSNLog-RequestId', JL.requestId);
                xhr.send(json);
            } catch (e) {
            }
        };
        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();
}
//# sourceMappingURL=jsnlog.js.map
;
(function() {
  define('common/logging',["jsnlog"], function(JL) {
    var logger, set_log_level;
    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]
      });
    };
    return {
      "logger": logger,
      "set_log_level": set_log_level
    };
  });

}).call(this);

/*
//@ sourceMappingURL=logging.js.map
*/;
(function() {
  var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('common/has_properties',["underscore", "backbone", "require", "./base", "./logging"], function(_, Backbone, require, base, Logging) {
    var HasProperties, logger, _is_ref;
    logger = Logging.logger;
    _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;
    };
    return HasProperties = (function(_super) {
      __extends(HasProperties, _super);

      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, prop_name, _i, _len, _ref;
        data = _.clone(this.attributes);
        _ref = _.keys(this.properties);
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          prop_name = _ref[_i];
          data[prop_name] = this.get(prop_name);
        }
        return data;
      };

      function HasProperties(attributes, options) {
        this.rpc = __bind(this.rpc, this);
        this.resolve_ref = __bind(this.resolve_ref, this);
        this.convert_to_ref = __bind(this.convert_to_ref, this);
        var attrs;
        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, options, _i, _len;
        if (!_.isArray(changes)) {
          changes = [changes];
        }
        options = {};
        changing = this._changing;
        this._changing = true;
        if (changes.length) {
          this._pending = true;
        }
        for (_i = 0, _len = changes.length; _i < _len; _i++) {
          change = changes[_i];
          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, toremove, val, _i, _len;
        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 (_i = 0, _len = toremove.length; _i < _len; _i++) {
            key = toremove[_i];
            delete attrs[key];
          }
        }
        if (!_.isEmpty(attrs)) {
          return HasProperties.__super__.set.call(this, attrs, options);
        }
      };

      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, prop_spec, _i, _len, _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 (_i = 0, _len = fields.length; _i < _len; _i++) {
          fld = fields[_i];
          _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,
          _this = this;
        if (_.isUndefined(use_cache)) {
          use_cache = true;
        }
        if (_.has(this.properties, prop_name)) {
          this.remove_property(prop_name);
        }
        changedep = function() {
          return _this.trigger('changedep:' + prop_name);
        };
        propchange = 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);
          }
        };
        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, obj, prop_spec, _i, _j, _len, _len1, _ref;
        prop_spec = this.properties[prop_name];
        dependencies = prop_spec.dependencies;
        for (_i = 0, _len = dependencies.length; _i < _len; _i++) {
          dep = dependencies[_i];
          obj = dep.obj;
          _ref = dep['fields'];
          for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
            fld = _ref[_j];
            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.prototype.resolve_ref = function(arg) {
        var x;
        if (_.isUndefined(arg)) {
          return arg;
        }
        if (_.isArray(arg)) {
          return (function() {
            var _i, _len, _results;
            _results = [];
            for (_i = 0, _len = arg.length; _i < _len; _i++) {
              x = arg[_i];
              _results.push(this.resolve_ref(x));
            }
            return _results;
          }).call(this);
        }
        if (_is_ref(arg)) {
          if (arg['type'] === this.type && arg['id'] === this.id) {
            return this;
          } else {
            return this.get_base().Collections(arg['type']).get(arg['id']);
          }
        }
        return arg;
      };

      HasProperties.prototype.get_base = function() {
        if (!this._base) {
          this._base = require('./base');
        }
        return this._base;
      };

      HasProperties.prototype.url = function() {
        var doc, url;
        doc = this.get('doc');
        if (doc == null) {
          logger.error("unset 'doc' in " + this);
        }
        url = this.get_base().Config.prefix + "bokeh/bb/" + doc + "/" + this.type + "/";
        if (this.isNew()) {
          return url;
        }
        return url + this.get('id') + "/";
      };

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

      HasProperties.prototype.defaults = function() {
        return {};
      };

      HasProperties.prototype.rpc = function(funcname, args, kwargs) {
        var data, doc, id, prefix, resp, type, url;
        prefix = this.get_base().Config.prefix;
        doc = this.get('doc');
        if (doc == null) {
          throw new Error("Unset 'doc' in " + this);
        }
        id = this.get('id');
        type = this.type;
        url = "" + prefix + "bokeh/bb/rpc/" + doc + "/" + type + "/" + id + "/" + funcname + "/";
        data = {
          args: args,
          kwargs: kwargs
        };
        resp = $.ajax({
          type: 'POST',
          url: url,
          data: JSON.stringify(data),
          contentType: 'application/json',
          xhrFields: {
            withCredentials: true
          }
        });
        return resp;
      };

      return HasProperties;

    })(Backbone.Model);
  });

}).call(this);

/*
//@ sourceMappingURL=has_properties.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('action/open_url',["underscore", "util/util", "common/collection", "common/has_properties"], function(_, Util, Collection, HasProperties) {
    var OpenURL, OpenURLs, _ref, _ref1;
    OpenURL = (function(_super) {
      __extends(OpenURL, _super);

      function OpenURL() {
        _ref = OpenURL.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      OpenURL.prototype.type = 'OpenURL';

      OpenURL.prototype.execute = function(data_source) {
        var i, indices, url, _i, _len, _results;
        indices = data_source.get("selected");
        _results = [];
        for (_i = 0, _len = indices.length; _i < _len; _i++) {
          i = indices[_i];
          url = Util.replace_placeholders(this.get("url"), data_source, i);
          _results.push(window.open(url));
        }
        return _results;
      };

      OpenURL.prototype.defaults = function() {
        return _.extend({}, OpenURL.__super__.defaults.call(this), {
          url: 'http://'
        });
      };

      return OpenURL;

    })(HasProperties);
    OpenURLs = (function(_super) {
      __extends(OpenURLs, _super);

      function OpenURLs() {
        _ref1 = OpenURLs.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      OpenURLs.prototype.model = OpenURL;

      return OpenURLs;

    })(Collection);
    return {
      Model: OpenURL,
      Collection: new OpenURLs()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=open_url.js.map
*/;
(function() {
  define('common/custom',["underscore"], function(_) {
    var monkey_patch;
    monkey_patch = function() {
      return _.uniqueId = function(prefix) {
        var hexDigits, i, s, uuid, _i;
        s = [];
        hexDigits = "0123456789ABCDEF";
        for (i = _i = 0; _i <= 31; i = ++_i) {
          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;
      }
    };
    return {
      "monkey_patch": monkey_patch
    };
  });

}).call(this);

/*
//@ sourceMappingURL=custom.js.map
*/;
(function(root) {
define("kiwi", [], function() {
  return (function() {
/*-----------------------------------------------------------------------------
| 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"/>
;
return root.kiwi = kiwi;
  }).apply(root, arguments);
});
}(this));

define('common/canvas_template',[],function(){
  var template = function(__obj) {
  var _safe = function(value) {
    if (typeof value === 'undefined' && value == null)
      value = '';
    var result = new String(value);
    result.ecoSafe = true;
    return result;
  };
  return (function() {
    var __out = [], __self = this, _print = function(value) {
      if (typeof value !== 'undefined' && value != null)
        __out.push(value.ecoSafe ? value : __self.escape(value));
    }, _capture = function(callback) {
      var out = __out, result;
      __out = [];
      callback.call(this);
      result = __out.join('');
      __out = out;
      return _safe(result);
    };
    (function() {
      if (this.map) {
        _print(_safe('\n<div class="bk-canvas-map"></div>\n'));
      }
    
      _print(_safe('\n<div class="bk-canvas-events" />\n<div class="bk-canvas-overlays" />\n<canvas class=\'bk-canvas\'></canvas>'));
    
    }).call(this);
    
    return __out.join('');
  }).call((function() {
    var obj = {
      escape: function(value) {
        return ('' + value)
          .replace(/&/g, '&amp;')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;')
          .replace(/"/g, '&quot;');
      },
      safe: _safe
    }, key;
    for (key in __obj) obj[key] = __obj[key];
    return obj;
  })());
};
  return template;
});

(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('common/continuum_view',["underscore", "backbone"], function(_, Backbone) {
    var ContinuumView, _ref;
    return ContinuumView = (function(_super) {
      __extends(ContinuumView, _super);

      function ContinuumView() {
        _ref = ContinuumView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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 target, val, _ref1;
        if (_.has(this, 'eventers')) {
          _ref1 = this.eventers;
          for (target in _ref1) {
            if (!__hasProp.call(_ref1, target)) continue;
            val = _ref1[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);
  });

}).call(this);

/*
//@ sourceMappingURL=continuum_view.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('range/range1d',["underscore", "common/collection", "common/has_properties"], function(_, Collection, HasProperties) {
    var Range1d, Range1ds, _ref, _ref1;
    Range1d = (function(_super) {
      __extends(Range1d, _super);

      function Range1d() {
        _ref = Range1d.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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);
    Range1ds = (function(_super) {
      __extends(Range1ds, _super);

      function Range1ds() {
        _ref1 = Range1ds.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Range1ds.prototype.model = Range1d;

      return Range1ds;

    })(Collection);
    return {
      "Model": Range1d,
      "Collection": new Range1ds()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=range1d.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('common/layout_box',["underscore", "./collection", "kiwi", "./has_properties", "range/range1d"], function(_, Collection, kiwi, HasProperties, Range1d) {
    var Constraint, EQ, Expr, GE, LE, LayoutBox, LayoutBoxs, Var, _ref, _ref1;
    Var = kiwi.Variable;
    Expr = kiwi.Expression;
    Constraint = kiwi.Constraint;
    EQ = kiwi.Operator.Eq;
    LE = kiwi.Operator.Le;
    GE = kiwi.Operator.Ge;
    LayoutBox = (function(_super) {
      __extends(LayoutBox, _super);

      function LayoutBox() {
        _ref = LayoutBox.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      LayoutBox.prototype.type = 'LayoutBox';

      LayoutBox.prototype.initialize = function(attrs, options) {
        var name, v, _i, _j, _len, _len1, _ref1, _ref2,
          _this = this;
        LayoutBox.__super__.initialize.call(this, attrs, options);
        this.solver = this.get('solver');
        this.var_constraints = {};
        _ref1 = ['top', 'left', 'width', 'height'];
        for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
          v = _ref1[_i];
          name = '_' + v;
          this[name] = new Var(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);
        }
        _ref2 = ['right', 'bottom'];
        for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) {
          v = _ref2[_j];
          name = '_' + v;
          this[name] = new Var(v);
          this.register_property(v, this._get_var, false);
        }
        this.solver.add_constraint(new Constraint(new Expr(this._top), GE));
        this.solver.add_constraint(new Constraint(new Expr(this._bottom), GE));
        this.solver.add_constraint(new Constraint(new Expr(this._left), GE));
        this.solver.add_constraint(new Constraint(new Expr(this._right), GE));
        this.solver.add_constraint(new Constraint(new Expr(this._width), GE));
        this.solver.add_constraint(new Constraint(new Expr(this._height), GE));
        this.solver.add_constraint(new Constraint(new Expr(this._left, this._width, [-1, this._right]), EQ));
        this.solver.add_constraint(new Constraint(new Expr(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._h_range.set('start', _this.get('left'));
          _this._h_range.set('end', _this.get('left') + _this.get('width'));
          return _this._h_range;
        }, 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._v_range.set('start', _this.get('bottom'));
          _this._v_range.set('end', _this.get('bottom') + _this.get('height'));
          return _this._v_range;
        }, false);
        this.add_dependencies('v_range', this, ['bottom', 'height']);
        this._aspect_constraint = null;
        this.register_property('aspect', function() {
          return _this.get('width') / _this.get('height');
        }, true);
        this.register_setter('aspect', this._set_aspect);
        return this.add_dependencies('aspect', this, ['width', 'height']);
      };

      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 (typeof value === 'number') {
          return this.solver.suggest_value(v, value);
        } else if (typeof value === 'string') {

        } else {
          c = new Constraint(new Expr(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 Expr([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);
    LayoutBoxs = (function(_super) {
      __extends(LayoutBoxs, _super);

      function LayoutBoxs() {
        _ref1 = LayoutBoxs.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      LayoutBoxs.prototype.model = LayoutBox;

      return LayoutBoxs;

    })(Collection);
    return {
      "Model": LayoutBox,
      "Collection": new LayoutBoxs()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=layout_box.js.map
*/;
(function() {
  define('common/solver',["backbone", "underscore", "kiwi"], function(Backbone, _, kiwi) {
    var Solver;
    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);
    return Solver;
  });

}).call(this);

/*
//@ sourceMappingURL=solver.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('common/canvas',["./collection", "kiwi", "./canvas_template", "./continuum_view", "./layout_box", "./logging", "./solver"], function(Collection, kiwi, canvas_template, ContinuumView, LayoutBox, Logging, Solver) {
    var Canvas, CanvasView, Canvases, Constraint, EQ, Expr, logger, _ref, _ref1, _ref2;
    Expr = kiwi.Expression;
    Constraint = kiwi.Constraint;
    EQ = kiwi.Operator.Eq;
    logger = Logging.logger;
    CanvasView = (function(_super) {
      __extends(CanvasView, _super);

      function CanvasView() {
        _ref = CanvasView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      CanvasView.prototype.className = "bk-canvas-wrapper";

      CanvasView.prototype.template = canvas_template;

      CanvasView.prototype.initialize = function(options) {
        var html, template_data, _ref1;
        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 = (_ref1 = this.$('div.bk-canvas-map')) != null ? _ref1 : 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;
        }
        this.ctx = this.canvas[0].getContext('2d');
        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 _ref1;
          return (_ref1 = ctx.imageSmoothingEnabled) != null ? _ref1 : 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(_super) {
      __extends(Canvas, _super);

      function Canvas() {
        _ref1 = Canvas.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      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 Expr(this._left), EQ));
        solver.add_constraint(new Constraint(new Expr(this._bottom), 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 idx, x, _i, _len;
        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, idx, y, _i, _len;
        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 idx, x, _i, _len;
        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, idx, y, _i, _len;
        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 Expr(this._width, -width), 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 Expr(this._height, -height), 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);
    Canvases = (function(_super) {
      __extends(Canvases, _super);

      function Canvases() {
        _ref2 = Canvases.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Canvases.prototype.model = Canvas;

      return Canvases;

    })(Collection);
    return {
      "Model": Canvas,
      "Collection": new Canvases()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=canvas.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('mapper/linear_mapper',["common/collection", "common/has_properties"], function(Collection, HasProperties) {
    var LinearMapper, LinearMappers, _ref, _ref1;
    LinearMapper = (function(_super) {
      __extends(LinearMapper, _super);

      function LinearMapper() {
        _ref = LinearMapper.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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, scale, _ref1;
        _ref1 = this.get('mapper_state'), scale = _ref1[0], offset = _ref1[1];
        return scale * x + offset;
      };

      LinearMapper.prototype.v_map_to_target = function(xs) {
        var idx, offset, result, scale, x, _i, _len, _ref1;
        _ref1 = this.get('mapper_state'), scale = _ref1[0], offset = _ref1[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, scale, _ref1;
        _ref1 = this.get('mapper_state'), scale = _ref1[0], offset = _ref1[1];
        return (xprime - offset) / scale;
      };

      LinearMapper.prototype.v_map_from_target = function(xprimes) {
        var idx, offset, result, scale, xprime, _i, _len, _ref1;
        _ref1 = this.get('mapper_state'), scale = _ref1[0], offset = _ref1[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);
    LinearMappers = (function(_super) {
      __extends(LinearMappers, _super);

      function LinearMappers() {
        _ref1 = LinearMappers.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      LinearMappers.prototype.model = LinearMapper;

      return LinearMappers;

    })(Collection);
    return {
      "Model": LinearMapper,
      "Collection": new LinearMappers()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=linear_mapper.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('mapper/log_mapper',["common/collection", "common/has_properties"], function(Collection, HasProperties) {
    var LogMapper, LogMappers, _ref, _ref1;
    LogMapper = (function(_super) {
      __extends(LogMapper, _super);

      function LogMapper() {
        _ref = LogMapper.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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 error, inter_offset, inter_scale, intermediate, offset, result, scale, _ref1;
        _ref1 = this.get('mapper_state'), scale = _ref1[0], offset = _ref1[1], inter_scale = _ref1[2], inter_offset = _ref1[3];
        intermediate = 0;
        result = 0;
        if (inter_scale === 0) {
          intermediate = 0;
        } else {
          try {
            intermediate = (Math.log(x) - inter_offset) / inter_scale;
            if (isNaN(intermediate)) {
              throw "NaN";
            }
            if (isFinite(intermediate) === false) {
              throw "Infinite";
            }
          } catch (_error) {
            error = _error;
            intermediate = 0;
          }
        }
        result = intermediate * scale + offset;
        return result;
      };

      LogMapper.prototype.v_map_to_target = function(xs) {
        var error, i, idx, inter_offset, inter_scale, intermediate, mask, mask1, mask2, offset, result, scale, x, _i, _j, _len, _len1, _ref1;
        _ref1 = this.get('mapper_state'), scale = _ref1[0], offset = _ref1[1], inter_scale = _ref1[2], inter_offset = _ref1[3];
        intermediate = new Float64Array(xs.length);
        result = new Float64Array(xs.length);
        if (inter_scale === 0) {
          intermediate = xs.map(function(i) {
            return i * 0;
          });
        } else {
          try {
            mask1 = xs.map(function(i) {
              return i <= 0;
            });
            mask2 = xs.map(function(i) {
              return isNaN(i);
            });
            mask = (function() {
              var _i, _ref2, _results;
              _results = [];
              for (i = _i = 0, _ref2 = xs.length; 0 <= _ref2 ? _i < _ref2 : _i > _ref2; i = 0 <= _ref2 ? ++_i : --_i) {
                _results.push(mask1[i] | mask2[i]);
              }
              return _results;
            })();
            mask = mask.reduce(function(x, y) {
              return x || y;
            });
            if (mask === 1) {
              xs[mask] = 1;
            }
            intermediate = xs.map(function(i) {
              return (Math.log(i) - inter_offset) / inter_scale;
            });
            for (idx = _i = 0, _len = intermediate.length; _i < _len; idx = ++_i) {
              x = intermediate[idx];
              if (isNaN(intermediate[idx])) {
                throw "NaN";
              }
              if (isFinite(intermediate[idx]) === false) {
                throw "Infinite";
              }
            }
          } catch (_error) {
            error = _error;
            intermediate = xs.map(function(i) {
              return i * 0;
            });
          }
        }
        for (idx = _j = 0, _len1 = xs.length; _j < _len1; idx = ++_j) {
          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, scale, _ref1;
        _ref1 = this.get('mapper_state'), scale = _ref1[0], offset = _ref1[1], inter_scale = _ref1[2], inter_offset = _ref1[3];
        intermediate = (xprime - offset) / scale;
        intermediate = Math.exp(inter_scale * intermediate + inter_offset);
        return intermediate;
      };

      LogMapper.prototype.v_map_from_target = function(xprimes) {
        var inter_offset, inter_scale, intermediate, offset, scale, _ref1;
        _ref1 = this.get('mapper_state'), scale = _ref1[0], offset = _ref1[1], inter_scale = _ref1[2], inter_offset = _ref1[3];
        intermediate = xprimes.map(function(i) {
          return (i - offset) / scale;
        });
        intermediate = intermediate.map(function(i) {
          return Math.exp(inter_scale * i + inter_offset);
        });
        return intermediate;
      };

      LogMapper.prototype._get_safe_scale = function(orig_start, orig_end) {
        var end, log_val, 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) {
            start = 1;
            end = 10;
          } 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, scale, screen_range, source_end, source_start, start, target_end, target_start, _ref1;
        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;
        _ref1 = this._get_safe_scale(source_start, source_end), start = _ref1[0], end = _ref1[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);
    LogMappers = (function(_super) {
      __extends(LogMappers, _super);

      function LogMappers() {
        _ref1 = LogMappers.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      LogMappers.prototype.model = LogMapper;

      return LogMappers;

    })(Collection);
    return {
      "Model": LogMapper,
      "Collection": new LogMappers()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=log_mapper.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('mapper/categorical_mapper',["common/collection", "./linear_mapper"], function(Collection, LinearMapper) {
    var CategoricalMapper, CategoricalMappers, _ref, _ref1;
    CategoricalMapper = (function(_super) {
      __extends(CategoricalMapper, _super);

      function CategoricalMapper() {
        _ref = CategoricalMapper.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      CategoricalMapper.prototype.map_to_target = function(x) {
        var factor, factors, percent, _ref1;
        if (typeof x === 'number') {
          return CategoricalMapper.__super__.map_to_target.call(this, x);
        }
        factors = this.get('source_range').get('factors');
        if (x.indexOf(':') >= 0) {
          _ref1 = x.split(':'), factor = _ref1[0], percent = _ref1[1];
          percent = parseFloat(percent);
          return CategoricalMapper.__super__.map_to_target.call(this, factors.indexOf(factor) + 0.5 + percent);
        }
        return CategoricalMapper.__super__.map_to_target.call(this, factors.indexOf(x) + 1);
      };

      CategoricalMapper.prototype.v_map_to_target = function(xs) {
        var factor, factors, i, percent, results, x, _i, _ref1, _ref2;
        if (typeof xs[0] === 'number') {
          return CategoricalMapper.__super__.v_map_to_target.call(this, xs);
        }
        factors = this.get('source_range').get('factors');
        results = Array(xs.length);
        for (i = _i = 0, _ref1 = xs.length; 0 <= _ref1 ? _i < _ref1 : _i > _ref1; i = 0 <= _ref1 ? ++_i : --_i) {
          x = xs[i];
          if (x.indexOf(':') >= 0) {
            _ref2 = x.split(':'), factor = _ref2[0], percent = _ref2[1];
            percent = parseFloat(percent);
            results[i] = factors.indexOf(factor) + 0.5 + percent;
          } else {
            results[i] = factors.indexOf(x) + 1;
          }
        }
        return CategoricalMapper.__super__.v_map_to_target.call(this, results);
      };

      CategoricalMapper.prototype.map_from_target = function(xprime, skip_cat) {
        var factors, start;
        if (skip_cat == null) {
          skip_cat = false;
        }
        xprime = CategoricalMapper.__super__.map_from_target.call(this, xprime) - 0.5;
        if (skip_cat) {
          return xprime;
        }
        factors = this.get('source_range').get('factors');
        start = this.get('source_range').get('start');
        return factors[Math.floor(xprime)];
      };

      CategoricalMapper.prototype.v_map_from_target = function(xprimes, skip_cat) {
        var factors, i, result, start, _i, _ref1;
        if (skip_cat == null) {
          skip_cat = false;
        }
        result = CategoricalMapper.__super__.v_map_from_target.call(this, xprimes);
        if (skip_cat) {
          return result;
        }
        factors = this.get('source_range').get('factors');
        start = this.get('source_range').get('start');
        for (i = _i = 0, _ref1 = result.length; 0 <= _ref1 ? _i < _ref1 : _i > _ref1; i = 0 <= _ref1 ? ++_i : --_i) {
          result[i] = factors[Math.floor(result[i] - 0.5)];
        }
        return result;
      };

      return CategoricalMapper;

    })(LinearMapper.Model);
    CategoricalMappers = (function(_super) {
      __extends(CategoricalMappers, _super);

      function CategoricalMappers() {
        _ref1 = CategoricalMappers.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      CategoricalMappers.prototype.model = CategoricalMapper;

      return CategoricalMappers;

    })(Collection);
    return {
      "Model": CategoricalMapper,
      "Collection": new CategoricalMappers()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=categorical_mapper.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('mapper/grid_mapper',["common/collection", "common/has_properties"], function(Collection, HasProperties) {
    var GridMapper, GridMappers, _ref, _ref1;
    GridMapper = (function(_super) {
      __extends(GridMapper, _super);

      function GridMapper() {
        _ref = GridMapper.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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);
    GridMappers = (function(_super) {
      __extends(GridMappers, _super);

      function GridMappers() {
        _ref1 = GridMappers.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      GridMappers.prototype.model = GridMapper;

      return GridMappers;

    })(Collection);
    return {
      "Model": GridMapper,
      "Collection": new GridMappers()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=grid_mapper.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('common/cartesian_frame',["underscore", "./collection", "./layout_box", "./logging", "mapper/linear_mapper", "mapper/log_mapper", "mapper/categorical_mapper", "mapper/grid_mapper"], function(_, Collection, LayoutBox, Logging, LinearMapper, LogMapper, CategoricalMapper, GridMapper) {
    var CartesianFrame, CartesianFrames, logger, _ref, _ref1;
    logger = Logging.logger;
    CartesianFrame = (function(_super) {
      __extends(CartesianFrame, _super);

      function CartesianFrame() {
        _ref = CartesianFrame.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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, x_units, y, y_units, canvas, x_name, y_name) {
        var hoff, i, sx, sy, voff, vx, vy, _i, _j, _ref1, _ref2;
        if (x_name == null) {
          x_name = 'default';
        }
        if (y_name == null) {
          y_name = 'default';
        }
        if (x_units === 'screen') {
          if (_.isArray(x)) {
            vx = x.slice(0);
          } else {
            vx = new Float64Array(x.length);
            vx.set(x);
          }
          hoff = this.get('h_range').get('start');
          for (i = _i = 0, _ref1 = vx.length; 0 <= _ref1 ? _i < _ref1 : _i > _ref1; i = 0 <= _ref1 ? ++_i : --_i) {
            vx[i] += hoff;
          }
        } else {
          vx = this.get('x_mappers')[x_name].v_map_to_target(x);
        }
        if (y_units === 'screen') {
          if (_.isArray(y)) {
            vy = y.slice(0);
          } else {
            vy = new Float64Array(y.length);
            vy.set(y);
          }
          voff = this.get('v_range').get('start');
          for (i = _j = 0, _ref2 = vy.length; 0 <= _ref2 ? _j < _ref2 : _j > _ref2; i = 0 <= _ref2 ? ++_j : --_j) {
            vy[i] += voff;
          }
        } else {
          vy = this.get('y_mappers')[y_name].v_map_to_target(y);
        }
        sx = canvas.v_vx_to_sx(vx);
        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, _ref1, _ref2, _results;
        _ref1 = this.get('x_mappers');
        for (name in _ref1) {
          mapper = _ref1[name];
          mapper.set('target_range', this.get('h_range'));
        }
        _ref2 = this.get('y_mappers');
        _results = [];
        for (name in _ref2) {
          mapper = _ref2[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);
    CartesianFrames = (function(_super) {
      __extends(CartesianFrames, _super);

      function CartesianFrames() {
        _ref1 = CartesianFrames.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      CartesianFrames.prototype.model = CartesianFrame;

      return CartesianFrames;

    })(Collection);
    return {
      "Model": CartesianFrame,
      "Collection": new CartesianFrames()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=cartesian_frame.js.map
*/;
(function() {
  define('common/build_views',["underscore"], function(_) {
    var build_views;
    return build_views = function(view_storage, view_models, options, view_types) {
      var created_views, i_model, key, model, newmodels, to_remove, view_specific_option, _i, _j, _len, _len1;
      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);
        }
        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;
    };
  });

}).call(this);

/*
//@ sourceMappingURL=build_views.js.map
*/;
/*! 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) {
  

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('hammer',[],function() {
        return Hammer;
    });
} else if (typeof module != 'undefined' && module.exports) {
    module.exports = Hammer;
} else {
    window[exportName] = Hammer;
}

})(window, document, 'Hammer');

/*! Copyright (c) 2013 Brandon Aaron (http://brandon.aaron.sh)
 * Licensed under the MIT License (LICENSE.txt).
 *
 * Version: 3.1.12
 *
 * Requires: jQuery 1.2.2+
 */

(function (factory) {
    if ( typeof define === 'function' && define.amd ) {
        // AMD. Register as an anonymous module.
        define('jquery_mousewheel',['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;
    }

}));

(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('common/ui_events',["backbone", "hammer", "jquery_mousewheel", "common/logging"], function(Backbone, Hammer, mousewheel, Logging) {
    var UIEvents, logger, _ref;
    logger = Logging.logger;
    return UIEvents = (function(_super) {
      __extends(UIEvents, _super);

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

      UIEvents.prototype.initialize = function(attrs, options) {
        var hit_area,
          _this = this;
        UIEvents.__super__.initialize.call(this, attrs, options);
        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(e) {
          return _this._doubletap(e);
        });
        this.hammer.on('tap', function(e) {
          return _this._tap(e);
        });
        this.hammer.on('press', function(e) {
          return _this._press(e);
        });
        this.hammer.get('pan').set({
          direction: Hammer.DIRECTION_ALL
        });
        this.hammer.on('panstart', function(e) {
          return _this._pan_start(e);
        });
        this.hammer.on('pan', function(e) {
          return _this._pan(e);
        });
        this.hammer.on('panend', function(e) {
          return _this._pan_end(e);
        });
        this.hammer.get('pinch').set({
          enable: true
        });
        this.hammer.on('pinchstart', function(e) {
          return _this._pinch_start(e);
        });
        this.hammer.on('pinch', function(e) {
          return _this._pinch(e);
        });
        this.hammer.on('pinchend', function(e) {
          return _this._pinch_end(e);
        });
        this.hammer.get('rotate').set({
          enable: true
        });
        this.hammer.on('rotatestart', function(e) {
          return _this._rotate_start(e);
        });
        this.hammer.on('rotate', function(e) {
          return _this._rotate(e);
        });
        this.hammer.on('rotateend', function(e) {
          return _this._rotate_end(e);
        });
        hit_area.mousemove(function(e) {
          return _this._mouse_move(e);
        });
        hit_area.mouseenter(function(e) {
          return _this._mouse_enter(e);
        });
        hit_area.mouseleave(function(e) {
          return _this._mouse_exit(e);
        });
        hit_area.mousewheel(function(e, delta) {
          return _this._mouse_wheel(e, delta);
        });
        $(document).keydown(function(e) {
          return _this._key_down(e);
        });
        return $(document).keyup(function(e) {
          return _this._key_up(e);
        });
      };

      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, base_event_type, gestures, tm;
        tm = this.get('tool_manager');
        base_event_type = event_type.split(":")[0];
        gestures = tm.get('gestures');
        active = gestures[base_event_type].active;
        if (active != null) {
          return this.trigger("" + event_type + ":" + active.id, e);
        }
      };

      UIEvents.prototype._bokify_hammer = function(e) {
        var left, offset, top, _ref1, _ref2;
        if (e.pointerType === "mouse") {
          offset = $(e.target).offset();
          left = (_ref1 = offset.left) != null ? _ref1 : 0;
          top = (_ref2 = offset.top) != null ? _ref2 : 0;
          return e.bokeh = {
            sx: e.srcEvent.pageX - left,
            sy: e.srcEvent.pageY - top
          };
        } else {
          return e.bokeh = {
            sx: e.center.x,
            sy: e.center.y
          };
        }
      };

      UIEvents.prototype._bokify_jq = function(e) {
        var left, offset, top, _ref1, _ref2;
        offset = $(e.currentTarget).offset();
        left = (_ref1 = offset.left) != null ? _ref1 : 0;
        top = (_ref2 = offset.top) != null ? _ref2 : 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;
        this._trigger('scroll', e);
        e.preventDefault();
        return e.stopPropagation();
      };

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

}).call(this);

/*
//@ sourceMappingURL=ui_events.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('common/has_parent',["underscore", "./has_properties"], function(_, HasProperties) {
    var HasParent, _ref;
    HasParent = (function(_super) {
      __extends(HasParent, _super);

      function HasParent() {
        _ref = HasParent.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      HasParent.prototype.initialize = function(attrs, options) {
        HasParent.__super__.initialize.call(this, attrs, options);
        return this._parent = HasProperties.prototype.get.apply(this, ['parent']);
      };

      HasParent.prototype.get = function(attr) {
        var val;
        if (!this._display_defaults) {
          this._display_defaults = this.display_defaults();
        }
        if (attr === 'parent') {
          return this._parent;
        }
        val = HasParent.__super__.get.call(this, attr);
        if (!_.isUndefined(val)) {
          return val;
        }
        if (this._parent && _.indexOf(this._parent.parent_properties, attr) >= 0) {
          val = this._parent.get(attr);
          if (!_.isUndefined(val)) {
            return val;
          }
        }
        return this._display_defaults[attr];
      };

      HasParent.prototype.display_defaults = function() {
        return {};
      };

      return HasParent;

    })(HasProperties);
    return HasParent;
  });

}).call(this);

/*
//@ sourceMappingURL=has_parent.js.map
*/;
(function() {
  define('common/plot_utils',[], function() {
    var LEVELS, delay_animation, throttle_animation, _delay_animation;
    LEVELS = ['image', 'underlay', 'glyph', 'overlay', 'annotation', 'tool'];
    _delay_animation = function(f) {
      return f();
    };
    delay_animation = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || _delay_animation;
    throttle_animation = function(func, wait) {
      var args, context, later, pending, previous, result, timeout, _ref;
      _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;
      };
    };
    return {
      "LEVELS": LEVELS,
      "throttle_animation": throttle_animation
    };
  });

}).call(this);

/*
//@ sourceMappingURL=plot_utils.js.map
*/;
define('bootstrap/dropdown',["jquery"], function(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)
 * ======================================================================== */


+function ($) {
  

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

});

define('common/toolbar_template',[],function(){
  var template = function(__obj) {
  var _safe = function(value) {
    if (typeof value === 'undefined' && value == null)
      value = '';
    var result = new String(value);
    result.ecoSafe = true;
    return result;
  };
  return (function() {
    var __out = [], __self = this, _print = function(value) {
      if (typeof value !== 'undefined' && value != null)
        __out.push(value.ecoSafe ? value : __self.escape(value));
    }, _capture = function(callback) {
      var out = __out, result;
      __out = [];
      callback.call(this);
      result = __out.join('');
      __out = out;
      return _safe(result);
    };
    (function() {
      if ((this.logo != null) && this.logo === "grey") {
        _print(_safe('\n  <a href=\'http://bokeh.pydata.org/\' target=\'_blank\' class=\'bk-logo bk-logo-small grey\'></a>\n'));
      } else if (this.logo != null) {
        _print(_safe('\n<a href=\'http://bokeh.pydata.org/\' target=\'_blank\' class=\'bk-logo bk-logo-small\'></a>\n'));
      }
    
      _print(_safe('\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    <li>\n  \t  <button class="bk-toolbar-button help" title="Help">\n      <a href="http://bokeh.pydata.org/en/latest/docs/user_guide/objects.html#tools" target="_blank">\n        <img class="bk-btn-icon" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA2hpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYxIDY0LjE0MDk0OSwgMjAxMC8xMi8wNy0xMDo1NzowMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDo3NzIwRUFGMDYyMjE2ODExOTdBNUNBNjVEQTY5OTRDRSIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDozMjFERDhDRjIwQjIxMUU0ODREQUYzNzM5QTM2MjBCRSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDozMjFERDhDRTIwQjIxMUU0ODREQUYzNzM5QTM2MjBCRSIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ1M1LjEgTWFjaW50b3NoIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6OTdFQUZCRjQ4NjIxNjgxMTk3QTVDQTY1REE2OTk0Q0UiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6NzcyMEVBRjA2MjIxNjgxMTk3QTVDQTY1REE2OTk0Q0UiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz6QBYrgAAABb0lEQVR42ozTwUeEQRjH8W3bKEs6JkpESqfVpS4RHaJL2b2sLepUh3To0KFVIjp0iegQUdG21WmVvUWsKBGRlIiU7Q+IVaT0ffi9eY33peFj7cw8zzvzzEzV7v5hxGltGEUvutR3hwvs4ck/OeoET6KACrJolaz6Cprz12L6rcEOajGEFyfxtRxhDX0Yx5e3ggV8IqlgW/4J3vCKddRrLKm5894KOjGCHiVrwDZ+sKKvpRQ0pzkzuETeEqSxpT1aa8ezCmbyuEW3b0sVxaQtQT+mfINXGPT9T+n3xqnLKTYsQQseI8FtWnstYdEZs9o0eqdQZxUNSWD9YwHj36i2UyijOWQFVvmPkOR2P8qW4AwDIQma0BEyZjGlqCo9gXjA1+0ePAQExxWTtwT3KOqG/bfZ3GOL9W7ikrIe6FSsvQdswcZymrvsf0xWpIzqYauZRcIXmFBfUUea8Qobc5a2qQtiz3nVec7nGHaf868AAwDKW1RIPmvhEQAAAABJRU5ErkJggg==">\n      </a>\n      <span class="tip">\n        Click the question mark to learn more about Bokeh plot tools.\n\t    </span>\n\t  </button>\n    </li>\n  </ul>\n</div>\n'));
    
    }).call(this);
    
    return __out.join('');
  }).call((function() {
    var obj = {
      escape: function(value) {
        return ('' + value)
          .replace(/&/g, '&amp;')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;')
          .replace(/"/g, '&quot;');
      },
      safe: _safe
    }, key;
    for (key in __obj) obj[key] = __obj[key];
    return obj;
  })());
};
  return template;
});

(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('common/plot_widget',["./continuum_view"], function(ContinuumView) {
    var PlotWidget, _ref;
    return PlotWidget = (function(_super) {
      __extends(PlotWidget, _super);

      function PlotWidget() {
        _ref = PlotWidget.__super__.constructor.apply(this, arguments);
        return _ref;
      }

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

      return PlotWidget;

    })(ContinuumView);
  });

}).call(this);

/*
//@ sourceMappingURL=plot_widget.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('tool/tool',["common/plot_widget", "common/has_properties", "common/logging"], function(PlotWidget, HasProperties, Logging) {
    var Tool, ToolView, logger, _ref, _ref1;
    logger = Logging.logger;
    ToolView = (function(_super) {
      __extends(ToolView, _super);

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

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

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

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

      return ToolView;

    })(PlotWidget);
    Tool = (function(_super) {
      __extends(Tool, _super);

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

      Tool.prototype._check_dims = function(dims, tool_name) {
        var hdim, wdim, _ref2;
        _ref2 = [false, false], wdim = _ref2[0], hdim = _ref2[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);
    return {
      "Model": Tool,
      "View": ToolView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=tool.js.map
*/;
define('tool/button_tool_template',[],function(){
  var template = function(__obj) {
  var _safe = function(value) {
    if (typeof value === 'undefined' && value == null)
      value = '';
    var result = new String(value);
    result.ecoSafe = true;
    return result;
  };
  return (function() {
    var __out = [], __self = this, _print = function(value) {
      if (typeof value !== 'undefined' && value != null)
        __out.push(value.ecoSafe ? value : __self.escape(value));
    }, _capture = function(callback) {
      var out = __out, result;
      __out = [];
      callback.call(this);
      result = __out.join('');
      __out = out;
      return _safe(result);
    };
    (function() {
      _print(_safe('<button type="button" class="bk-toolbar-button hover">\n  <img class=\'bk-btn-icon\' src='));
    
      _print(this.icon);
    
      _print(_safe(' />\n  <span class=\'tip\'>'));
    
      _print(this.tooltip);
    
      _print(_safe('</span>\n</button>\n'));
    
    }).call(this);
    
    return __out.join('');
  }).call((function() {
    var obj = {
      escape: function(value) {
        return ('' + value)
          .replace(/&/g, '&amp;')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;')
          .replace(/"/g, '&quot;');
      },
      safe: _safe
    }, key;
    for (key in __obj) obj[key] = __obj[key];
    return obj;
  })());
};
  return template;
});

(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('tool/button_tool',["backbone", "./tool", "./button_tool_template"], function(Backbone, Tool, button_tool_template) {
    var ButtonTool, ButtonToolButtonView, ButtonToolView, _ref, _ref1, _ref2;
    ButtonToolButtonView = (function(_super) {
      __extends(ButtonToolButtonView, _super);

      function ButtonToolButtonView() {
        _ref = ButtonToolButtonView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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(_super) {
      __extends(ButtonToolView, _super);

      function ButtonToolView() {
        _ref1 = ButtonToolView.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      return ButtonToolView;

    })(Tool.View);
    ButtonTool = (function(_super) {
      __extends(ButtonTool, _super);

      function ButtonTool() {
        _ref2 = ButtonTool.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      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.defaults = function() {
        return _.extend({}, ButtonTool.__super__.defaults.call(this), {
          active: false,
          tool_name: this.tool_name,
          icon: this.icon
        });
      };

      return ButtonTool;

    })(Tool.Model);
    return {
      "Model": ButtonTool,
      "View": ButtonToolView,
      "ButtonView": ButtonToolButtonView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=button_tool.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('tool/actions/action_tool',["backbone", "tool/button_tool"], function(Backbone, ButtonTool) {
    var ActionTool, ActionToolButtonView, ActionToolView, _ref, _ref1, _ref2;
    ActionToolButtonView = (function(_super) {
      __extends(ActionToolButtonView, _super);

      function ActionToolButtonView() {
        _ref = ActionToolButtonView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      ActionToolButtonView.prototype._clicked = function() {
        return this.model.trigger('do');
      };

      return ActionToolButtonView;

    })(ButtonTool.ButtonView);
    ActionToolView = (function(_super) {
      __extends(ActionToolView, _super);

      function ActionToolView() {
        _ref1 = ActionToolView.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      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(_super) {
      __extends(ActionTool, _super);

      function ActionTool() {
        _ref2 = ActionTool.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      return ActionTool;

    })(ButtonTool.Model);
    return {
      "Model": ActionTool,
      "View": ActionToolView,
      "ButtonView": ActionToolButtonView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=action_tool.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('tool/gestures/gesture_tool',["backbone", "tool/button_tool"], function(Backbone, ButtonTool) {
    var GestureTool, GestureToolButtonView, GestureToolView, _ref, _ref1, _ref2;
    GestureToolButtonView = (function(_super) {
      __extends(GestureToolButtonView, _super);

      function GestureToolButtonView() {
        _ref = GestureToolButtonView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      GestureToolButtonView.prototype._clicked = function() {
        return this.model.set('active', true);
      };

      return GestureToolButtonView;

    })(ButtonTool.ButtonView);
    GestureToolView = (function(_super) {
      __extends(GestureToolView, _super);

      function GestureToolView() {
        _ref1 = GestureToolView.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      return GestureToolView;

    })(ButtonTool.View);
    GestureTool = (function(_super) {
      __extends(GestureTool, _super);

      function GestureTool() {
        _ref2 = GestureTool.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      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);
    return {
      "Model": GestureTool,
      "View": GestureToolView,
      "ButtonView": GestureToolButtonView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=gesture_tool.js.map
*/;
define('tool/inspectors/inspect_tool_list_item_template',[],function(){
  var template = function(__obj) {
  var _safe = function(value) {
    if (typeof value === 'undefined' && value == null)
      value = '';
    var result = new String(value);
    result.ecoSafe = true;
    return result;
  };
  return (function() {
    var __out = [], __self = this, _print = function(value) {
      if (typeof value !== 'undefined' && value != null)
        __out.push(value.ecoSafe ? value : __self.escape(value));
    }, _capture = function(callback) {
      var out = __out, result;
      __out = [];
      callback.call(this);
      result = __out.join('');
      __out = out;
      return _safe(result);
    };
    (function() {
      _print(_safe('<input type="checkbox" '));
    
      _print(this.active ? _print(_safe('checked')) : void 0);
    
      _print(_safe('>'));
    
      _print(this.tool_name);
    
      _print(_safe('</input>\n'));
    
    }).call(this);
    
    return __out.join('');
  }).call((function() {
    var obj = {
      escape: function(value) {
        return ('' + value)
          .replace(/&/g, '&amp;')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;')
          .replace(/"/g, '&quot;');
      },
      safe: _safe
    }, key;
    for (key in __obj) obj[key] = __obj[key];
    return obj;
  })());
};
  return template;
});

(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('tool/inspectors/inspect_tool',["backbone", "common/logging", "tool/tool", "./inspect_tool_list_item_template"], function(Backbone, Logging, Tool, inspect_tool_list_item_template) {
    var InspectTool, InspectToolListItemView, InspectToolView, logger, _ref, _ref1, _ref2;
    logger = Logging.logger;
    InspectToolListItemView = (function(_super) {
      __extends(InspectToolListItemView, _super);

      function InspectToolListItemView() {
        _ref = InspectToolListItemView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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(_super) {
      __extends(InspectToolView, _super);

      function InspectToolView() {
        _ref1 = InspectToolView.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      return InspectToolView;

    })(Tool.View);
    InspectTool = (function(_super) {
      __extends(InspectTool, _super);

      function InspectTool() {
        _ref2 = InspectTool.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      InspectTool.prototype.event_type = "move";

      InspectTool.prototype.bind_bokeh_events = function() {
        InspectTool.__super__.bind_bokeh_events.call(this);
        return this.listenTo(events, 'move', this._inspect);
      };

      InspectTool.prototype.initialize = function(attrs, options) {
        var all_renderers, names, r, renderers, _i, _len, _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._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);
    return {
      "Model": InspectTool,
      "View": InspectToolView,
      "ListItemView": InspectToolListItemView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=inspect_tool.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, 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(fn, me){ return function(){ return fn.apply(me, arguments); }; };

  define('common/tool_manager',["underscore", "jquery", "bootstrap/dropdown", "backbone", "./logging", "./toolbar_template", "common/has_properties", "tool/actions/action_tool", "tool/gestures/gesture_tool", "tool/inspectors/inspect_tool"], function(_, $, $$1, Backbone, Logging, toolbar_template, HasProperties, ActionTool, GestureTool, InspectTool) {
    var ToolManager, ToolManagerView, logger, _ref, _ref1;
    logger = Logging.logger;
    ToolManagerView = (function(_super) {
      __extends(ToolManagerView, _super);

      function ToolManagerView() {
        _ref = ToolManagerView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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 = this;
        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='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(_super) {
      __extends(ToolManager, _super);

      function ToolManager() {
        this._active_change = __bind(this._active_change, this);
        _ref1 = ToolManager.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

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

      ToolManager.prototype._init_tools = function() {
        var actions, et, gestures, inspectors, tool, tools, _i, _len, _ref2, _results;
        gestures = this.get('gestures');
        _ref2 = this.get('tools');
        for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
          tool = _ref2[_i];
          if (tool instanceof InspectTool.Model) {
            inspectors = this.get('inspectors');
            inspectors.push(tool);
            this.set('inspectors', inspectors);
          } 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');
          });
          _results.push(gestures[et].tools[0].set('active', true));
        }
        return _results;
      };

      ToolManager.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("ToolManager: deactivating tool: " + prev.type + " (" + prev.id + ") for event type '" + et + "'");
          prev.set('active', false);
        }
        gestures[et].active = tool;
        this.set('gestures', gestures);
        logger.debug("ToolManager: activating tool: " + tool.type + " (" + tool.id + ") for event type '" + et + "'");
        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: []
        };
      };

      return ToolManager;

    })(HasProperties);
    return {
      "Model": ToolManager,
      "View": ToolManagerView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=tool_manager.js.map
*/;
define('common/plot_template',[],function(){
  var template = function(__obj) {
  var _safe = function(value) {
    if (typeof value === 'undefined' && value == null)
      value = '';
    var result = new String(value);
    result.ecoSafe = true;
    return result;
  };
  return (function() {
    var __out = [], __self = this, _print = function(value) {
      if (typeof value !== 'undefined' && value != null)
        __out.push(value.ecoSafe ? value : __self.escape(value));
    }, _capture = function(callback) {
      var out = __out, result;
      __out = [];
      callback.call(this);
      result = __out.join('');
      __out = out;
      return _safe(result);
    };
    (function() {
      _print(_safe('<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);
    
    return __out.join('');
  }).call((function() {
    var obj = {
      escape: function(value) {
        return ('' + value)
          .replace(/&/g, '&amp;')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;')
          .replace(/"/g, '&quot;');
      },
      safe: _safe
    }, key;
    for (key in __obj) obj[key] = __obj[key];
    return obj;
  })());
};
  return template;
});

(function() {
  define('common/svg_colors',[], function() {
    var svg_colors;
    return svg_colors = {
      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",
      lightsalmon: "#FFA07A",
      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",
      mediumslateblue: "#7B68EE",
      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"
    };
  });

}).call(this);

/*
//@ sourceMappingURL=svg_colors.js.map
*/;
(function() {
  var __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; },
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/properties',["underscore", "common/logging", "common/svg_colors"], function(_, Logging, svg_colors) {
    var FillProperties, GlyphProperties, LineProperties, Properties, TextProperties, logger;
    logger = Logging.logger;
    Properties = (function() {
      function Properties() {}

      Properties.prototype.source_v_select = function(attrname, datasource) {
        var i, length, obj, value;
        obj = this[attrname];
        if (obj == null) {
          throw new Error("requested vector selection of unknown property '" + attrname + "'");
        } else if ((obj.field != null) && (obj.field in datasource.get('data'))) {
          return datasource.get_column(obj.field);
        } else if (_.isObject(obj)) {
          length = datasource.get_length();
          if (length == null) {
            length = 1;
          }
          value = obj.value != null ? obj.value : NaN;
          return (function() {
            var _i, _results;
            _results = [];
            for (i = _i = 0; 0 <= length ? _i < length : _i > length; i = 0 <= length ? ++_i : --_i) {
              _results.push(value);
            }
            return _results;
          })();
        } else {
          throw new Error("requested vector selection of '" + attrname + "' failed for " + obj);
        }
      };

      Properties.prototype._fix_singleton_array_value = function(obj) {
        var value;
        if (obj.value != null) {
          value = obj.value;
          if (_.isArray(value)) {
            if (value.length === 1) {
              return _.extend({}, obj, {
                value: value[0]
              });
            } else {
              throw new Error("expected an array of length 1, got " + value);
            }
          }
        }
        return obj;
      };

      Properties.prototype.string = function(styleprovider, attrname) {
        var value;
        this[attrname] = {};
        value = styleprovider.mget(attrname);
        if (value == null) {
          return this[attrname].value = null;
        } else if (_.isString(value)) {
          return this[attrname].value = value;
        } else if (_.isObject(value)) {
          value = this._fix_singleton_array_value(value);
          return this[attrname] = _.extend(this[attrname], value);
        } else {
          return logger.warn("string property '" + attrname + "' given invalid value: " + value);
        }
      };

      Properties.prototype.boolean = function(styleprovider, attrname) {
        var value;
        this[attrname] = {};
        value = styleprovider.mget(attrname);
        if (value == null) {
          return this[attrname].value = null;
        } else if (_.isBoolean(value)) {
          return this[attrname].value = value;
        } else if (_.isString(value)) {
          return this[attrname].field = value;
        } else if (_.isObject(value)) {
          value = this._fix_singleton_array_value(value);
          return this[attrname] = _.extend(this[attrname], value);
        } else {
          return logger.warn("boolean property '" + attrname + "' given invalid value: " + value);
        }
      };

      Properties.prototype.number = function(styleprovider, attrname) {
        var units_value, value, _ref;
        this[attrname] = {};
        units_value = (_ref = styleprovider.mget(attrname + '_units')) != null ? _ref : 'data';
        this[attrname].units = units_value;
        value = styleprovider.mget(attrname);
        if (value == null) {
          return this[attrname].value = null;
        } else if (_.isNumber(value)) {
          return this[attrname].value = value;
        } else if (_.isString(value)) {
          return this[attrname].field = value;
        } else if (_.isObject(value)) {
          value = this._fix_singleton_array_value(value);
          return this[attrname] = _.extend(this[attrname], value);
        } else {
          return logger.warn("number property '" + attrname + "' given invalid value: " + value);
        }
      };

      Properties.prototype.color = function(styleprovider, attrname) {
        var value;
        this[attrname] = {};
        value = styleprovider.mget(attrname);
        if (value == null) {
          return this[attrname].value = null;
        } else if (_.isString(value)) {
          if ((svg_colors[value] != null) || value.substring(0, 1) === "#") {
            return this[attrname].value = value;
          } else {
            return this[attrname].field = value;
          }
        } else if (_.isObject(value)) {
          value = this._fix_singleton_array_value(value);
          return this[attrname] = _.extend(this[attrname], value);
        } else {
          return logger.warn("color property '" + attrname + "' given invalid value: " + value);
        }
      };

      Properties.prototype.array = function(styleprovider, attrname) {
        var units_value, value, _ref;
        this[attrname] = {};
        units_value = (_ref = styleprovider.mget(attrname + "_units")) != null ? _ref : 'data';
        this[attrname].units = units_value;
        value = styleprovider.mget(attrname);
        if (value == null) {
          return this[attrname].value = null;
        } else if (_.isString(value)) {
          return this[attrname].field = value;
        } else if (_.isArray(value)) {
          return this[attrname].value = value;
        } else if (_.isObject(value)) {
          return this[attrname] = _.extend(this[attrname], value);
        } else {
          return logger.warn("array property '" + attrname + "' given invalid value: " + value);
        }
      };

      Properties.prototype["enum"] = function(styleprovider, attrname, vals) {
        var levels, value;
        this[attrname] = {};
        levels = vals.split(" ");
        value = styleprovider.mget(attrname);
        if (value == null) {
          return this[attrname].value = null;
        } else if (_.isString(value)) {
          if (__indexOf.call(levels, value) >= 0) {
            return this[attrname].value = value;
          } else {
            return this[attrname].field = value;
          }
        } else if (_.isObject(value)) {
          value = this._fix_singleton_array_value(value);
          return this[attrname] = _.extend(this[attrname], value);
        } else {
          logger.warn("enum property '" + attrname + "' given invalid value: " + value);
          return logger.warn(" - acceptable values:" + levels);
        }
      };

      Properties.prototype.setattr = function(styleprovider, attrname, attrtype) {
        var values, _ref;
        values = null;
        if (attrtype.indexOf(":") > -1) {
          _ref = attrtype.split(":"), attrtype = _ref[0], values = _ref[1];
        }
        if (attrtype === "string") {
          return this.string(styleprovider, attrname);
        } else if (attrtype === "boolean") {
          return this.boolean(styleprovider, attrname);
        } else if (attrtype === "number") {
          return this.number(styleprovider, attrname);
        } else if (attrtype === "color") {
          return this.color(styleprovider, attrname);
        } else if (attrtype === "array") {
          return this.array(styleprovider, attrname);
        } else if (attrtype === "enum" && values) {
          return this["enum"](styleprovider, attrname, values);
        } else {
          return logger.warn("Unknown type '" + attrtype + "' for glyph property: " + attrname);
        }
      };

      Properties.prototype.select = function(attrname, obj) {
        if (!(attrname in this)) {
          logger.warn("requested selection of unknown property '" + attrname + "' on object: " + obj);
          return;
        }
        if ((this[attrname].field != null) && (this[attrname].field in obj)) {
          return obj[this[attrname].field];
        }
        if (this[attrname].value != null) {
          return this[attrname].value;
        }
        if (obj.get && obj.get(attrname)) {
          return obj.get(attrname);
        }
        if (obj.mget && obj.mget(attrname)) {
          return obj.mget(attrname);
        }
        if (obj[attrname] != null) {
          return obj[attrname];
        }
        return logger.warn("selection for attribute '" + attrname + "' failed on object: " + obj);
      };

      return Properties;

    })();
    LineProperties = (function(_super) {
      __extends(LineProperties, _super);

      function LineProperties(styleprovider, prefix) {
        if (prefix == null) {
          prefix = "";
        }
        this.line_color_name = "" + prefix + "line_color";
        this.line_width_name = "" + prefix + "line_width";
        this.line_alpha_name = "" + prefix + "line_alpha";
        this.line_join_name = "" + prefix + "line_join";
        this.line_cap_name = "" + prefix + "line_cap";
        this.line_dash_name = "" + prefix + "line_dash";
        this.line_dash_offset_name = "" + prefix + "line_dash_offset";
        this.color(styleprovider, this.line_color_name);
        this.number(styleprovider, this.line_width_name);
        this.number(styleprovider, this.line_alpha_name);
        this["enum"](styleprovider, this.line_join_name, "miter round bevel");
        this["enum"](styleprovider, this.line_cap_name, "butt round square");
        this.array(styleprovider, this.line_dash_name);
        this.number(styleprovider, this.line_dash_offset_name);
        this.do_stroke = true;
        if (!_.isUndefined(this[this.line_color_name].value)) {
          if (_.isNull(this[this.line_color_name].value)) {
            this.do_stroke = false;
          }
        }
      }

      LineProperties.prototype.set = function(ctx, obj) {
        ctx.strokeStyle = this.select(this.line_color_name, obj);
        ctx.globalAlpha = this.select(this.line_alpha_name, obj);
        ctx.lineWidth = this.select(this.line_width_name, obj);
        ctx.lineJoin = this.select(this.line_join_name, obj);
        ctx.lineCap = this.select(this.line_cap_name, obj);
        ctx.setLineDash(this.select(this.line_dash_name, obj));
        return ctx.setLineDashOffset(this.select(this.line_dash_offset_name, obj));
      };

      LineProperties.prototype.set_prop_cache = function(datasource) {
        this.cache = {};
        this.cache.strokeStyle = this.source_v_select(this.line_color_name, datasource);
        this.cache.globalAlpha = this.source_v_select(this.line_alpha_name, datasource);
        this.cache.lineWidth = this.source_v_select(this.line_width_name, datasource);
        this.cache.lineJoin = this.source_v_select(this.line_join_name, datasource);
        this.cache.lineCap = this.source_v_select(this.line_cap_name, datasource);
        this.cache.setLineDash = this.source_v_select(this.line_dash_name, datasource);
        return this.cache.setLineDashOffset = this.source_v_select(this.line_dash_offset_name, datasource);
      };

      LineProperties.prototype.clear_prop_cache = function() {
        return this.cache = {};
      };

      LineProperties.prototype.set_vectorize = function(ctx, i) {
        var did_change;
        did_change = false;
        if ((this.cache.strokeStyle[i] != null) && ctx.strokeStyle !== this.cache.strokeStyle[i]) {
          ctx.strokeStyle = this.cache.strokeStyle[i];
          did_change = true;
        }
        if ((this.cache.globalAlpha[i] != null) && ctx.globalAlpha !== this.cache.globalAlpha[i]) {
          ctx.globalAlpha = this.cache.globalAlpha[i];
          did_change = true;
        }
        if ((this.cache.lineWidth[i] != null) && ctx.lineWidth !== this.cache.lineWidth[i]) {
          ctx.lineWidth = this.cache.lineWidth[i];
          did_change = true;
        }
        if ((this.cache.lineJoin[i] != null) && ctx.lineJoin !== this.cache.lineJoin[i]) {
          ctx.lineJoin = this.cache.lineJoin[i];
          did_change = true;
        }
        if ((this.cache.lineCap[i] != null) && ctx.lineCap !== this.cache.lineCap[i]) {
          ctx.lineCap = this.cache.lineCap[i];
          did_change = true;
        }
        if ((this.cache.setLineDash[i] != null) && ctx.getLineDash() !== this.cache.setLineDash[i]) {
          ctx.setLineDash(this.cache.setLineDash[i]);
          did_change = true;
        }
        if ((this.cache.setLineDashOffset[i] != null) && ctx.getLineDashOffset() !== this.cache.setLineDashOffset[i]) {
          ctx.setLineDashOffset(this.cache.setLineDashOffset[i]);
          did_change = true;
        }
        return did_change;
      };

      return LineProperties;

    })(Properties);
    FillProperties = (function(_super) {
      __extends(FillProperties, _super);

      function FillProperties(styleprovider, prefix) {
        if (prefix == null) {
          prefix = "";
        }
        this.fill_color_name = "" + prefix + "fill_color";
        this.fill_alpha_name = "" + prefix + "fill_alpha";
        this.color(styleprovider, this.fill_color_name);
        this.number(styleprovider, this.fill_alpha_name);
        this.do_fill = true;
        if (!_.isUndefined(this[this.fill_color_name].value)) {
          if (_.isNull(this[this.fill_color_name].value)) {
            this.do_fill = false;
          }
        }
      }

      FillProperties.prototype.set = function(ctx, obj) {
        ctx.fillStyle = this.select(this.fill_color_name, obj);
        return ctx.globalAlpha = this.select(this.fill_alpha_name, obj);
      };

      FillProperties.prototype.set_prop_cache = function(datasource) {
        this.cache = {};
        this.cache.fillStyle = this.source_v_select(this.fill_color_name, datasource);
        return this.cache.globalAlpha = this.source_v_select(this.fill_alpha_name, datasource);
      };

      FillProperties.prototype.set_vectorize = function(ctx, i) {
        var did_change;
        did_change = false;
        if (ctx.fillStyle !== this.cache.fillStyle[i]) {
          ctx.fillStyle = this.cache.fillStyle[i];
          did_change = true;
        }
        if (ctx.globalAlpha !== this.cache.globalAlpha[i]) {
          ctx.globalAlpha = this.cache.globalAlpha[i];
          did_change = true;
        }
        return did_change;
      };

      return FillProperties;

    })(Properties);
    TextProperties = (function(_super) {
      __extends(TextProperties, _super);

      function TextProperties(styleprovider, prefix) {
        if (prefix == null) {
          prefix = "";
        }
        this.text_font_name = "" + prefix + "text_font";
        this.text_font_size_name = "" + prefix + "text_font_size";
        this.text_font_style_name = "" + prefix + "text_font_style";
        this.text_color_name = "" + prefix + "text_color";
        this.text_alpha_name = "" + prefix + "text_alpha";
        this.text_align_name = "" + prefix + "text_align";
        this.text_baseline_name = "" + prefix + "text_baseline";
        this.string(styleprovider, this.text_font_name);
        this.string(styleprovider, this.text_font_size_name);
        this["enum"](styleprovider, this.text_font_style_name, "normal italic bold");
        this.color(styleprovider, this.text_color_name);
        this.number(styleprovider, this.text_alpha_name);
        this["enum"](styleprovider, this.text_align_name, "left right center");
        this["enum"](styleprovider, this.text_baseline_name, "top middle bottom alphabetic hanging");
      }

      TextProperties.prototype.font = function(obj, font_size) {
        var font, font_style;
        if (font_size == null) {
          font_size = this.select(this.text_font_size_name, obj);
        }
        font = this.select(this.text_font_name, obj);
        font_style = this.select(this.text_font_style_name, obj);
        font = font_style + " " + font_size + " " + font;
        return font;
      };

      TextProperties.prototype.set = function(ctx, obj) {
        ctx.font = this.font(obj);
        ctx.fillStyle = this.select(this.text_color_name, obj);
        ctx.globalAlpha = this.select(this.text_alpha_name, obj);
        ctx.textAlign = this.select(this.text_align_name, obj);
        return ctx.textBaseline = this.select(this.text_baseline_name, obj);
      };

      TextProperties.prototype.set_prop_cache = function(datasource) {
        var font, font_size, font_style, i;
        this.cache = {};
        font_size = this.source_v_select(this.text_font_size_name, datasource);
        font = this.source_v_select(this.text_font_name, datasource);
        font_style = this.source_v_select(this.text_font_style_name, datasource);
        this.cache.font = (function() {
          var _i, _ref, _results;
          _results = [];
          for (i = _i = 0, _ref = font.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
            _results.push("" + font_style[i] + " " + font_size[i] + " " + font[i]);
          }
          return _results;
        })();
        this.cache.fillStyle = this.source_v_select(this.text_color_name, datasource);
        this.cache.globalAlpha = this.source_v_select(this.text_alpha_name, datasource);
        this.cache.textAlign = this.source_v_select(this.text_align_name, datasource);
        return this.cache.textBaseline = this.source_v_select(this.text_baseline_name, datasource);
      };

      TextProperties.prototype.clear_prop_cache = function() {
        return this.cache = {};
      };

      TextProperties.prototype.set_vectorize = function(ctx, i) {
        var did_change;
        did_change = false;
        if (ctx.font !== this.cache.font[i]) {
          ctx.font = this.cache.font[i];
          did_change = true;
        }
        if (ctx.fillStyle !== this.cache.fillStyle[i]) {
          ctx.fillStyle = this.cache.fillStyle[i];
          did_change = true;
        }
        if (ctx.globalAlpha !== this.cache.globalAlpha[i]) {
          ctx.globalAlpha = this.cache.globalAlpha[i];
          did_change = true;
        }
        if (ctx.textAlign !== this.cache.textAlign[i]) {
          ctx.textAlign = this.cache.textAlign[i];
          did_change = true;
        }
        if (ctx.textBaseline !== this.cache.textBaseline[i]) {
          ctx.textBaseline = this.cache.textBaseline[i];
          did_change = true;
        }
        return did_change;
      };

      return TextProperties;

    })(Properties);
    GlyphProperties = (function(_super) {
      __extends(GlyphProperties, _super);

      function GlyphProperties(styleprovider, attrnames) {
        var attrname, attrtype, _i, _len, _ref;
        for (_i = 0, _len = attrnames.length; _i < _len; _i++) {
          attrname = attrnames[_i];
          attrtype = "number";
          if (attrname.indexOf(":") > -1) {
            _ref = attrname.split(":"), attrname = _ref[0], attrtype = _ref[1];
          }
          this.setattr(styleprovider, attrname, attrtype);
        }
      }

      return GlyphProperties;

    })(Properties);
    return {
      Glyph: GlyphProperties,
      Fill: FillProperties,
      Line: LineProperties,
      Text: TextProperties
    };
  });

}).call(this);

/*
//@ sourceMappingURL=properties.js.map
*/;
(function() {
  var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('common/plot',["underscore", "backbone", "kiwi", "./build_views", "./canvas", "./cartesian_frame", "./continuum_view", "./collection", "./ui_events", "./has_parent", "./layout_box", "./logging", "./plot_utils", "./solver", "./tool_manager", "./plot_template", "renderer/properties"], function(_, Backbone, kiwi, build_views, Canvas, CartesianFrame, ContinuumView, Collection, UIEvents, HasParent, LayoutBox, Logging, plot_utils, Solver, ToolManager, plot_template, properties) {
    var Constraint, EQ, Expr, GE, LE, Plot, PlotView, Plots, logger, _ref, _ref1, _ref2;
    Expr = kiwi.Expression;
    Constraint = kiwi.Constraint;
    EQ = kiwi.Operator.Eq;
    LE = kiwi.Operator.Le;
    GE = kiwi.Operator.Ge;
    logger = Logging.logger;
    PlotView = (function(_super) {
      __extends(PlotView, _super);

      function PlotView() {
        this.request_render = __bind(this.request_render, this);
        _ref = PlotView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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.initialize = function(options) {
        var id, level, tool_view, toolbar_location, toolbar_selector, _i, _len, _ref1, _ref2;
        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();
        this.throttled_render = plot_utils.throttle_animation(this.render, 15);
        this.outline_props = new properties.Line(this, 'outline_');
        this.title_props = new properties.Text(this, 'title_');
        this.renderers = {};
        this.tools = {};
        this.levels = {};
        _ref1 = plot_utils.LEVELS;
        for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
          level = _ref1[_i];
          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
        });
        _ref2 = this.tools;
        for (id in _ref2) {
          tool_view = _ref2[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.unpause();
        logger.debug("PlotView initialized");
        return this;
      };

      PlotView.prototype.map_to_screen = function(x, x_units, y, y_units, 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, x_units, y, y_units, this.canvas, x_name, y_name);
      };

      PlotView.prototype.update_range = function(range_info) {
        var name, rng, _ref1, _ref2;
        if (range_info == null) {
          range_info = this.initial_range_info;
        }
        this.pause();
        _ref1 = this.frame.get('x_ranges');
        for (name in _ref1) {
          rng = _ref1[name];
          rng.set(range_info.xrs[name]);
        }
        _ref2 = this.frame.get('y_ranges');
        for (name in _ref2) {
          rng = _ref2[name];
          rng.set(range_info.yrs[name]);
        }
        return this.unpause();
      };

      PlotView.prototype.build_levels = function() {
        var id_, level, old_renderers, renderers_to_remove, t, tools, v, views, _i, _j, _k, _len, _len1, _len2;
        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 (_i = 0, _len = renderers_to_remove.length; _i < _len; _i++) {
          id_ = renderers_to_remove[_i];
          delete this.levels.glyph[id_];
        }
        tools = build_views(this.tools, this.mget('tools'), this.view_options());
        for (_j = 0, _len1 = views.length; _j < _len1; _j++) {
          v = views[_j];
          level = v.mget('level');
          this.levels[level][v.model.id] = v;
          v.bind_bokeh_events();
        }
        for (_k = 0, _len2 = tools.length; _k < _len2; _k++) {
          t = tools[_k];
          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, rng, _ref1, _ref2,
          _this = this;
        _ref1 = this.mget('frame').get('x_ranges');
        for (name in _ref1) {
          rng = _ref1[name];
          this.listenTo(rng, 'change', this.request_render);
        }
        _ref2 = this.mget('frame').get('y_ranges');
        for (name in _ref2) {
          rng = _ref2[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() {
          return _this.remove();
        });
      };

      PlotView.prototype.set_initial_range = function() {
        var good_vals, name, rng, xrs, yrs, _ref1, _ref2;
        good_vals = true;
        xrs = {};
        _ref1 = this.frame.get('x_ranges');
        for (name in _ref1) {
          rng = _ref1[name];
          if ((rng.get('start') == null) || (rng.get('end') == null) || _.isNaN(rng.get('start') + rng.get('end'))) {
            good_vals = false;
            break;
          }
          xrs[name] = {
            start: rng.get('start'),
            end: rng.get('end')
          };
        }
        if (good_vals) {
          yrs = {};
          _ref2 = this.frame.get('y_ranges');
          for (name in _ref2) {
            rng = _ref2[name];
            if ((rng.get('start') == null) || (rng.get('end') == null) || _.isNaN(rng.get('start') + rng.get('end'))) {
              good_vals = false;
              break;
            }
            yrs[name] = {
              start: rng.get('start'),
              end: rng.get('end')
            };
          }
        }
        if (good_vals) {
          this.initial_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, frame, frame_box, height, k, sx, sy, th, title, trigger, v, width, _ref1;
        if (force_canvas == null) {
          force_canvas = false;
        }
        logger.trace("Plot.render(force_canvas=" + force_canvas + ")");
        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');
        _ref1 = this.renderers;
        for (k in _ref1) {
          v = _ref1[k];
          if (v.model.update_layout != null) {
            v.model.update_layout(v, this.canvas.solver);
          }
        }
        title = this.mget('title');
        if (title) {
          this.title_props.set(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();
        if (this.initial_range_info == null) {
          this.set_initial_range();
        }
        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 (this.outline_props.do_stroke) {
          this.outline_props.set(ctx, {});
          ctx.strokeRect.apply(ctx, frame_box);
        }
        this._render_levels(ctx, ['image', 'underlay', 'glyph'], frame_box);
        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(ctx, {});
          return ctx.fillText(title, sx, sy);
        }
      };

      PlotView.prototype._render_levels = function(ctx, levels, clip_region) {
        var i, indices, level, renderer, renderers, sortKey, _i, _j, _k, _len, _len1, _len2, _ref1;
        ctx.save();
        if (clip_region != null) {
          ctx.beginPath();
          ctx.rect.apply(ctx, clip_region);
          ctx.clip();
          ctx.beginPath();
        }
        indices = {};
        _ref1 = this.mget("renderers");
        for (i = _i = 0, _len = _ref1.length; _i < _len; i = ++_i) {
          renderer = _ref1[i];
          indices[renderer.id] = i;
        }
        sortKey = function(renderer) {
          return indices[renderer.model.id];
        };
        for (_j = 0, _len1 = levels.length; _j < _len1; _j++) {
          level = levels[_j];
          renderers = _.sortBy(_.values(this.levels[level]), sortKey);
          for (_k = 0, _len2 = renderers.length; _k < _len2; _k++) {
            renderer = renderers[_k];
            renderer.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(_super) {
      __extends(Plot, _super);

      function Plot() {
        _ref1 = Plot.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Plot.prototype.type = 'Plot';

      Plot.prototype.default_view = PlotView;

      Plot.prototype.initialize = function(attrs, options) {
        var canvas, r, _i, _len, _ref2, _ref3;
        Plot.__super__.initialize.call(this, attrs, options);
        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 (_i = 0, _len = _ref3.length; _i < _len; _i++) {
          r = _ref3[_i];
          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
        });
        LayoutBox.Collection.add(this.title_panel);
        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, _ref2, _ref3, _ref4, _ref5,
          _this = this;
        min_border_top = (_ref2 = this.get('min_border_top')) != null ? _ref2 : this.get('min_border');
        min_border_bottom = (_ref3 = this.get('min_border_bottom')) != null ? _ref3 : this.get('min_border');
        min_border_left = (_ref4 = this.get('min_border_left')) != null ? _ref4 : this.get('min_border');
        min_border_right = (_ref5 = this.get('min_border_right')) != null ? _ref5 : this.get('min_border');
        do_side = function(solver, min_size, side, cnames, dim, op) {
          var box, c0, c1, canvas, elts, frame, last, padding, r, _i, _len, _ref6;
          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 Expr(box['_' + dim], -min_size), GE), kiwi.Strength.strong);
          solver.add_constraint(new Constraint(new Expr(frame[c0], [-1, box[c1]]), EQ));
          solver.add_constraint(new Constraint(new Expr(box[c0], [-1, canvas[c0]]), EQ));
          last = frame;
          elts = _this.get(side);
          for (_i = 0, _len = elts.length; _i < _len; _i++) {
            r = elts[_i];
            if ((_ref6 = r.get('location')) != null ? _ref6 : 'auto' === 'auto') {
              r.set('location', side, {
                'silent': true
              });
            }
            if (r.initialize_layout != null) {
              r.initialize_layout(solver);
            }
            solver.add_constraint(new Constraint(new Expr(last[c0], [-1, r[c1]]), EQ), kiwi.Strength.strong);
            last = r;
          }
          padding = new LayoutBox.Model({
            solver: solver
          });
          solver.add_constraint(new Constraint(new Expr(last[c0], [-1, padding[c1]]), EQ), kiwi.Strength.strong);
          return solver.add_constraint(new Constraint(new Expr(padding[c0], [-1, canvas[c0]]), EQ), kiwi.Strength.strong);
        };
        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.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: 'Plot',
          above: [],
          below: [],
          left: [],
          right: [],
          toolbar_location: "above",
          logo: "normal"
        });
      };

      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);
    Plots = (function(_super) {
      __extends(Plots, _super);

      function Plots() {
        _ref2 = Plots.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Plots.prototype.model = Plot;

      return Plots;

    })(Collection);
    return {
      "Model": Plot,
      "Collection": new Plots(),
      "View": PlotView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=plot.js.map
*/;
(function() {
  var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('common/gmap_plot',["underscore", "./collection", "./solver", "./plot"], function(_, Collection, Solver, Plot) {
    var GMapPlot, GMapPlotView, GMapPlots, _ref, _ref1, _ref2;
    GMapPlotView = (function(_super) {
      __extends(GMapPlotView, _super);

      function GMapPlotView() {
        this.bounds_change = __bind(this.bounds_change, this);
        _ref = GMapPlotView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      GMapPlotView.prototype.initialize = function(options) {
        GMapPlotView.__super__.initialize.call(this, _.defaults(options, this.default_options));
        return this.zoom_count = null;
      };

      GMapPlotView.prototype.update_range = function(range_info) {
        var center, ne_lat, ne_lng, sw_lat, sw_lng, xr, yr;
        if (range_info == null) {
          range_info = this.initial_range_info;
        }
        this.pause();
        if (range_info.sdx != null) {
          this.map.panBy(range_info.sdx, range_info.sdy);
        } else {
          xr = range_info.xrs["default"];
          yr = range_info.yrs["default"];
          sw_lng = Math.min(xr.start, xr.end);
          ne_lng = Math.max(xr.start, xr.end);
          sw_lat = Math.min(yr.start, yr.end);
          ne_lat = Math.max(yr.start, yr.end);
          center = new google.maps.LatLng((ne_lat + sw_lat) / 2, (ne_lng + sw_lng) / 2);
          if (range_info.factor == null) {
            this.map.setCenter(center);
            this.map.setZoom(this.initial_zoom);
          } else if (range_info.factor > 0) {
            this.zoom_count += 1;
            if (this.zoom_count === 10) {
              this.map.setZoom(this.map.getZoom() + 1);
              this.zoom_count = 0;
            }
          } else {
            this.zoom_count -= 1;
            if (this.zoom_count === -10) {
              this.map.setCenter(center);
              this.map.setZoom(this.map.getZoom() - 1);
              this.map.setCenter(center);
              this.zoom_count = 0;
            }
          }
        }
        return this.unpause();
      };

      GMapPlotView.prototype.bind_bokeh_events = function() {
        var build_map, height, left, script, top, width,
          _this = this;
        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() {
          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]
          };
          _this.map = new maps.Map(_this.canvas_view.map_div[0], map_options);
          return maps.event.addListener(_this.map, 'bounds_changed', _this.bounds_change);
        };
        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.exp&sensor=false&callback=_bokeh_gmap_callback';
          return document.body.appendChild(script);
        }
      };

      GMapPlotView.prototype.bounds_change = function() {
        var bds, ne, sw;
        bds = this.map.getBounds();
        ne = bds.getNorthEast();
        sw = bds.getSouthWest();
        this.x_range.set({
          start: sw.lng(),
          end: ne.lng(),
          silent: true
        });
        this.y_range.set({
          start: sw.lat(),
          end: ne.lat(),
          silent: true
        });
        if (this.initial_range_info == null) {
          this.initial_range_info = {
            xr: {
              start: this.x_range.get('start'),
              end: this.x_range.get('end')
            },
            yr: {
              start: this.y_range.get('start'),
              end: this.y_range.get('end')
            }
          };
        }
        return this.render();
      };

      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(_super) {
      __extends(GMapPlot, _super);

      function GMapPlot() {
        _ref1 = GMapPlot.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      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);
    GMapPlots = (function(_super) {
      __extends(GMapPlots, _super);

      function GMapPlots() {
        _ref2 = GMapPlots.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      GMapPlots.prototype.model = GMapPlot;

      return GMapPlots;

    })(Collection);
    return {
      "Model": GMapPlot,
      "Collection": new GMapPlots(),
      "View": GMapPlotView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=gmap_plot.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('common/geojs_plot',["underscore", "./collection", "./solver", "./plot"], function(_, Collection, Solver, Plot) {
    var GeoJSPlot, GeoJSPlotView, GeoJSPlots, _ref, _ref1, _ref2;
    GeoJSPlotView = (function(_super) {
      __extends(GeoJSPlotView, _super);

      function GeoJSPlotView() {
        _ref = GeoJSPlotView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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,
          _this = this;
        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() {
          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');
        };
        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(_super) {
      __extends(GeoJSPlot, _super);

      function GeoJSPlot() {
        _ref1 = GeoJSPlot.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      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);
    GeoJSPlots = (function(_super) {
      __extends(GeoJSPlots, _super);

      function GeoJSPlots() {
        _ref2 = GeoJSPlots.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      GeoJSPlots.prototype.model = GeoJSPlot;

      return GeoJSPlots;

    })(Collection);
    return {
      "Model": GeoJSPlot,
      "Collection": new GeoJSPlots(),
      "View": GeoJSPlotView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=geojs_plot.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, 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(fn, me){ return function(){ return fn.apply(me, arguments); }; };

  define('common/grid_plot',["underscore", "backbone", "./build_views", "./continuum_view", "./collection", "./has_properties", "./logging", "./tool_manager", "./plot_template", "renderer/properties"], function(_, Backbone, build_views, ContinuumView, Collection, HasProperties, Logging, ToolManager, plot_template, Properties) {
    var GridPlot, GridPlotView, GridPlots, GridToolManager, GridViewState, logger, _ToolProxy, _ref, _ref1, _ref2, _ref3, _ref4, _ref5;
    logger = Logging.logger;
    _ToolProxy = (function(_super) {
      __extends(_ToolProxy, _super);

      function _ToolProxy() {
        _ref = _ToolProxy.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      _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 tool, _i, _len, _ref1;
        _ref1 = this.attributes.tools;
        for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
          tool = _ref1[_i];
          tool.trigger('do');
        }
        return null;
      };

      _ToolProxy.prototype.active = function() {
        var tool, _i, _len, _ref1;
        _ref1 = this.attributes.tools;
        for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
          tool = _ref1[_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 tool, _i, _len, _ref1;
        _ToolProxy.__super__.set.call(this, attr, value);
        _ref1 = this.attributes.tools;
        for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
          tool = _ref1[_i];
          tool.set(attr, value);
        }
        return null;
      };

      return _ToolProxy;

    })(Backbone.Model);
    GridToolManager = (function(_super) {
      __extends(GridToolManager, _super);

      function GridToolManager() {
        this._active_change = __bind(this._active_change, this);
        _ref1 = GridToolManager.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      GridToolManager.prototype._init_tools = function() {
        var actions, et, gestures, info, inspectors, proxy, tm, tmp, tool, tools, typ, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8, _results;
        inspectors = {};
        actions = {};
        gestures = {};
        _ref2 = this.get('tool_managers');
        for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
          tm = _ref2[_i];
          _ref3 = tm.get('gestures');
          for (et in _ref3) {
            info = _ref3[et];
            if (!(et in gestures)) {
              gestures[et] = {};
            }
            _ref4 = info.tools;
            for (_j = 0, _len1 = _ref4.length; _j < _len1; _j++) {
              tool = _ref4[_j];
              if (!(tool.type in gestures[et])) {
                gestures[et][tool.type] = [];
              }
              gestures[et][tool.type].push(tool);
            }
          }
          _ref5 = tm.get('inspectors');
          for (_k = 0, _len2 = _ref5.length; _k < _len2; _k++) {
            tool = _ref5[_k];
            if (!(tool.type in inspectors)) {
              inspectors[tool.type] = [];
            }
            inspectors[tool.type].push(tool);
          }
          _ref6 = tm.get('actions');
          for (_l = 0, _len3 = _ref6.length; _l < _len3; _l++) {
            tool = _ref6[_l];
            if (!(tool.type in actions)) {
              actions[tool.type] = [];
            }
            actions[tool.type].push(tool);
          }
        }
        for (et in gestures) {
          _ref7 = gestures[et];
          for (typ in _ref7) {
            tools = _ref7[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);
        }
        _ref8 = this.get('gestures');
        _results = [];
        for (et in _ref8) {
          info = _ref8[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(_super) {
      __extends(GridViewState, _super);

      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);
        _ref2 = GridViewState.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      GridViewState.prototype.setup_layout_properties = function() {
        var row, viewstate, _i, _len, _ref3, _results;
        this.register_property('layout_heights', this.layout_heights, false);
        this.register_property('layout_widths', this.layout_widths, false);
        _ref3 = this.get('viewstates');
        _results = [];
        for (_i = 0, _len = _ref3.length; _i < _len; _i++) {
          row = _ref3[_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) {
        GridViewState.__super__.initialize.call(this, attrs, options);
        this.setup_layout_properties();
        this.listenTo(this, 'change:viewstates', this.setup_layout_properties);
        this.register_property('height', function() {
          return _.reduce(this.get('layout_heights'), (function(x, y) {
            return x + y;
          }), 0);
        }, false);
        this.add_dependencies('height', this, 'layout_heights');
        this.register_property('width', function() {
          return _.reduce(this.get('layout_widths'), (function(x, y) {
            return x + y;
          }), 0);
        }, 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, _ref3, _results;
          _ref3 = this.get('viewstates');
          _results = [];
          for (_i = 0, _len = _ref3.length; _i < _len; _i++) {
            row = _ref3[_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, _ref3, _results;
          _ref3 = _.range(num_cols);
          _results = [];
          for (_i = 0, _len = _ref3.length; _i < _len; _i++) {
            n = _ref3[_i];
            _results.push((function() {
              var _j, _len1, _ref4, _results1;
              _ref4 = this.get('viewstates');
              _results1 = [];
              for (_j = 0, _len1 = _ref4.length; _j < _len1; _j++) {
                row = _ref4[_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(_super) {
      __extends(GridPlotView, _super);

      function GridPlotView() {
        _ref3 = GridPlotView.__super__.constructor.apply(this, arguments);
        return _ref3;
      }

      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, plot, row, viewstates, vsrow, _i, _j, _k, _l, _len, _len1, _len2, _len3, _len4, _m, _ref4, _ref5, _ref6, _results;
        childmodels = [];
        _ref4 = this.mget('children');
        for (_i = 0, _len = _ref4.length; _i < _len; _i++) {
          row = _ref4[_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 = [];
        _ref5 = this.mget('children');
        for (_k = 0, _len2 = _ref5.length; _k < _len2; _k++) {
          row = _ref5[_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);
        _ref6 = this.mget('children');
        _results = [];
        for (_m = 0, _len4 = _ref6.length; _m < _len4; _m++) {
          row = _ref6[_m];
          _results.push((function() {
            var _len5, _n, _results1;
            _results1 = [];
            for (_n = 0, _len5 = row.length; _n < _len5; _n++) {
              plot = row[_n];
              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, last_plot, plot, plot_divs, plot_wrapper, ridx, row, row_heights, toolbar_location, toolbar_selector, total_height, view, width, x_coords, xpos, y_coords, ypos, _i, _j, _k, _len, _len1, _len2, _ref4, _ref5;
        GridPlotView.__super__.render.call(this);
        _ref4 = _.values(this.child_views);
        for (_i = 0, _len = _ref4.length; _i < _len; _i++) {
          view = _ref4[_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;
        _ref5 = this.mget('children');
        for (ridx = _j = 0, _len1 = _ref5.length; _j < _len1; ridx = ++_j) {
          row = _ref5[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(_super) {
      __extends(GridPlot, _super);

      function GridPlot() {
        _ref4 = GridPlot.__super__.constructor.apply(this, arguments);
        return _ref4;
      }

      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, plot, _i, _len, _ref5;
          children = [];
          _ref5 = _.flatten(this.get('children'));
          for (_i = 0, _len = _ref5.length; _i < _len; _i++) {
            plot = _ref5[_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);
    GridPlots = (function(_super) {
      __extends(GridPlots, _super);

      function GridPlots() {
        _ref5 = GridPlots.__super__.constructor.apply(this, arguments);
        return _ref5;
      }

      GridPlots.prototype.model = GridPlot;

      return GridPlots;

    })(Collection);
    return {
      "Model": GridPlot,
      "Collection": new GridPlots(),
      "View": GridPlotView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=grid_plot.js.map
*/;
(function() {
  var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('common/plot_context',["underscore", "./collection", "./build_views", "./has_parent", "./continuum_view"], function(_, Collection, build_views, HasParent, ContinuumView) {
    var PlotContext, PlotContextView, PlotContexts, _ref, _ref1, _ref2;
    PlotContextView = (function(_super) {
      __extends(PlotContextView, _super);

      function PlotContextView() {
        this.removeplot = __bind(this.removeplot, this);
        this.closeall = __bind(this.closeall, this);
        _ref = PlotContextView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      PlotContextView.prototype.initialize = function(options) {
        this.views = {};
        this.child_models = [];
        PlotContextView.__super__.initialize.call(this, options);
        return this.render();
      };

      PlotContextView.prototype.delegateEvents = function() {
        this.listenTo(this.model, 'destroy', this.remove);
        this.listenTo(this.model, 'change', this.render);
        return PlotContextView.__super__.delegateEvents.call(this);
      };

      PlotContextView.prototype.build_children = function() {
        var created_views;
        created_views = build_views(this.views, this.mget('children'), {});
        window.pc_created_views = created_views;
        window.pc_views = this.views;
        return null;
      };

      PlotContextView.prototype.size_textarea = function(textarea) {
        var scrollHeight;
        scrollHeight = $(textarea).height(0).prop('scrollHeight');
        return $(textarea).height(scrollHeight);
      };

      PlotContextView.prototype.closeall = function(e) {
        this.mset('children', []);
        return this.model.save();
      };

      PlotContextView.prototype.removeplot = function(e) {
        var newchildren, plotnum, s_pc, view, x;
        plotnum = parseInt($(e.currentTarget).parent().attr('data-plot_num'));
        s_pc = this.mget('children')[plotnum];
        view = this.views[s_pc.get('id')];
        view.remove();
        newchildren = (function() {
          var _i, _len, _ref1, _results;
          _ref1 = this.mget('children');
          _results = [];
          for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
            x = _ref1[_i];
            if (x.id !== view.model.id) {
              _results.push(x);
            }
          }
          return _results;
        }).call(this);
        this.mset('children', newchildren);
        this.model.save();
        return false;
      };

      PlotContextView.prototype.render = function() {
        var index, key, modelref, node, numplots, tab_names, to_render, val, view, _i, _len, _ref1, _ref2,
          _this = this;
        PlotContextView.__super__.render.call(this);
        this.build_children();
        _ref1 = this.views;
        for (key in _ref1) {
          if (!__hasProp.call(_ref1, key)) continue;
          val = _ref1[key];
          val.$el.detach();
        }
        this.$el.html('');
        numplots = _.keys(this.views).length;
        to_render = [];
        tab_names = {};
        _ref2 = this.mget('children');
        for (index = _i = 0, _len = _ref2.length; _i < _len; index = ++_i) {
          modelref = _ref2[index];
          view = this.views[modelref.id];
          node = $("<div class='jsp' data-plot_num='" + index + "'></div>");
          this.$el.append(node);
          node.append(view.el);
        }
        _.defer(function() {
          var textarea, _j, _len1, _ref3, _results;
          _ref3 = _this.$el.find('.plottitle');
          _results = [];
          for (_j = 0, _len1 = _ref3.length; _j < _len1; _j++) {
            textarea = _ref3[_j];
            _results.push(_this.size_textarea($(textarea)));
          }
          return _results;
        });
        return null;
      };

      return PlotContextView;

    })(ContinuumView);
    PlotContext = (function(_super) {
      __extends(PlotContext, _super);

      function PlotContext() {
        _ref1 = PlotContext.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      PlotContext.prototype.type = 'PlotContext';

      PlotContext.prototype.default_view = PlotContextView;

      PlotContext.prototype.url = function() {
        return PlotContext.__super__.url.call(this);
      };

      PlotContext.prototype.defaults = function() {
        return _.extend({}, PlotContext.__super__.defaults.call(this), {
          children: []
        });
      };

      return PlotContext;

    })(HasParent);
    PlotContexts = (function(_super) {
      __extends(PlotContexts, _super);

      function PlotContexts() {
        _ref2 = PlotContexts.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      PlotContexts.prototype.model = PlotContext;

      return PlotContexts;

    })(Collection);
    return {
      "Model": PlotContext,
      "Collection": new PlotContexts(),
      "View": PlotContextView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=plot_context.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('common/selector',["underscore", "./has_properties", "./logging"], function(_, HasProperties, Logging) {
    var Selector, logger, _ref;
    logger = Logging.logger;
    return Selector = (function(_super) {
      __extends(Selector, _super);

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

      Selector.prototype.type = 'Selector';

      Selector.prototype.update = function(indices, final, append) {
        this.set('timestamp', new Date());
        this.set('final', final);
        if (append) {
          indices = _.union(this.get('indices'), indices);
        }
        return this.set('indices', indices);
      };

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

      Selector.prototype.defaults = function() {
        return _.extend({}, Selector.__super__.defaults.call(this), {
          indices: []
        });
      };

      return Selector;

    })(HasProperties);
  });

}).call(this);

/*
//@ sourceMappingURL=selector.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('common/selection_manager',["underscore", "./has_properties", "./logging", "./selector"], function(_, HasProperties, Logging, Selector) {
    var SelectionManager, logger, _ref;
    logger = Logging.logger;
    return SelectionManager = (function(_super) {
      __extends(SelectionManager, _super);

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

      SelectionManager.prototype.type = 'SelectionManager';

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

      SelectionManager.prototype.set_selection = function(indices) {
        this._save_indices(indices);
        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);
        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, s, selector, _ref1;
        if (rview != null) {
          selector = this._get_selector(rview);
          selector.clear();
        } else {
          _ref1 = this.selectors;
          for (k in _ref1) {
            s = _ref1[k];
            s.clear();
          }
        }
        return this._save_indices([]);
      };

      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').save({
          "selected": indices
        }, {
          patch: true
        });
      };

      return SelectionManager;

    })(HasProperties);
  });

}).call(this);

/*
//@ sourceMappingURL=selection_manager.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('common/tool_events',["backbone", "common/has_properties", "common/logging"], function(Backbone, HasProperties, Logging) {
    var ToolEvents, ToolEventsCollection, logger, _ref, _ref1;
    logger = Logging.logger;
    ToolEvents = (function(_super) {
      __extends(ToolEvents, _super);

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

      ToolEvents.prototype.type = 'ToolEvents';

      return ToolEvents;

    })(HasProperties);
    ToolEventsCollection = (function(_super) {
      __extends(ToolEventsCollection, _super);

      function ToolEventsCollection() {
        _ref1 = ToolEventsCollection.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      ToolEventsCollection.prototype.model = ToolEvents;

      return ToolEventsCollection;

    })(Backbone.Collection);
    return {
      "Model": ToolEvents,
      "Collection": new ToolEventsCollection()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=tool_events.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('mapper/linear_color_mapper',["underscore", "common/collection", "common/has_properties"], function(_, Collection, HasProperties) {
    var LinearColorMapper, LinearColorMappers, _ref, _ref1;
    LinearColorMapper = (function(_super) {
      __extends(LinearColorMapper, _super);

      function LinearColorMapper() {
        _ref = LinearColorMapper.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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, low, offset, scale, value, _i, _j, _ref1, _ref2, _ref3, _ref4;
        buf = new ArrayBuffer(data.length * 4);
        color = new Uint32Array(buf);
        low = (_ref1 = this.get('low')) != null ? _ref1 : _.min(data);
        high = (_ref2 = this.get('high')) != null ? _ref2 : _.max(data);
        N = this.palette.length - 1;
        scale = N / (high - low);
        offset = -scale * low;
        if (this.little_endian) {
          for (i = _i = 0, _ref3 = data.length; 0 <= _ref3 ? _i < _ref3 : _i > _ref3; i = 0 <= _ref3 ? ++_i : --_i) {
            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 = _j = 0, _ref4 = data.length; 0 <= _ref4 ? _j < _ref4 : _j > _ref4; i = 0 <= _ref4 ? ++_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] = (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 i, new_palette, _i, _ref1;
        new_palette = new Uint32Array(palette.length + 1);
        for (i = _i = 0, _ref1 = palette.length; 0 <= _ref1 ? _i < _ref1 : _i > _ref1; i = 0 <= _ref1 ? ++_i : --_i) {
          if (_.isNumber(palette[i])) {
            new_palette[i] = palette[i];
          } else {
            new_palette[i] = parseInt(palette[i].slice(1), 16);
          }
        }
        new_palette[new_palette.length - 1] = palette[palette.length - 1];
        return new_palette;
      };

      return LinearColorMapper;

    })(HasProperties);
    LinearColorMappers = (function(_super) {
      __extends(LinearColorMappers, _super);

      function LinearColorMappers() {
        _ref1 = LinearColorMappers.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      LinearColorMappers.prototype.model = LinearColorMapper;

      return LinearColorMappers;

    })(Collection);
    return {
      "Model": LinearColorMapper,
      "Collection": new LinearColorMappers()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=linear_color_mapper.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('range/data_range1d',["underscore", "common/collection", "range/range1d"], function(_, Collection, Range1d) {
    var DataRange1d, DataRange1ds, _ref, _ref1;
    DataRange1d = (function(_super) {
      __extends(DataRange1d, _super);

      function DataRange1d() {
        _ref = DataRange1d.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      DataRange1d.prototype.type = 'DataRange1d';

      DataRange1d.prototype._get_minmax = function() {
        var center, colname, columns, max, min, source, sourceobj, span, _i, _j, _len, _len1, _ref1, _ref2, _ref3, _ref4;
        columns = [];
        _ref1 = this.get('sources');
        for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
          source = _ref1[_i];
          sourceobj = this.resolve_ref(source['source']);
          _ref2 = source['columns'];
          for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) {
            colname = _ref2[_j];
            columns.push(sourceobj.get_column(colname));
          }
        }
        columns = _.flatten(columns);
        columns = _.filter(columns, function(x) {
          return typeof x !== "string";
        });
        columns = _.reject(columns, function(x) {
          return isNaN(x);
        });
        _ref3 = [_.min(columns), _.max(columns)], min = _ref3[0], max = _ref3[1];
        if (max !== min) {
          span = (max - min) * (1 + this.get('rangepadding'));
        } else {
          if (max !== 0) {
            span = Math.abs(max) * (1 + this.get('rangepadding'));
          } else {
            span = 2;
          }
        }
        center = (max + min) / 2.0;
        _ref4 = [center - span / 2.0, center + span / 2.0], min = _ref4[0], max = _ref4[1];
        return [min, max];
      };

      DataRange1d.prototype._get_start = function() {
        if (!_.isNullOrUndefined(this.get('_start'))) {
          return this.get('_start');
        } else {
          return this.get('minmax')[0];
        }
      };

      DataRange1d.prototype._set_start = function(start) {
        return this.set('_start', start);
      };

      DataRange1d.prototype._get_end = function() {
        if (!_.isNullOrUndefined(this.get('_end'))) {
          return this.get('_end');
        } else {
          return this.get('minmax')[1];
        }
      };

      DataRange1d.prototype._set_end = function(end) {
        return this.set('_end', end);
      };

      DataRange1d.prototype.initialize = function(attrs, options) {
        var columns_ref, source, _i, _len, _ref1;
        this.register_property('minmax', this._get_minmax, true);
        this.add_dependencies('minmax', this, ['sources'], ['rangepadding']);
        _ref1 = this.get('sources');
        for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
          columns_ref = _ref1[_i];
          source = this.resolve_ref(columns_ref.source);
          this.add_dependencies('minmax', source, 'data');
        }
        this.register_property('start', this._get_start, true);
        this.register_setter('start', this._set_start);
        this.add_dependencies('start', this, ['minmax', '_start']);
        this.register_property('end', this._get_end, true);
        this.register_setter('end', this._set_end);
        this.add_dependencies('end', this, ['minmax', '_end']);
        return DataRange1d.__super__.initialize.call(this, attrs, options);
      };

      DataRange1d.prototype.defaults = function() {
        return _.extend({}, DataRange1d.__super__.defaults.call(this), {
          sources: [],
          rangepadding: 0.1
        });
      };

      return DataRange1d;

    })(Range1d.Model);
    DataRange1ds = (function(_super) {
      __extends(DataRange1ds, _super);

      function DataRange1ds() {
        _ref1 = DataRange1ds.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      DataRange1ds.prototype.model = DataRange1d;

      return DataRange1ds;

    })(Collection);
    return {
      "Model": DataRange1d,
      "Collection": new DataRange1ds()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=data_range1d.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('range/factor_range',["common/collection", "common/has_properties"], function(Collection, HasProperties) {
    var FactorRange, FactorRanges, _ref, _ref1;
    FactorRange = (function(_super) {
      __extends(FactorRange, _super);

      function FactorRange() {
        _ref = FactorRange.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      FactorRange.prototype.type = 'FactorRange';

      FactorRange.prototype.initialize = function(attrs, options) {
        FactorRange.__super__.initialize.call(this, attrs, options);
        this.set('end', this.get('factors').length + 0.5);
        this.register_property('min', function() {
          return this.get('start');
        }, false);
        this.add_dependencies('min', this, ['factors']);
        this.register_property('max', function() {
          return this.get('end');
        }, false);
        this.add_dependencies('max', this, ['factors']);
        return this.listenTo(this, 'change:factors', function() {
          return this.set('end', this.get('factors').length + 0.5);
        });
      };

      FactorRange.prototype.defaults = function() {
        return _.extend({}, FactorRange.__super__.defaults.call(this), {
          start: 0.5,
          factors: []
        });
      };

      return FactorRange;

    })(HasProperties);
    FactorRanges = (function(_super) {
      __extends(FactorRanges, _super);

      function FactorRanges() {
        _ref1 = FactorRanges.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      FactorRanges.prototype.model = FactorRange;

      return FactorRanges;

    })(Collection);
    return {
      "Model": FactorRange,
      "Collection": new FactorRanges()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=factor_range.js.map
*/;
(function() {
  define('common/textutils',[], function() {
    var cache, getTextHeight;
    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;
    };
    return {
      "getTextHeight": getTextHeight
    };
  });

}).call(this);

/*
//@ sourceMappingURL=textutils.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/annotation/legend',["underscore", "common/has_parent", "common/plot_widget", "common/collection", "common/textutils", "renderer/properties"], function(_, HasParent, PlotWidget, Collection, textutils, properties) {
    var Legend, LegendView, Legends, _ref, _ref1, _ref2;
    LegendView = (function(_super) {
      __extends(LegendView, _super);

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

      LegendView.prototype.initialize = function(options) {
        LegendView.__super__.initialize.call(this, options);
        this.label_props = new properties.Text(this, 'label_');
        this.border_props = new properties.Line(this, 'border_');
        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, text_width, text_widths, v_range, x, y, _ref1;
        legend_names = (function() {
          var _i, _len, _ref1, _ref2, _results;
          _ref1 = this.mget("legends");
          _results = [];
          for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
            _ref2 = _ref1[_i], legend_name = _ref2[0], glyphs = _ref2[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(this)), 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(ctx, this);
        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") {
          _ref1 = this.absolute_coords, x = _ref1[0], y = _ref1[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, idx, legend_name, legend_spacing, renderer, view, x, x1, x2, y, y1, y2, yoffset, yspacing, _i, _j, _len, _len1, _ref1, _ref2, _ref3;
        if (this.need_calc_dims) {
          this.calc_dims();
          this.need_calc_dims = false;
        }
        ctx = this.plot_view.canvas_view.ctx;
        ctx.save();
        ctx.fillStyle = this.plot_model.get('background_fill');
        this.border_props.set(ctx, this);
        ctx.beginPath();
        ctx.rect(this.box_coords[0], this.box_coords[1], this.legend_width, this.legend_height);
        ctx.fill();
        ctx.stroke();
        legend_spacing = this.mget('legend_spacing');
        _ref1 = this.mget("legends");
        for (idx = _i = 0, _len = _ref1.length; _i < _len; idx = ++_i) {
          _ref2 = _ref1[idx], legend_name = _ref2[0], glyphs = _ref2[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(ctx, this);
          ctx.fillText(legend_name, x, y);
          _ref3 = this.model.resolve_ref(glyphs);
          for (_j = 0, _len1 = _ref3.length; _j < _len1; _j++) {
            renderer = _ref3[_j];
            view = this.plot_view.renderers[renderer.id];
            view.draw_legend(ctx, x1, x2, y1, y2);
          }
        }
        return ctx.restore();
      };

      return LegendView;

    })(PlotWidget);
    Legend = (function(_super) {
      __extends(Legend, _super);

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

      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,
          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);
    Legends = (function(_super) {
      __extends(Legends, _super);

      function Legends() {
        _ref2 = Legends.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Legends.prototype.model = Legend;

      return Legends;

    })(Collection);
    return {
      "Model": Legend,
      "Collection": new Legends(),
      "View": LegendView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=legend.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/annotation/span',["underscore", "common/has_parent", "common/plot_widget", "common/collection", "common/logging"], function(_, HasParent, PlotWidget, Collection, Logging) {
    var Span, SpanView, Spans, logger, _ref, _ref1, _ref2;
    logger = Logging.logger;
    SpanView = (function(_super) {
      __extends(SpanView, _super);

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

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

      SpanView.prototype.bind_bokeh_events = function() {
        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, frame, height, left, top, width;
        if (this.mget('location') == null) {
          this.$el.hide();
          return;
        }
        frame = this.plot_model.get('frame');
        canvas = this.plot_model.get('canvas');
        if (this.mget('dimension') === 'width') {
          top = canvas.vy_to_sy(this.mget('location'));
          left = canvas.vx_to_sx(frame.get('left'));
          width = "" + (frame.get('width')) + "px";
          height = "1px";
        } else {
          top = canvas.vy_to_sy(frame.get('top'));
          left = canvas.vx_to_sx(this.mget('location'));
          width = "1px";
          height = "" + (frame.get('height')) + "px";
        }
        this.$el.css({
          'top': top,
          'left': left,
          'width': width,
          'height': height,
          'z-index': 1000,
          'background-color': this.mget('color')
        });
        return this.$el.show();
      };

      return SpanView;

    })(PlotWidget);
    Span = (function(_super) {
      __extends(Span, _super);

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

      Span.prototype.default_view = SpanView;

      Span.prototype.type = 'Span';

      Span.prototype.defaults = function() {
        return _.extend({}, Span.__super__.defaults.call(this), {
          level: "overlay",
          dimension: "width",
          units: "screen",
          color: "black"
        });
      };

      return Span;

    })(HasParent);
    Spans = (function(_super) {
      __extends(Spans, _super);

      function Spans() {
        _ref2 = Spans.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Spans.prototype.model = Span;

      return Spans;

    })(Collection);
    return {
      "Model": Span,
      "Collection": new Spans(),
      "View": SpanView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=span.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/annotation/tooltip',["underscore", "common/has_parent", "common/plot_widget", "common/collection", "common/logging"], function(_, HasParent, PlotWidget, Collection, Logging) {
    var Tooltip, TooltipView, Tooltips, logger, _ref, _ref1, _ref2;
    logger = Logging.logger;
    TooltipView = (function(_super) {
      __extends(TooltipView, _super);

      function TooltipView() {
        _ref = TooltipView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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 content, left, ow, side, sx, sy, tip, top, val, vx, vy, _i, _len, _ref1;
        this.$el.empty();
        this.$el.hide();
        this.$el.toggleClass("bk-tooltip-custom", this.mget("custom"));
        if (_.isEmpty(this.mget('data'))) {
          return;
        }
        _ref1 = this.mget('data');
        for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
          val = _ref1[_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');
        if (side === "right") {
          this.$el.addClass("bk-left");
          top = sy - this.$el.height() / 2;
          left = sx + 18;
        } else if (side === "left") {
          this.$el.addClass("bk-right");
          top = sy - this.$el.height() / 2;
          left = sx - this.$el.width() - 23;
        } else {
          logger.warn("invalid tooltip side: '" + side + "'");
          return;
        }
        if (this.$el.children().length > 0) {
          this.$el.css({
            top: top,
            left: left
          });
          return this.$el.show();
        }
      };

      return TooltipView;

    })(PlotWidget);
    Tooltip = (function(_super) {
      __extends(Tooltip, _super);

      function Tooltip() {
        _ref1 = Tooltip.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      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);
    Tooltips = (function(_super) {
      __extends(Tooltips, _super);

      function Tooltips() {
        _ref2 = Tooltips.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Tooltips.prototype.model = Tooltip;

      return Tooltips;

    })(Collection);
    return {
      "Model": Tooltip,
      "Collection": new Tooltips(),
      "View": TooltipView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=tooltip.js.map
*/;
(function() {
  var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('source/column_data_source',["underscore", "common/collection", "common/has_properties", "common/selection_manager"], function(_, Collection, HasProperties, SelectionManager) {
    var ColumnDataSource, ColumnDataSources, _ref, _ref1;
    ColumnDataSource = (function(_super) {
      __extends(ColumnDataSource, _super);

      function ColumnDataSource() {
        this.defaults = __bind(this.defaults, this);
        _ref = ColumnDataSource.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      ColumnDataSource.prototype.type = 'ColumnDataSource';

      ColumnDataSource.prototype.get_column = function(colname) {
        var _ref1;
        return (_ref1 = this.get('data')[colname]) != null ? _ref1 : 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.datapoints = function() {
        var data, field, fields, i, point, points, _i, _j, _len, _ref1;
        data = this.get('data');
        fields = _.keys(data);
        if (fields.length === 0) {
          return [];
        }
        points = [];
        for (i = _i = 0, _ref1 = data[fields[0]].length; 0 <= _ref1 ? _i < _ref1 : _i > _ref1; i = 0 <= _ref1 ? ++_i : --_i) {
          point = {};
          for (_j = 0, _len = fields.length; _j < _len; _j++) {
            field = fields[_j];
            point[field] = data[field][i];
          }
          points.push(point);
        }
        return points;
      };

      ColumnDataSource.prototype.defaults = function() {
        return _.extend({}, ColumnDataSource.__super__.defaults.call(this), {
          data: {},
          selection_manager: new SelectionManager({
            'source': this
          })
        });
      };

      return ColumnDataSource;

    })(HasProperties);
    ColumnDataSources = (function(_super) {
      __extends(ColumnDataSources, _super);

      function ColumnDataSources() {
        _ref1 = ColumnDataSources.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      ColumnDataSources.prototype.model = ColumnDataSource;

      return ColumnDataSources;

    })(Collection);
    return {
      "Model": ColumnDataSource,
      "Collection": new ColumnDataSources()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=column_data_source.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('source/remote_data_source',["backbone", "underscore", "./column_data_source"], function(Backbone, _, ColumnDataSource) {
    var RemoteDataSource, _ref;
    RemoteDataSource = (function(_super) {
      __extends(RemoteDataSource, _super);

      function RemoteDataSource() {
        _ref = RemoteDataSource.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      return RemoteDataSource;

    })(ColumnDataSource.Model);
    return {
      'RemoteDataSource': RemoteDataSource
    };
  });

}).call(this);

/*
//@ sourceMappingURL=remote_data_source.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/glyph_renderer',["underscore", "common/logging", "common/has_parent", "common/collection", "common/plot_widget", "range/factor_range", "source/remote_data_source"], function(_, Logging, HasParent, Collection, PlotWidget, FactorRange, RemoteDataSource) {
    var GlyphRenderer, GlyphRendererView, GlyphRenderers, logger, _ref, _ref1, _ref2;
    logger = Logging.logger;
    GlyphRendererView = (function(_super) {
      __extends(GlyphRendererView, _super);

      function GlyphRendererView() {
        _ref = GlyphRendererView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      GlyphRendererView.prototype.initialize = function(options) {
        var nonselection_glyph, selection_glyph;
        GlyphRendererView.__super__.initialize.call(this, options);
        this.glyph = this.build_glyph(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(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(nonselection_glyph);
        this.need_set_data = true;
        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")];
        if (this.mget('data_source') instanceof RemoteDataSource.RemoteDataSource) {
          return this.mget('data_source').setup(this.plot_view, this.glyph);
        }
      };

      GlyphRendererView.prototype.build_glyph = 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);
        return this.listenTo(this.mget('data_source'), 'select', this.request_render);
      };

      GlyphRendererView.prototype.have_selection_glyphs = function() {
        return true;
      };

      GlyphRendererView.prototype.setup_server_data = function() {};

      GlyphRendererView.prototype.set_data = function(request_render) {
        var dt, source, t0;
        if (request_render == null) {
          request_render = true;
        }
        source = this.mget('data_source');
        t0 = Date.now();
        this.all_indices = this.glyph.set_data(source);
        this.selection_glyph.set_data(source);
        this.nonselection_glyph.set_data(source);
        dt = Date.now() - t0;
        logger.debug("" + this.glyph.model.type + " glyph (" + this.glyph.model.id + "): set_data finished in " + dt + "ms");
        this.have_new_data = true;
        if (request_render) {
          return this.request_render();
        }
      };

      GlyphRendererView.prototype.render = function() {
        var ctx, do_render, dt, i, idx, indices, nonselected, selected, selected_indices, selected_mask, selection, t0, _i, _j, _len, _len1,
          _this = this;
        if (this.need_set_data) {
          this.set_data(false);
          this.need_set_data = false;
        }
        this.glyph._map_data();
        this.selection_glyph._map_data();
        this.nonselection_glyph._map_data();
        if ((this._mask_data != null) && !(this.plot_view.x_range instanceof FactorRange.Model) && !(this.plot_view.y_range instanceof FactorRange.Model)) {
          indices = this._mask_data();
        } else {
          indices = this.all_indices;
        }
        ctx = this.plot_view.canvas_view.ctx;
        ctx.save();
        do_render = function(ctx, indices, glyph) {
          if (_this.have_new_data) {
            glyph.update_data(_this.mget('data_source'));
          }
          return glyph.render(ctx, indices);
        };
        selection = this.mget('data_source').get('selected');
        if ((selection != null) && selection.length > 0) {
          selected_indices = selection;
        } else {
          selected_indices = [];
        }
        t0 = Date.now();
        if (!(selected_indices && selected_indices.length && this.have_selection_glyphs())) {
          do_render(ctx, indices, this.glyph);
        } else {
          selected_mask = (function() {
            var _i, _len, _ref1, _results;
            _ref1 = this.all_indices;
            _results = [];
            for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
              i = _ref1[_i];
              _results.push(false);
            }
            return _results;
          }).call(this);
          for (_i = 0, _len = selected_indices.length; _i < _len; _i++) {
            idx = selected_indices[_i];
            selected_mask[idx] = true;
          }
          selected = new Array();
          nonselected = new Array();
          for (_j = 0, _len1 = indices.length; _j < _len1; _j++) {
            i = indices[_j];
            if (selected_mask[i]) {
              selected.push(i);
            } else {
              nonselected.push(i);
            }
          }
          do_render(ctx, selected, this.selection_glyph);
          do_render(ctx, nonselected, this.nonselection_glyph);
        }
        dt = Date.now() - t0;
        logger.trace("" + this.glyph.model.type + " glyph (" + this.glyph.model.id + "): do_render calls finished in " + dt + "ms");
        this.have_new_data = false;
        return ctx.restore();
      };

      GlyphRendererView.prototype.xrange = function() {
        return this.plot_view.x_range;
      };

      GlyphRendererView.prototype.yrange = function() {
        return this.plot_view.y_range;
      };

      GlyphRendererView.prototype.map_to_screen = function(x, x_units, y, y_units) {
        return this.plot_view.map_to_screen(x, x_units, y, y_units, 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(_super) {
      __extends(GlyphRenderer, _super);

      function GlyphRenderer() {
        _ref1 = GlyphRenderer.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      GlyphRenderer.prototype.default_view = GlyphRendererView;

      GlyphRenderer.prototype.type = 'GlyphRenderer';

      GlyphRenderer.prototype.selection_defaults = {};

      GlyphRenderer.prototype.nonselection_defaults = {
        fill_alpha: 0.1,
        line_alpha: 0.1
      };

      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);
    GlyphRenderers = (function(_super) {
      __extends(GlyphRenderers, _super);

      function GlyphRenderers() {
        _ref2 = GlyphRenderers.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      GlyphRenderers.prototype.model = GlyphRenderer;

      return GlyphRenderers;

    })(Collection);
    return {
      Model: GlyphRenderer,
      View: GlyphRendererView,
      Collection: new GlyphRenderers()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=glyph_renderer.js.map
*/;
/*
 (c) 2013, Vladimir Agafonkin
 RBush, a JavaScript library for high-performance 2D spatial indexing of points and rectangles.
 https://github.com/mourner/rbush
*/

(function () { 

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

    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, level, height) {

        var N = right - left + 1,
            M = this._maxEntries,
            node;

        if (N <= M) {
            node = {
                children: items.slice(left, right + 1),
                height: 1,
                bbox: null,
                leaf: true
            };
            calcBBox(node, this.toBBox);
            return node;
        }

        if (!level) {
            // 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
        };

        var N2 = Math.ceil(N / M),
            N1 = N2 * Math.ceil(Math.sqrt(M)),
            i, j, right2, childNode;

        // split the items into M mostly square tiles
        for (i = left; i <= right; i += N1) {

            if (i + N1 <= right) partitionSort(items, i, right, i + N1, this.compareMinX);
            right2 = Math.min(i + N1 - 1, right);

            for (j = i; j <= right2; j += N2) {

                if (j + N2 <= right2) partitionSort(items, j, right2, j + N2, this.compareMinY);

                // pack each entry recursively
                childNode = this._build(items, j, Math.min(j + N2 - 1, right2), level + 1, height - 1);
                node.children.push(childNode);
            }
        }

        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 newNode = {
            children: node.children.splice(this._chooseSplitIndex(node, m, M)),
            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];
}


function partitionSort(arr, left, right, k, compare) {
    var pivot;

    while (true) {
        pivot = Math.floor((left + right) / 2);
        pivot = partition(arr, left, right, pivot, compare);

        if (k === pivot) break;
        else if (k < pivot) right = pivot - 1;
        else left = pivot + 1;
    }

    partition(arr, left, right, k, compare);
}

function partition(arr, left, right, pivot, compare) {
    var k = left,
        value = arr[pivot];

    swap(arr, pivot, right);

    for (var i = left; i < right; i++) {
        if (compare(arr[i], value) < 0) {
            swap(arr, k, i);
            k++;
        }
    }
    swap(arr, right, k);

    return k;
}

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;

})();
(function() {
  define('common/mathutils',[], function() {
    var angle_between, angle_dist, angle_norm;
    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);
      }
    };
    return {
      "angle_norm": angle_norm,
      "angle_dist": angle_dist,
      "angle_between": angle_between
    };
  });

}).call(this);

/*
//@ sourceMappingURL=mathutils.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
    __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; };

  define('renderer/glyph/glyph',["underscore", "common/logging", "common/has_parent", "common/collection", "common/continuum_view", "renderer/properties"], function(_, Logging, HasParent, Collection, ContinuumView, properties) {
    var Glyph, GlyphView, Glyphs, logger, _ref, _ref1, _ref2;
    logger = Logging.logger;
    GlyphView = (function(_super) {
      __extends(GlyphView, _super);

      function GlyphView() {
        _ref = GlyphView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      GlyphView.prototype.initialize = function(options) {
        GlyphView.__super__.initialize.call(this, options);
        this.renderer = options.renderer;
        this.glyph = new properties.Glyph(this, this._fields);
        this.props = {};
        if (__indexOf.call(this._properties, 'line') >= 0) {
          this.props.line = new properties.Line(this);
        }
        if (__indexOf.call(this._properties, 'fill') >= 0) {
          this.props.fill = new properties.Fill(this);
        }
        if (__indexOf.call(this._properties, 'text') >= 0) {
          return this.props.text = new properties.Text(this);
        }
      };

      GlyphView.prototype.render = function(ctx, indicies) {
        if (this.mget("visible")) {
          return this._render(ctx, indicies);
        }
      };

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

      GlyphView.prototype.update_data = function(source) {
        if ((this.props.fill != null) && this.props.fill.do_fill) {
          this.props.fill.set_prop_cache(source);
        }
        if ((this.props.line != null) && this.props.line.do_stroke) {
          this.props.line.set_prop_cache(source);
        }
        if (this.props.text != null) {
          return this.props.text.set_prop_cache(source);
        }
      };

      GlyphView.prototype.set_data = function(source) {
        var dir, field, i, junk, values, x, _i, _j, _k, _len, _ref1, _ref2, _ref3, _ref4, _results;
        _ref1 = this._fields;
        for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
          field = _ref1[_i];
          if (field.indexOf(":") > -1) {
            _ref2 = field.split(":"), field = _ref2[0], junk = _ref2[1];
          }
          this[field] = this.glyph.source_v_select(field, source);
          if (field === "direction") {
            values = new Uint8Array(this.direction.length);
            for (i = _j = 0, _ref3 = this.direction.length; 0 <= _ref3 ? _j < _ref3 : _j > _ref3; i = 0 <= _ref3 ? ++_j : --_j) {
              dir = this.direction[i];
              if (dir === 'clock') {
                values[i] = false;
              } else if (dir === 'anticlock') {
                values[i] = true;
              } else {
                values = NaN;
              }
            }
            this.direction = values;
          }
          if (field.indexOf("angle") > -1) {
            this[field] = (function() {
              var _k, _len1, _ref4, _results;
              _ref4 = this[field];
              _results = [];
              for (_k = 0, _len1 = _ref4.length; _k < _len1; _k++) {
                x = _ref4[_k];
                _results.push(-x);
              }
              return _results;
            }).call(this);
          }
        }
        this._set_data();
        return (function() {
          _results = [];
          for (var _k = 0, _ref4 = this[field].length; 0 <= _ref4 ? _k < _ref4 : _k > _ref4; 0 <= _ref4 ? _k++ : _k--){ _results.push(_k); }
          return _results;
        }).apply(this);
      };

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

      GlyphView.prototype.distance_vector = function(pt, span_prop_name, position, dilate) {
        var d, halfspan, i, local_select, mapper, pt0, pt1, pt_units, ptc, source, span, span_units, spt0, spt1,
          _this = this;
        if (dilate == null) {
          dilate = false;
        }
        " returns an array ";
        pt_units = this.glyph[pt].units;
        span_units = this.glyph[span_prop_name].units;
        if (pt === 'x') {
          mapper = this.renderer.xmapper;
        } else if (pt === 'y') {
          mapper = this.renderer.ymapper;
        }
        source = this.renderer.mget('data_source');
        local_select = function(prop_name) {
          return _this.glyph.source_v_select(prop_name, source);
        };
        span = local_select(span_prop_name);
        if (span_units === 'screen') {
          return span;
        }
        if (position === 'center') {
          halfspan = (function() {
            var _i, _len, _results;
            _results = [];
            for (_i = 0, _len = span.length; _i < _len; _i++) {
              d = span[_i];
              _results.push(d / 2);
            }
            return _results;
          })();
          ptc = local_select(pt);
          if (pt_units === 'screen') {
            ptc = mapper.v_map_from_target(ptc);
          }
          if (typeof ptc[0] === 'string') {
            ptc = mapper.v_map_to_target(ptc);
          }
          pt0 = (function() {
            var _i, _ref1, _results;
            _results = [];
            for (i = _i = 0, _ref1 = ptc.length; 0 <= _ref1 ? _i < _ref1 : _i > _ref1; i = 0 <= _ref1 ? ++_i : --_i) {
              _results.push(ptc[i] - halfspan[i]);
            }
            return _results;
          })();
          pt1 = (function() {
            var _i, _ref1, _results;
            _results = [];
            for (i = _i = 0, _ref1 = ptc.length; 0 <= _ref1 ? _i < _ref1 : _i > _ref1; i = 0 <= _ref1 ? ++_i : --_i) {
              _results.push(ptc[i] + halfspan[i]);
            }
            return _results;
          })();
        } else {
          pt0 = local_select(pt);
          if (pt_units === 'screen') {
            pt0 = mapper.v_map_from_target(pt0);
          }
          pt1 = (function() {
            var _i, _ref1, _results;
            _results = [];
            for (i = _i = 0, _ref1 = pt0.length; 0 <= _ref1 ? _i < _ref1 : _i > _ref1; i = 0 <= _ref1 ? ++_i : --_i) {
              _results.push(pt0[i] + span[i]);
            }
            return _results;
          })();
        }
        spt0 = mapper.v_map_to_target(pt0);
        spt1 = mapper.v_map_to_target(pt1);
        if (dilate) {
          return (function() {
            var _i, _ref1, _results;
            _results = [];
            for (i = _i = 0, _ref1 = spt0.length; 0 <= _ref1 ? _i < _ref1 : _i > _ref1; i = 0 <= _ref1 ? ++_i : --_i) {
              _results.push(Math.ceil(Math.abs(spt1[i] - spt0[i])));
            }
            return _results;
          })();
        } else {
          return (function() {
            var _i, _ref1, _results;
            _results = [];
            for (i = _i = 0, _ref1 = spt0.length; 0 <= _ref1 ? _i < _ref1 : _i > _ref1; i = 0 <= _ref1 ? ++_i : --_i) {
              _results.push(Math.abs(spt1[i] - spt0[i]));
            }
            return _results;
          })();
        }
      };

      GlyphView.prototype.hit_test = function(geometry) {
        var result, type;
        result = null;
        if (geometry.type === "point") {
          if (this._hit_point != null) {
            result = this._hit_point(geometry);
          } else if (this._point_hit_warned == null) {
            type = this.model.type;
            logger.warn("'point' selection not available on " + type + " renderer");
            this._point_hit_warned = true;
          }
        } else if (geometry.type === "rect") {
          if (this._hit_rect != null) {
            result = this._hit_rect(geometry);
          } else if (this._rect_hit_warned == null) {
            type = this.model.type;
            logger.warn("'rect' selection not available on " + type + " renderer");
            this._rect_hit_warned = true;
          }
        } else if (geometry.type === "poly") {
          if (this._hit_poly != null) {
            result = this._hit_poly(geometry);
          } else if (this._poly_hit_warned == null) {
            type = this.model.type;
            logger.warn("'poly' selection not available on " + type + " renderer");
            this._poly_hit_warned = true;
          }
        } else {
          logger.error("unrecognized selection geometry type '" + geometry.type + "'");
        }
        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 reference_point, _ref1;
        reference_point = (_ref1 = this.get_reference_point()) != null ? _ref1 : 0;
        ctx.save();
        ctx.beginPath();
        ctx.moveTo(x0, (y0 + y1) / 2);
        ctx.lineTo(x1, (y0 + y1) / 2);
        if (this.props.line.do_stroke) {
          this.props.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, reference_point, sx0, sx1, sy0, sy1, w, _ref1;
        reference_point = (_ref1 = this.get_reference_point()) != null ? _ref1 : 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.props.fill.do_fill) {
          this.props.fill.set_vectorize(ctx, reference_point);
          ctx.fillRect(sx0, sy0, sx1 - sx0, sy1 - sy0);
        }
        if (this.props.line.do_stroke) {
          ctx.beginPath();
          ctx.rect(sx0, sy0, sx1 - sx0, sy1 - sy0);
          this.props.line.set_vectorize(ctx, reference_point);
          return ctx.stroke();
        }
      };

      return GlyphView;

    })(ContinuumView);
    Glyph = (function(_super) {
      __extends(Glyph, _super);

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

      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.defaults = function() {
        return _.extend({
          visible: true
        });
      };

      return Glyph;

    })(HasParent);
    Glyphs = (function(_super) {
      __extends(Glyphs, _super);

      function Glyphs() {
        _ref2 = Glyphs.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      return Glyphs;

    })(Collection);
    return {
      Model: Glyph,
      View: GlyphView,
      Collection: Glyphs
    };
  });

}).call(this);

/*
//@ sourceMappingURL=glyph.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/annular_wedge',["underscore", "rbush", "common/mathutils", "renderer/properties", "./glyph"], function(_, rbush, mathutils, Properties, Glyph) {
    var AnnularWedge, AnnularWedgeView, AnnularWedges, _ref, _ref1, _ref2;
    AnnularWedgeView = (function(_super) {
      __extends(AnnularWedgeView, _super);

      function AnnularWedgeView() {
        _ref = AnnularWedgeView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      AnnularWedgeView.prototype._fields = ['x', 'y', 'inner_radius', 'outer_radius', 'start_angle', 'end_angle', 'direction:string'];

      AnnularWedgeView.prototype._properties = ['line', 'fill'];

      AnnularWedgeView.prototype._set_data = function() {
        var i, pts, _i, _ref1;
        this.max_radius = _.max(this.outer_radius);
        this.index = rbush();
        pts = [];
        for (i = _i = 0, _ref1 = this.x.length; 0 <= _ref1 ? _i < _ref1 : _i > _ref1; i = 0 <= _ref1 ? ++_i : --_i) {
          if (!isNaN(this.x[i] + this.y[i])) {
            pts.push([
              this.x[i], this.y[i], this.x[i], this.y[i], {
                'i': i
              }
            ]);
          }
        }
        return this.index.load(pts);
      };

      AnnularWedgeView.prototype._map_data = function() {
        var i, _i, _ref1, _ref2, _results;
        _ref1 = this.renderer.map_to_screen(this.x, this.glyph.x.units, this.y, this.glyph.y.units), this.sx = _ref1[0], this.sy = _ref1[1];
        this.inner_radius = this.distance_vector('x', 'inner_radius', 'edge');
        this.outer_radius = this.distance_vector('x', 'outer_radius', 'edge');
        this.angle = new Float32Array(this.start_angle.length);
        _results = [];
        for (i = _i = 0, _ref2 = this.start_angle.length; 0 <= _ref2 ? _i < _ref2 : _i > _ref2; i = 0 <= _ref2 ? ++_i : --_i) {
          _results.push(this.angle[i] = this.end_angle[i] - this.start_angle[i]);
        }
        return _results;
      };

      AnnularWedgeView.prototype._render = function(ctx, indices, sx, sy, inner_radius, outer_radius) {
        var i, _i, _len, _results;
        if (sx == null) {
          sx = this.sx;
        }
        if (sy == null) {
          sy = this.sy;
        }
        if (inner_radius == null) {
          inner_radius = this.inner_radius;
        }
        if (outer_radius == null) {
          outer_radius = this.outer_radius;
        }
        _results = [];
        for (_i = 0, _len = indices.length; _i < _len; _i++) {
          i = indices[_i];
          if (isNaN(sx[i] + sy[i] + inner_radius[i] + outer_radius[i] + this.start_angle[i] + this.angle[i])) {
            continue;
          }
          ctx.translate(sx[i], sy[i]);
          ctx.rotate(this.start_angle[i]);
          ctx.moveTo(outer_radius[i], 0);
          ctx.beginPath();
          ctx.arc(0, 0, outer_radius[i], 0, this.angle[i], this.direction[i]);
          ctx.rotate(this.angle[i]);
          ctx.lineTo(inner_radius[i], 0);
          ctx.arc(0, 0, inner_radius[i], 0, -this.angle[i], !this.direction[i]);
          ctx.closePath();
          ctx.rotate(-this.angle[i] - this.start_angle[i]);
          ctx.translate(-sx[i], -sy[i]);
          if (this.props.fill.do_fill) {
            this.props.fill.set_vectorize(ctx, i);
            ctx.fill();
          }
          if (this.props.line.do_stroke) {
            this.props.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, candidates2, candidates3, dist, hits, i, pt, r2, sx, sx0, sx1, sy, sy0, sy1, vx, vx0, vx1, vy, vy0, vy1, x, x0, x1, y, y0, y1, _i, _j, _k, _l, _len, _len1, _len2, _len3, _len4, _m, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6;
        _ref1 = [geometry.vx, geometry.vy], vx = _ref1[0], vy = _ref1[1];
        x = this.renderer.xmapper.map_from_target(vx);
        y = this.renderer.ymapper.map_from_target(vy);
        if (this.outer_radius_units === "screen") {
          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];
          vy0 = vy - this.max_radius;
          vy1 = vy + this.max_radius;
          _ref3 = this.renderer.ymapper.v_map_from_target([vy0, vy1]), y0 = _ref3[0], y1 = _ref3[1];
        } else {
          x0 = x - this.max_radius;
          x1 = x + this.max_radius;
          y0 = y - this.max_radius;
          y1 = y + this.max_radius;
        }
        candidates = (function() {
          var _i, _len, _ref4, _results;
          _ref4 = this.index.search([x0, y0, x1, y1]);
          _results = [];
          for (_i = 0, _len = _ref4.length; _i < _len; _i++) {
            pt = _ref4[_i];
            _results.push(pt[4].i);
          }
          return _results;
        }).call(this);
        candidates2 = [];
        if (this.outer_radius_units === "screen") {
          sx = this.renderer.plot_view.canvas.vx_to_sx(vx);
          sy = this.renderer.plot_view.canvas.vy_to_sy(vy);
          for (_i = 0, _len = candidates.length; _i < _len; _i++) {
            i = candidates[_i];
            r2 = Math.pow(this.outer_radius[i], 2);
            dist = Math.pow(this.sx[i] - sx, 2) + Math.pow(this.sy[i] - sy, 2);
            if (dist <= r2) {
              candidates2.push([i, dist]);
            }
          }
        } else {
          for (_j = 0, _len1 = candidates.length; _j < _len1; _j++) {
            i = candidates[_j];
            r2 = Math.pow(this.outer_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 <= r2) {
              candidates2.push([i, dist]);
            }
          }
        }
        candidates3 = [];
        if (this.inner_radius_units === "screen") {
          sx = this.renderer.plot_view.canvas.vx_to_sx(vx);
          sy = this.renderer.plot_view.canvas.vy_to_sy(vy);
          for (_k = 0, _len2 = candidates2.length; _k < _len2; _k++) {
            _ref4 = candidates2[_k], i = _ref4[0], dist = _ref4[1];
            r2 = Math.pow(this.inner_radius[i], 2);
            if (dist >= r2) {
              candidates3.push([i, dist]);
            }
          }
        } else {
          for (_l = 0, _len3 = candidates2.length; _l < _len3; _l++) {
            _ref5 = candidates2[_l], i = _ref5[0], dist = _ref5[1];
            r2 = Math.pow(this.inner_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]);
            if (dist >= r2) {
              candidates3.push([i, dist]);
            }
          }
        }
        hits = [];
        for (_m = 0, _len4 = candidates3.length; _m < _len4; _m++) {
          _ref6 = candidates3[_m], i = _ref6[0], dist = _ref6[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]);
          }
        }
        hits = _.chain(hits).sortBy(function(elt) {
          return elt[1];
        }).map(function(elt) {
          return elt[0];
        }).value();
        return hits;
      };

      AnnularWedgeView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
        var indices, inner_radius, outer_radius, r, reference_point, sx, sy, _ref1;
        reference_point = (_ref1 = this.get_reference_point()) != null ? _ref1 : 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;
        inner_radius = {};
        inner_radius[reference_point] = r * 0.25;
        outer_radius = {};
        outer_radius[reference_point] = r * 0.8;
        return this._render(ctx, indices, sx, sy, inner_radius, outer_radius);
      };

      return AnnularWedgeView;

    })(Glyph.View);
    AnnularWedge = (function(_super) {
      __extends(AnnularWedge, _super);

      function AnnularWedge() {
        _ref1 = AnnularWedge.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      AnnularWedge.prototype.default_view = AnnularWedgeView;

      AnnularWedge.prototype.type = 'AnnularWedge';

      AnnularWedge.prototype.display_defaults = function() {
        return _.extend({}, AnnularWedge.__super__.display_defaults.call(this), this.line_defaults, this.fill_defaults, {
          direction: 'anticlock'
        });
      };

      return AnnularWedge;

    })(Glyph.Model);
    AnnularWedges = (function(_super) {
      __extends(AnnularWedges, _super);

      function AnnularWedges() {
        _ref2 = AnnularWedges.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      AnnularWedges.prototype.model = AnnularWedge;

      return AnnularWedges;

    })(Glyph.Collection);
    return {
      Model: AnnularWedge,
      View: AnnularWedgeView,
      Collection: new AnnularWedges()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=annular_wedge.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/annulus',["underscore", "rbush", "renderer/properties", "./glyph"], function(_, rbush, Properties, Glyph) {
    var Annulus, AnnulusView, Annuluses, _ref, _ref1, _ref2;
    AnnulusView = (function(_super) {
      __extends(AnnulusView, _super);

      function AnnulusView() {
        _ref = AnnulusView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      AnnulusView.prototype._fields = ['x', 'y', 'inner_radius', 'outer_radius'];

      AnnulusView.prototype._properties = ['line', 'fill'];

      AnnulusView.prototype._set_data = function() {
        var i, pts, _i, _ref1;
        this.max_radius = _.max(this.outer_radius);
        this.index = rbush();
        pts = [];
        for (i = _i = 0, _ref1 = this.x.length; 0 <= _ref1 ? _i < _ref1 : _i > _ref1; i = 0 <= _ref1 ? ++_i : --_i) {
          if (!isNaN(this.x[i] + this.y[i])) {
            pts.push([
              this.x[i], this.y[i], this.x[i], this.y[i], {
                'i': i
              }
            ]);
          }
        }
        return this.index.load(pts);
      };

      AnnulusView.prototype._map_data = function() {
        var _ref1;
        _ref1 = this.renderer.map_to_screen(this.x, this.glyph.x.units, this.y, this.glyph.y.units), this.sx = _ref1[0], this.sy = _ref1[1];
        this.inner_radius = this.distance_vector('x', 'inner_radius', 'edge');
        return this.outer_radius = this.distance_vector('x', 'outer_radius', 'edge');
      };

      AnnulusView.prototype._render = function(ctx, indices, sx, sy, inner_radius, outer_radius) {
        var i, _i, _len, _results;
        if (sx == null) {
          sx = this.sx;
        }
        if (sy == null) {
          sy = this.sy;
        }
        if (inner_radius == null) {
          inner_radius = this.inner_radius;
        }
        if (outer_radius == null) {
          outer_radius = this.outer_radius;
        }
        _results = [];
        for (_i = 0, _len = indices.length; _i < _len; _i++) {
          i = indices[_i];
          if (isNaN(sx[i] + sy[i] + inner_radius[i] + outer_radius[i])) {
            continue;
          }
          ctx.beginPath();
          ctx.arc(sx[i], sy[i], inner_radius[i], 0, 2 * Math.PI * 2, false);
          ctx.moveTo(sx[i] + outer_radius[i], sy[i]);
          ctx.arc(sx[i], sy[i], outer_radius[i], 0, 2 * Math.PI * 2, true);
          if (this.props.fill.do_fill) {
            this.props.fill.set_vectorize(ctx, i);
            ctx.fill();
          }
          if (this.props.line.do_stroke) {
            this.props.line.set_vectorize(ctx, i);
            _results.push(ctx.stroke());
          } else {
            _results.push(void 0);
          }
        }
        return _results;
      };

      AnnulusView.prototype._hit_point = function(geometry) {
        var candidates, candidates2, dist, hits, i, pt, r2, sx, sx0, sx1, sy, sy0, sy1, vx, vx0, vx1, vy, vy0, vy1, x, x0, x1, y, y0, y1, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref1, _ref2, _ref3, _ref4, _ref5;
        _ref1 = [geometry.vx, geometry.vy], vx = _ref1[0], vy = _ref1[1];
        x = this.renderer.xmapper.map_from_target(vx);
        y = this.renderer.ymapper.map_from_target(vy);
        if (this.outer_radius_units === "screen") {
          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];
          vy0 = vy - this.max_radius;
          vy1 = vy + this.max_radius;
          _ref3 = this.renderer.ymapper.v_map_from_target([vy0, vy1]), y0 = _ref3[0], y1 = _ref3[1];
        } else {
          x0 = x - this.max_radius;
          x1 = x + this.max_radius;
          y0 = y - this.max_radius;
          y1 = y + this.max_radius;
        }
        candidates = (function() {
          var _i, _len, _ref4, _results;
          _ref4 = this.index.search([x0, y0, x1, y1]);
          _results = [];
          for (_i = 0, _len = _ref4.length; _i < _len; _i++) {
            pt = _ref4[_i];
            _results.push(pt[4].i);
          }
          return _results;
        }).call(this);
        candidates2 = [];
        if (this.outer_radius_units === "screen") {
          sx = this.renderer.plot_view.canvas.vx_to_sx(vx);
          sy = this.renderer.plot_view.canvas.vy_to_sy(vy);
          for (_i = 0, _len = candidates.length; _i < _len; _i++) {
            i = candidates[_i];
            r2 = Math.pow(this.outer_radius[i], 2);
            dist = Math.pow(this.sx[i] - sx, 2) + Math.pow(this.sy[i] - sy, 2);
            if (dist <= r2) {
              candidates2.push([i, dist]);
            }
          }
        } else {
          for (_j = 0, _len1 = candidates.length; _j < _len1; _j++) {
            i = candidates[_j];
            r2 = Math.pow(this.outer_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 <= r2) {
              candidates2.push([i, dist]);
            }
          }
        }
        hits = [];
        if (this.inner_radius_units === "screen") {
          sx = this.renderer.plot_view.canvas.vx_to_sx(vx);
          sy = this.renderer.plot_view.canvas.vy_to_sy(vy);
          for (_k = 0, _len2 = candidates2.length; _k < _len2; _k++) {
            _ref4 = candidates2[_k], i = _ref4[0], dist = _ref4[1];
            r2 = Math.pow(this.inner_radius[i], 2);
            if (dist >= r2) {
              hits.push([i, dist]);
            }
          }
        } else {
          for (_l = 0, _len3 = candidates2.length; _l < _len3; _l++) {
            _ref5 = candidates2[_l], i = _ref5[0], dist = _ref5[1];
            r2 = Math.pow(this.inner_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]);
            if (dist >= r2) {
              hits.push([i, dist]);
            }
          }
        }
        hits = _.chain(hits).sortBy(function(elt) {
          return elt[1];
        }).map(function(elt) {
          return elt[0];
        }).value();
        return hits;
      };

      AnnulusView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
        var indices, inner_radius, outer_radius, r, reference_point, sx, sy, _ref1;
        reference_point = (_ref1 = this.get_reference_point()) != null ? _ref1 : 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;
        inner_radius = {};
        inner_radius[reference_point] = r * 0.4;
        outer_radius = {};
        outer_radius[reference_point] = r * 0.8;
        return this._render(ctx, indices, sx, sy, inner_radius, outer_radius);
      };

      return AnnulusView;

    })(Glyph.View);
    Annulus = (function(_super) {
      __extends(Annulus, _super);

      function Annulus() {
        _ref1 = Annulus.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Annulus.prototype.default_view = AnnulusView;

      Annulus.prototype.type = 'Annulus';

      Annulus.prototype.display_defaults = function() {
        return _.extend({}, Annulus.__super__.display_defaults.call(this), this.line_defaults, this.fill_defaults);
      };

      return Annulus;

    })(Glyph.Model);
    Annuluses = (function(_super) {
      __extends(Annuluses, _super);

      function Annuluses() {
        _ref2 = Annuluses.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Annuluses.prototype.model = Annulus;

      return Annuluses;

    })(Glyph.Collection);
    return {
      Model: Annulus,
      View: AnnulusView,
      Collection: new Annuluses()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=annulus.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/arc',["underscore", "renderer/properties", "./glyph"], function(_, Properties, Glyph) {
    var Arc, ArcView, Arcs, _ref, _ref1, _ref2;
    ArcView = (function(_super) {
      __extends(ArcView, _super);

      function ArcView() {
        _ref = ArcView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      ArcView.prototype._fields = ['x', 'y', 'radius', 'start_angle', 'end_angle', 'direction:string'];

      ArcView.prototype._properties = ['line'];

      ArcView.prototype._map_data = function() {
        var _ref1;
        _ref1 = this.renderer.map_to_screen(this.x, this.glyph.x.units, this.y, this.glyph.y.units), this.sx = _ref1[0], this.sy = _ref1[1];
        return this.radius = this.distance_vector('x', 'radius', 'edge');
      };

      ArcView.prototype._render = function(ctx, indices, sx, sy, radius) {
        var i, _i, _len, _results;
        if (sx == null) {
          sx = this.sx;
        }
        if (sy == null) {
          sy = this.sy;
        }
        if (radius == null) {
          radius = this.radius;
        }
        if (this.props.line.do_stroke) {
          _results = [];
          for (_i = 0, _len = indices.length; _i < _len; _i++) {
            i = indices[_i];
            if (isNaN(sx[i] + sy[i] + radius[i] + this.start_angle[i] + this.end_angle[i] + this.direction[i])) {
              continue;
            }
            ctx.beginPath();
            ctx.arc(sx[i], sy[i], radius[i], this.start_angle[i], this.end_angle[i], this.direction[i]);
            this.props.line.set_vectorize(ctx, i);
            _results.push(ctx.stroke());
          }
          return _results;
        }
      };

      ArcView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
        var indices, radius, reference_point, sx, sy, _ref1;
        reference_point = (_ref1 = this.get_reference_point()) != null ? _ref1 : 0;
        indices = [reference_point];
        sx = {};
        sx[reference_point] = (x0 + x1) / 2;
        sy = {};
        sy[reference_point] = (y0 + y1) / 2;
        radius = {};
        radius[reference_point] = Math.min(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 0.4;
        return this._render(ctx, indices, sx, sy, radius);
      };

      return ArcView;

    })(Glyph.View);
    Arc = (function(_super) {
      __extends(Arc, _super);

      function Arc() {
        _ref1 = Arc.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Arc.prototype.default_view = ArcView;

      Arc.prototype.type = 'Arc';

      Arc.prototype.display_defaults = function() {
        return _.extend({}, Arc.__super__.display_defaults.call(this), this.line_defaults, {
          direction: 'anticlock'
        });
      };

      return Arc;

    })(Glyph.Model);
    Arcs = (function(_super) {
      __extends(Arcs, _super);

      function Arcs() {
        _ref2 = Arcs.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Arcs.prototype.model = Arc;

      return Arcs;

    })(Glyph.Collection);
    return {
      Model: Arc,
      View: ArcView,
      Collection: new Arcs()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=arc.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/bezier',["underscore", "renderer/properties", "./glyph"], function(_, Properties, Glyph) {
    var Bezier, BezierView, Beziers, _ref, _ref1, _ref2;
    BezierView = (function(_super) {
      __extends(BezierView, _super);

      function BezierView() {
        _ref = BezierView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      BezierView.prototype._fields = ['x0', 'y0', 'x1', 'y1', 'cx0', 'cy0', 'cx1', 'cy1'];

      BezierView.prototype._properties = ['line'];

      BezierView.prototype._map_data = function() {
        var _ref1, _ref2, _ref3, _ref4;
        _ref1 = this.renderer.map_to_screen(this.x0, this.glyph.x0.units, this.y0, this.glyph.y0.units), this.sx0 = _ref1[0], this.sy0 = _ref1[1];
        _ref2 = this.renderer.map_to_screen(this.x1, this.glyph.x1.units, this.y1, this.glyph.y1.units), this.sx1 = _ref2[0], this.sy1 = _ref2[1];
        _ref3 = this.renderer.map_to_screen(this.cx0, this.glyph.cx0.units, this.cy0, this.glyph.cy0.units), this.scx0 = _ref3[0], this.scy0 = _ref3[1];
        return _ref4 = this.renderer.map_to_screen(this.cx1, this.glyph.cx1.units, this.cy1, this.glyph.cy1.units), this.scx1 = _ref4[0], this.scy1 = _ref4[1], _ref4;
      };

      BezierView.prototype._render = function(ctx, indices) {
        var i, _i, _len, _results;
        if (this.props.line.do_stroke) {
          _results = [];
          for (_i = 0, _len = indices.length; _i < _len; _i++) {
            i = indices[_i];
            if (isNaN(this.sx0[i] + this.sy0[i] + this.sx1[i] + this.sy1[i] + this.scx0[i] + this.scy0[i] + this.scx1[i] + this.scy1[i])) {
              continue;
            }
            ctx.beginPath();
            ctx.moveTo(this.sx0[i], this.sy0[i]);
            ctx.bezierCurveTo(this.scx0[i], this.scy0[i], this.scx1[i], this.scy1[i], this.sx1[i], this.sy1[i]);
            this.props.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(_super) {
      __extends(Bezier, _super);

      function Bezier() {
        _ref1 = Bezier.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Bezier.prototype.default_view = BezierView;

      Bezier.prototype.type = 'Bezier';

      Bezier.prototype.display_defaults = function() {
        return _.extend({}, Bezier.__super__.display_defaults.call(this), this.line_defaults);
      };

      return Bezier;

    })(Glyph.Model);
    Beziers = (function(_super) {
      __extends(Beziers, _super);

      function Beziers() {
        _ref2 = Beziers.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Beziers.prototype.model = Bezier;

      return Beziers;

    })(Glyph.Collection);
    return {
      Model: Bezier,
      View: BezierView,
      Collection: new Beziers()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=bezier.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/circle',["underscore", "rbush", "renderer/properties", "./glyph"], function(_, rbush, Properties, Glyph) {
    var Circle, CircleView, Circles, point_in_poly, _ref, _ref1, _ref2;
    point_in_poly = function(x, y, px, py) {
      var i, inside, x1, x2, y1, y2, _i, _ref;
      inside = false;
      x1 = px[px.length - 1];
      y1 = py[py.length - 1];
      for (i = _i = 0, _ref = px.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
        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;
    };
    CircleView = (function(_super) {
      __extends(CircleView, _super);

      function CircleView() {
        _ref = CircleView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      CircleView.prototype._properties = ['line', 'fill'];

      CircleView.prototype.initialize = function(options) {
        if (this.mget("radius") != null) {
          this._fields = ['x', 'y', 'radius', 'radius_dimension'];
        } else {
          this._fields = ['x', 'y', 'size'];
        }
        return CircleView.__super__.initialize.call(this, options);
      };

      CircleView.prototype._set_data = function() {
        var i, pts, _i, _ref1;
        if (this.size) {
          this.max_radius = _.max(this.size) / 2;
        } else {
          this.max_radius = _.max(this.radius);
        }
        this.index = rbush();
        pts = [];
        for (i = _i = 0, _ref1 = this.x.length; 0 <= _ref1 ? _i < _ref1 : _i > _ref1; i = 0 <= _ref1 ? ++_i : --_i) {
          if (!isNaN(this.x[i] + this.y[i])) {
            pts.push([
              this.x[i], this.y[i], this.x[i], this.y[i], {
                'i': i
              }
            ]);
          }
        }
        return this.index.load(pts);
      };

      CircleView.prototype._map_data = function() {
        var rd, s, _ref1;
        _ref1 = this.renderer.map_to_screen(this.x, this.glyph.x.units, this.y, this.glyph.y.units), this.sx = _ref1[0], this.sy = _ref1[1];
        if (this.size) {
          this.radius = (function() {
            var _i, _len, _ref2, _results;
            _ref2 = this.distance_vector('x', 'size', 'edge');
            _results = [];
            for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
              s = _ref2[_i];
              _results.push(s / 2);
            }
            return _results;
          }).call(this);
          return this.radius_units = this.glyph.size.units;
        } else {
          rd = this.mget('radius_dimension');
          if (rd !== 'x' && rd !== 'y') {
            rd = 'x';
          }
          return this.radius = this.distance_vector(rd, 'radius', 'edge');
        }
      };

      CircleView.prototype._mask_data = function() {
        var hr, sx0, sx1, sy0, sy1, vr, x, x0, x1, y0, y1, _ref1, _ref2, _ref3, _ref4;
        hr = this.renderer.plot_view.frame.get('h_range');
        vr = this.renderer.plot_view.frame.get('v_range');
        if (this.radius_units === "screen") {
          sx0 = hr.get('start') - this.max_radius;
          sx1 = hr.get('end') - this.max_radius;
          _ref1 = this.renderer.xmapper.v_map_from_target([sx0, sx1]), x0 = _ref1[0], x1 = _ref1[1];
          sy0 = vr.get('start') - this.max_radius;
          sy1 = vr.get('end') - this.max_radius;
          _ref2 = this.renderer.ymapper.v_map_from_target([sy0, sy1]), y0 = _ref2[0], y1 = _ref2[1];
        } else {
          sx0 = hr.get('start');
          sx1 = hr.get('end');
          _ref3 = this.renderer.xmapper.v_map_from_target([sx0, sx1]), x0 = _ref3[0], x1 = _ref3[1];
          x0 -= this.max_radius;
          x1 += this.max_radius;
          sy0 = vr.get('start');
          sy1 = vr.get('end');
          _ref4 = this.renderer.ymapper.v_map_from_target([sy0, sy1]), y0 = _ref4[0], y1 = _ref4[1];
          y0 -= this.max_radius;
          y1 += this.max_radius;
        }
        return (function() {
          var _i, _len, _ref5, _results;
          _ref5 = this.index.search([x0, y0, x1, y1]);
          _results = [];
          for (_i = 0, _len = _ref5.length; _i < _len; _i++) {
            x = _ref5[_i];
            _results.push(x[4].i);
          }
          return _results;
        }).call(this);
      };

      CircleView.prototype._render = function(ctx, indices, sx, sy, radius) {
        var i, _i, _len, _results;
        if (sx == null) {
          sx = this.sx;
        }
        if (sy == null) {
          sy = this.sy;
        }
        if (radius == null) {
          radius = this.radius;
        }
        _results = [];
        for (_i = 0, _len = indices.length; _i < _len; _i++) {
          i = indices[_i];
          if (isNaN(sx[i] + sy[i] + radius[i])) {
            continue;
          }
          ctx.beginPath();
          ctx.arc(sx[i], sy[i], radius[i], 0, 2 * Math.PI, false);
          if (this.props.fill.do_fill) {
            this.props.fill.set_vectorize(ctx, i);
            ctx.fill();
          }
          if (this.props.line.do_stroke) {
            this.props.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, pt, r2, sx, sx0, sx1, sy, sy0, sy1, vx, vx0, vx1, vy, vy0, vy1, x, x0, x1, y, y0, y1, _i, _j, _len, _len1, _ref1, _ref2, _ref3;
        _ref1 = [geometry.vx, geometry.vy], vx = _ref1[0], vy = _ref1[1];
        x = this.renderer.xmapper.map_from_target(vx);
        y = this.renderer.ymapper.map_from_target(vy);
        if (this.radius_units === "screen") {
          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];
          vy0 = vy - this.max_radius;
          vy1 = vy + this.max_radius;
          _ref3 = this.renderer.ymapper.v_map_from_target([vy0, vy1]), y0 = _ref3[0], y1 = _ref3[1];
        } else {
          x0 = x - this.max_radius;
          x1 = x + this.max_radius;
          y0 = y - this.max_radius;
          y1 = y + this.max_radius;
        }
        candidates = (function() {
          var _i, _len, _ref4, _results;
          _ref4 = this.index.search([x0, y0, x1, y1]);
          _results = [];
          for (_i = 0, _len = _ref4.length; _i < _len; _i++) {
            pt = _ref4[_i];
            _results.push(pt[4].i);
          }
          return _results;
        }).call(this);
        hits = [];
        if (this.radius_units === "screen") {
          sx = this.renderer.plot_view.canvas.vx_to_sx(vx);
          sy = this.renderer.plot_view.canvas.vy_to_sy(vy);
          for (_i = 0, _len = candidates.length; _i < _len; _i++) {
            i = candidates[_i];
            r2 = Math.pow(this.radius[i], 2);
            dist = Math.pow(this.sx[i] - sx, 2) + Math.pow(this.sy[i] - sy, 2);
            if (dist <= r2) {
              hits.push([i, dist]);
            }
          }
        } else {
          for (_j = 0, _len1 = candidates.length; _j < _len1; _j++) {
            i = candidates[_j];
            r2 = Math.pow(this.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 <= r2) {
              hits.push([i, dist]);
            }
          }
        }
        hits = _.chain(hits).sortBy(function(elt) {
          return elt[1];
        }).map(function(elt) {
          return elt[0];
        }).value();
        return hits;
      };

      CircleView.prototype._hit_rect = function(geometry) {
        var x, x0, x1, y0, y1, _ref1, _ref2;
        _ref1 = this.renderer.xmapper.v_map_from_target([geometry.vx0, geometry.vx1]), x0 = _ref1[0], x1 = _ref1[1];
        _ref2 = this.renderer.ymapper.v_map_from_target([geometry.vy0, geometry.vy1]), y0 = _ref2[0], y1 = _ref2[1];
        return (function() {
          var _i, _len, _ref3, _results;
          _ref3 = this.index.search([x0, y0, x1, y1]);
          _results = [];
          for (_i = 0, _len = _ref3.length; _i < _len; _i++) {
            x = _ref3[_i];
            _results.push(x[4].i);
          }
          return _results;
        }).call(this);
      };

      CircleView.prototype._hit_poly = function(geometry) {
        var candidates, hits, i, idx, sx, sy, vx, vy, _i, _j, _ref1, _ref2, _ref3, _results;
        _ref1 = [_.clone(geometry.vx), _.clone(geometry.vy)], vx = _ref1[0], vy = _ref1[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 _i = 0, _ref2 = this.sx.length; 0 <= _ref2 ? _i < _ref2 : _i > _ref2; 0 <= _ref2 ? _i++ : _i--){ _results.push(_i); }
          return _results;
        }).apply(this);
        hits = [];
        for (i = _j = 0, _ref3 = candidates.length; 0 <= _ref3 ? _j < _ref3 : _j > _ref3; i = 0 <= _ref3 ? ++_j : --_j) {
          idx = candidates[i];
          if (point_in_poly(this.sx[i], this.sy[i], sx, sy)) {
            hits.push(idx);
          }
        }
        return hits;
      };

      CircleView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
        var indices, radius, reference_point, sx, sy, _ref1;
        reference_point = (_ref1 = this.get_reference_point()) != null ? _ref1 : 0;
        indices = [reference_point];
        sx = {};
        sx[reference_point] = (x0 + x1) / 2;
        sy = {};
        sy[reference_point] = (y0 + y1) / 2;
        radius = {};
        radius[reference_point] = Math.min(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 0.2;
        return this._render(ctx, indices, sx, sy, radius);
      };

      return CircleView;

    })(Glyph.View);
    Circle = (function(_super) {
      __extends(Circle, _super);

      function Circle() {
        _ref1 = Circle.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Circle.prototype.default_view = CircleView;

      Circle.prototype.type = 'Circle';

      Circle.prototype.display_defaults = function() {
        return _.extend({}, Circle.__super__.display_defaults.call(this), this.line_defaults, this.fill_defaults, {
          size: 4
        });
      };

      Circle.prototype.defaults = function() {
        return _.extend({}, Circle.__super__.defaults.call(this), {
          size_units: 'screen',
          radius_units: 'data',
          radius_dimension: 'x'
        });
      };

      return Circle;

    })(Glyph.Model);
    Circles = (function(_super) {
      __extends(Circles, _super);

      function Circles() {
        _ref2 = Circles.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Circles.prototype.model = Circle;

      return Circles;

    })(Glyph.Collection);
    return {
      Model: Circle,
      View: CircleView,
      Collection: new Circles()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=circle.js.map
*/;
define('gear_utils',[],function() {
/*==========================================================================*
  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()
{
  
/* ----------------------------------------------------------
 * 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
};

}());

return { create_gear_tooth: createGearTooth, create_internal_gear_tooth: createIntGearTooth };
});

(function() {
  define('util/bezier',[], function() {
    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 _i, _results;
        _results = [];
        for (i = _i = 0; 0 <= segments ? _i < segments : _i > segments; i = 0 <= segments ? ++_i : --_i) {
          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;
    };
    return {
      arc_to_bezier: arc_to_bezier
    };
  });

}).call(this);

/*
//@ sourceMappingURL=bezier.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/gear',["underscore", "gear_utils", "renderer/properties", "util/bezier", "./glyph"], function(_, GearUtils, Properties, Bezier, Glyph) {
    var Gear, GearView, Gears, _ref, _ref1, _ref2;
    GearView = (function(_super) {
      __extends(GearView, _super);

      function GearView() {
        _ref = GearView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      GearView.prototype._fields = ['x', 'y', 'angle', 'module', 'teeth', 'pressure_angle', 'shaft_size', 'internal:boolean'];

      GearView.prototype._properties = ['line', 'fill'];

      GearView.prototype._map_data = function() {
        var _ref1;
        _ref1 = this.renderer.map_to_screen(this.x, this.glyph.x.units, this.y, this.glyph.y.units), this.sx = _ref1[0], this.sy = _ref1[1];
        return this.smodule = this.distance_vector('x', 'module', 'edge');
      };

      GearView.prototype._render = function(ctx, indices) {
        var M, angle, fn, i, internal, j, module, pitch_radius, pressure_angle, rim_radius, rot, seq, seq0, shaft_radius, shaft_size, sx, sy, teeth, x, y, _i, _j, _len, _ref1, _ref2;
        for (_i = 0, _len = indices.length; _i < _len; _i++) {
          i = indices[_i];
          _ref1 = [this.sx[i], this.sy[i], this.angle[i], this.smodule[i], this.teeth[i], this.pressure_angle[i], this.shaft_size[i], this.internal[i]], sx = _ref1[0], sy = _ref1[1], angle = _ref1[2], module = _ref1[3], teeth = _ref1[4], pressure_angle = _ref1[5], shaft_size = _ref1[6], internal = _ref1[7];
          if (isNaN(sx + sy + angle + module + teeth + pressure_angle + shaft_size + internal)) {
            continue;
          }
          pitch_radius = module * teeth / 2;
          if (internal) {
            fn = GearUtils.create_internal_gear_tooth;
          } else {
            fn = GearUtils.create_gear_tooth;
          }
          seq0 = fn(module, teeth, pressure_angle);
          _ref2 = seq0.slice(0, 3), M = _ref2[0], x = _ref2[1], y = _ref2[2];
          seq = seq0.slice(3);
          ctx.save();
          ctx.translate(sx, sy);
          ctx.rotate(angle);
          ctx.beginPath();
          rot = 2 * Math.PI / teeth;
          ctx.moveTo(x, y);
          for (j = _j = 0; 0 <= teeth ? _j < teeth : _j > teeth; j = 0 <= teeth ? ++_j : --_j) {
            this._render_seq(ctx, seq);
            ctx.rotate(rot);
          }
          ctx.closePath();
          if (internal) {
            rim_radius = pitch_radius + 2.75 * module;
            ctx.moveTo(rim_radius, 0);
            ctx.arc(0, 0, rim_radius, 0, 2 * Math.PI, true);
          } else if (shaft_size > 0) {
            shaft_radius = pitch_radius * shaft_size;
            ctx.moveTo(shaft_radius, 0);
            ctx.arc(0, 0, shaft_radius, 0, 2 * Math.PI, true);
          }
          if (this.props.fill.do_fill) {
            this.props.fill.set_vectorize(ctx, i);
            ctx.fill();
          }
          if (this.props.line.do_stroke) {
            this.props.line.set_vectorize(ctx, i);
            ctx.stroke();
          }
          ctx.restore();
        }
      };

      GearView.prototype._render_seq = function(ctx, seq) {
        var c, cx0, cx1, cy0, cy1, i, large_arc, px, py, rx, ry, segments, sweep, x, x_rotation, y, _i, _len, _ref1, _ref10, _ref11, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8, _ref9;
        i = 0;
        while (i < seq.length) {
          if (_.isString(seq[i])) {
            c = seq[i];
            i += 1;
          }
          switch (c) {
            case "M":
              _ref1 = seq.slice(i, i + 2), x = _ref1[0], y = _ref1[1];
              ctx.moveTo(x, y);
              _ref2 = [x, y], px = _ref2[0], py = _ref2[1];
              i += 2;
              break;
            case "L":
              _ref3 = seq.slice(i, i + 2), x = _ref3[0], y = _ref3[1];
              ctx.lineTo(x, y);
              _ref4 = [x, y], px = _ref4[0], py = _ref4[1];
              i += 2;
              break;
            case "C":
              _ref5 = seq.slice(i, i + 6), cx0 = _ref5[0], cy0 = _ref5[1], cx1 = _ref5[2], cy1 = _ref5[3], x = _ref5[4], y = _ref5[5];
              ctx.bezierCurveTo(cx0, cy0, cx1, cy1, x, y);
              _ref6 = [x, y], px = _ref6[0], py = _ref6[1];
              i += 6;
              break;
            case "Q":
              _ref7 = seq.slice(i, i + 4), cx0 = _ref7[0], cy0 = _ref7[1], x = _ref7[2], y = _ref7[3];
              ctx.quadraticCurveTo(cx0, cy0, x, y);
              _ref8 = [x, y], px = _ref8[0], py = _ref8[1];
              i += 4;
              break;
            case "A":
              _ref9 = seq.slice(i, i + 7), rx = _ref9[0], ry = _ref9[1], x_rotation = _ref9[2], large_arc = _ref9[3], sweep = _ref9[4], x = _ref9[5], y = _ref9[6];
              segments = Bezier.arc_to_bezier(px, py, rx, ry, -x_rotation, large_arc, 1 - sweep, x, y);
              for (_i = 0, _len = segments.length; _i < _len; _i++) {
                _ref10 = segments[_i], cx0 = _ref10[0], cy0 = _ref10[1], cx1 = _ref10[2], cy1 = _ref10[3], x = _ref10[4], y = _ref10[5];
                ctx.bezierCurveTo(cx0, cy0, cx1, cy1, x, y);
              }
              _ref11 = [x, y], px = _ref11[0], py = _ref11[1];
              i += 7;
              break;
            default:
              throw new Error("unexpected command: " + c);
          }
        }
      };

      GearView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
        return this._generic_line_legend(ctx, x0, x1, y0, y1);
      };

      return GearView;

    })(Glyph.View);
    Gear = (function(_super) {
      __extends(Gear, _super);

      function Gear() {
        _ref1 = Gear.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Gear.prototype.default_view = GearView;

      Gear.prototype.type = 'Gear';

      Gear.prototype.defaults = function() {
        return _.extend({}, Gear.__super__.defaults.call(this), {
          x: void 0,
          y: void 0,
          angle: 0,
          module: void 0,
          teeth: void 0,
          pressure_angle: 20,
          shaft_size: 0.3,
          internal: false
        });
      };

      Gear.prototype.display_defaults = function() {
        return _.extend({}, Gear.__super__.display_defaults.call(this), this.line_defaults, this.fill_defaults);
      };

      return Gear;

    })(Glyph.Model);
    Gears = (function(_super) {
      __extends(Gears, _super);

      function Gears() {
        _ref2 = Gears.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Gears.prototype.model = Gear;

      return Gears;

    })(Glyph.Collection);
    return {
      Model: Gear,
      View: GearView,
      Collection: new Gears()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=gear.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/image',["underscore", "renderer/properties", "mapper/linear_color_mapper", "./glyph"], function(_, Properties, LinearColorMapper, Glyph) {
    var Image, ImageView, Images, _ref, _ref1, _ref2;
    ImageView = (function(_super) {
      __extends(ImageView, _super);

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

      ImageView.prototype._properties = [];

      ImageView.prototype.initialize = function(options) {
        if (this.mget("rows") != null) {
          this._fields = ['image:array', 'rows', 'cols', 'x', 'y', 'dw', 'dh', 'palette:string'];
        } else {
          this._fields = ['image:array', 'x', 'y', 'dw', 'dh', 'palette:string'];
        }
        return ImageView.__super__.initialize.call(this, options);
      };

      ImageView.prototype._set_data = function() {
        var buf, buf8, canvas, cmap, ctx, i, image_data, img, _i, _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 = _i = 0, _ref1 = this.image.length; 0 <= _ref1 ? _i < _ref1 : _i > _ref1; i = 0 <= _ref1 ? ++_i : --_i) {
          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);
          _results.push(this.image_data[i] = canvas);
        }
        return _results;
      };

      ImageView.prototype._map_data = function() {
        var _ref1;
        _ref1 = this.renderer.map_to_screen(this.x, this.glyph.x.units, this.y, this.glyph.y.units), this.sx = _ref1[0], this.sy = _ref1[1];
        this.sw = this.distance_vector('x', 'dw', 'edge', this.mget('dilate'));
        return this.sh = this.distance_vector('y', 'dh', 'edge', this.mget('dilate'));
      };

      ImageView.prototype._render = function(ctx, indices) {
        var i, old_smoothing, y_offset, _i, _len;
        old_smoothing = ctx.getImageSmoothingEnabled();
        ctx.setImageSmoothingEnabled(false);
        for (_i = 0, _len = indices.length; _i < _len; _i++) {
          i = indices[_i];
          if (this.image_data[i] == null) {
            continue;
          }
          if (isNaN(this.sx[i] + this.sy[i] + this.sw[i] + this.sh[i])) {
            continue;
          }
          y_offset = this.sy[i];
          ctx.translate(0, y_offset);
          ctx.scale(1, -1);
          ctx.translate(0, -y_offset);
          ctx.drawImage(this.image_data[i], this.sx[i] | 0, this.sy[i] | 0, this.sw[i], this.sh[i]);
          ctx.translate(0, y_offset);
          ctx.scale(1, -1);
          ctx.translate(0, -y_offset);
        }
        return ctx.setImageSmoothingEnabled(old_smoothing);
      };

      return ImageView;

    })(Glyph.View);
    Image = (function(_super) {
      __extends(Image, _super);

      function Image() {
        _ref1 = Image.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Image.prototype.default_view = ImageView;

      Image.prototype.type = 'Image';

      Image.prototype.display_defaults = function() {
        return _.extend({}, Image.__super__.display_defaults.call(this), {
          level: 'underlay',
          dilate: false
        });
      };

      return Image;

    })(Glyph.Model);
    Images = (function(_super) {
      __extends(Images, _super);

      function Images() {
        _ref2 = Images.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Images.prototype.model = Image;

      return Images;

    })(Glyph.Collection);
    return {
      Model: Image,
      View: ImageView,
      Collection: new Images()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=image.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/image_rgba',["underscore", "renderer/properties", "./glyph"], function(_, Properties, Glyph) {
    var ImageRGBA, ImageRGBAView, ImageRGBAs, _ref, _ref1, _ref2;
    ImageRGBAView = (function(_super) {
      __extends(ImageRGBAView, _super);

      function ImageRGBAView() {
        _ref = ImageRGBAView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      ImageRGBAView.prototype._properties = [];

      ImageRGBAView.prototype.initialize = function(options) {
        if (this.mget("rows") != null) {
          this._fields = ['image:array', 'rows', 'cols', 'x', 'y', 'dw', 'dh'];
        } else {
          this._fields = ['image:array', 'x', 'y', 'dw', 'dh'];
        }
        return ImageRGBAView.__super__.initialize.call(this, options);
      };

      ImageRGBAView.prototype._set_data = function() {
        var buf, buf8, canvas, color, ctx, flat, i, image_data, j, _i, _j, _ref1, _ref2, _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 = _i = 0, _ref1 = this.image.length; 0 <= _ref1 ? _i < _ref1 : _i > _ref1; i = 0 <= _ref1 ? ++_i : --_i) {
          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 = _j = 0, _ref2 = flat.length; 0 <= _ref2 ? _j < _ref2 : _j > _ref2; j = 0 <= _ref2 ? ++_j : --_j) {
              color[j] = flat[j];
            }
            buf8 = new Uint8ClampedArray(buf);
            image_data.data.set(buf8);
          }
          ctx.putImageData(image_data, 0, 0);
          _results.push(this.image_data[i] = canvas);
        }
        return _results;
      };

      ImageRGBAView.prototype._map_data = function() {
        var _ref1;
        _ref1 = this.renderer.map_to_screen(this.x, this.glyph.x.units, this.y, this.glyph.y.units), this.sx = _ref1[0], this.sy = _ref1[1];
        this.sw = this.distance_vector('x', 'dw', 'edge', this.mget('dilate'));
        return this.sh = this.distance_vector('y', 'dh', 'edge', this.mget('dilate'));
      };

      ImageRGBAView.prototype._render = function(ctx, indices) {
        var i, old_smoothing, y_offset, _i, _len;
        old_smoothing = ctx.getImageSmoothingEnabled();
        ctx.setImageSmoothingEnabled(false);
        for (_i = 0, _len = indices.length; _i < _len; _i++) {
          i = indices[_i];
          if (isNaN(this.sx[i] + this.sy[i] + this.sw[i] + this.sh[i])) {
            continue;
          }
          y_offset = this.sy[i];
          ctx.translate(0, y_offset);
          ctx.scale(1, -1);
          ctx.translate(0, -y_offset);
          ctx.drawImage(this.image_data[i], this.sx[i] | 0, this.sy[i] | 0, this.sw[i], this.sh[i]);
          ctx.translate(0, y_offset);
          ctx.scale(1, -1);
          ctx.translate(0, -y_offset);
        }
        return ctx.setImageSmoothingEnabled(old_smoothing);
      };

      return ImageRGBAView;

    })(Glyph.View);
    ImageRGBA = (function(_super) {
      __extends(ImageRGBA, _super);

      function ImageRGBA() {
        _ref1 = ImageRGBA.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      ImageRGBA.prototype.default_view = ImageRGBAView;

      ImageRGBA.prototype.type = 'ImageRGBA';

      ImageRGBA.prototype.display_defaults = function() {
        return _.extend({}, ImageRGBA.__super__.display_defaults.call(this), {
          level: 'underlay',
          dilate: false
        });
      };

      return ImageRGBA;

    })(Glyph.Model);
    ImageRGBAs = (function(_super) {
      __extends(ImageRGBAs, _super);

      function ImageRGBAs() {
        _ref2 = ImageRGBAs.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      ImageRGBAs.prototype.model = ImageRGBA;

      return ImageRGBAs;

    })(Glyph.Collection);
    return {
      Model: ImageRGBA,
      View: ImageRGBAView,
      Collection: new ImageRGBAs()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=image_rgba.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/image_url',["underscore", "renderer/properties", "./glyph"], function(_, Properties, Glyph) {
    var ImageURL, ImageURLView, ImageURLs, _ref, _ref1, _ref2;
    ImageURLView = (function(_super) {
      __extends(ImageURLView, _super);

      function ImageURLView() {
        _ref = ImageURLView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      ImageURLView.prototype._fields = ['url:string', 'x', 'y', 'w', 'h', 'angle'];

      ImageURLView.prototype._properties = [];

      ImageURLView.prototype._set_data = function() {
        var img;
        this.image = (function() {
          var _i, _len, _ref1, _results;
          _ref1 = this.url;
          _results = [];
          for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
            img = _ref1[_i];
            _results.push(null);
          }
          return _results;
        }).call(this);
        this.need_load = (function() {
          var _i, _len, _ref1, _results;
          _ref1 = this.url;
          _results = [];
          for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
            img = _ref1[_i];
            _results.push(true);
          }
          return _results;
        }).call(this);
        return this.loaded = (function() {
          var _i, _len, _ref1, _results;
          _ref1 = this.url;
          _results = [];
          for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
            img = _ref1[_i];
            _results.push(false);
          }
          return _results;
        }).call(this);
      };

      ImageURLView.prototype._map_data = function() {
        var _ref1;
        _ref1 = this.renderer.map_to_screen(this.x, this.glyph.x.units, this.y, this.glyph.y.units), this.sx = _ref1[0], this.sy = _ref1[1];
        this.sw = this.distance_vector('x', 'w', 'edge', this.mget('dilate'));
        return this.sh = this.distance_vector('y', 'h', 'edge', this.mget('dilate'));
      };

      ImageURLView.prototype._render = function(ctx, indices) {
        var i, img, _i, _len, _results,
          _this = this;
        _results = [];
        for (_i = 0, _len = indices.length; _i < _len; _i++) {
          i = indices[_i];
          if (isNaN(this.sx[i] + this.sy[i] + this.angle[i])) {
            continue;
          }
          if (this.need_load[i]) {
            img = new Image();
            img.onload = (function(img, i) {
              return function() {
                var frame;
                _this.loaded[i] = true;
                _this.image[i] = img;
                ctx.save();
                ctx.beginPath();
                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();
                _this._render_image(ctx, i, img);
                return ctx.restore();
              };
            })(img, i);
            img.src = this.url[i];
            _results.push(this.need_load[i] = false);
          } else if (this.loaded[i]) {
            _results.push(this._render_image(ctx, i, this.image[i]));
          } else {
            _results.push(void 0);
          }
        }
        return _results;
      };

      ImageURLView.prototype._final_sx_sy = function() {
        var anchor,
          _this = this;
        anchor = this.mget('anchor') || "top_left";
        switch (anchor) {
          case "top_left":
            return function(i) {
              return [_this.sx[i], _this.sy[i]];
            };
          case "top_center":
            return function(i) {
              return [_this.sx[i] - _this.sw[i] / 2, _this.sy[i]];
            };
          case "top_right":
            return function(i) {
              return [_this.sx[i] - _this.sw[i], _this.sy[i]];
            };
          case "right_center":
            return function(i) {
              return [_this.sx[i] - _this.sw[i], _this.sy[i] - _this.sh[i] / 2];
            };
          case "bottom_right":
            return function(i) {
              return [_this.sx[i] - _this.sw[i], _this.sy[i] - _this.sh[i]];
            };
          case "bottom_center":
            return function(i) {
              return [_this.sx[i] - _this.sw[i] / 2, _this.sy[i] - _this.sh[i]];
            };
          case "bottom_left":
            return function(i) {
              return [_this.sx[i], _this.sy[i] - _this.sh[i]];
            };
          case "left_center":
            return function(i) {
              return [_this.sx[i], _this.sy[i] - _this.sh[i] / 2];
            };
          case "center":
            return function(i) {
              return [_this.sx[i] - _this.sw[i] / 2, _this.sy[i] - _this.sh[i] / 2];
            };
        }
      };

      ImageURLView.prototype._render_image = function(ctx, i, img) {
        var sx, sy, _ref1;
        if (isNaN(this.sw[i])) {
          this.sw[i] = img.width;
        }
        if (isNaN(this.sh[i])) {
          this.sh[i] = img.height;
        }
        _ref1 = this._final_sx_sy()(i), sx = _ref1[0], sy = _ref1[1];
        if (this.angle[i]) {
          ctx.translate(sx, sy);
          ctx.rotate(this.angle[i]);
          ctx.drawImage(img, 0, 0, this.sw[i], this.sh[i]);
          ctx.rotate(-this.angle[i]);
          return ctx.translate(-sx, -sy);
        } else {
          return ctx.drawImage(img, sx, sy, this.sw[i], this.sh[i]);
        }
      };

      return ImageURLView;

    })(Glyph.View);
    ImageURL = (function(_super) {
      __extends(ImageURL, _super);

      function ImageURL() {
        _ref1 = ImageURL.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      ImageURL.prototype.default_view = ImageURLView;

      ImageURL.prototype.type = 'ImageURL';

      ImageURL.prototype.defaults = function() {
        return _.extend({}, ImageURL.__super__.defaults.call(this), {
          angle: 0
        });
      };

      ImageURL.prototype.display_defaults = function() {
        return _.extend({}, ImageURL.__super__.display_defaults.call(this), {
          level: 'underlay'
        });
      };

      return ImageURL;

    })(Glyph.Model);
    ImageURLs = (function(_super) {
      __extends(ImageURLs, _super);

      function ImageURLs() {
        _ref2 = ImageURLs.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      ImageURLs.prototype.model = ImageURL;

      return ImageURLs;

    })(Glyph.Collection);
    return {
      Model: ImageURL,
      View: ImageURLView,
      Collection: new ImageURLs()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=image_url.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/line',["underscore", "renderer/properties", "./glyph"], function(_, Properties, Glyph) {
    var Line, LineView, Lines, _ref, _ref1, _ref2;
    LineView = (function(_super) {
      __extends(LineView, _super);

      function LineView() {
        _ref = LineView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      LineView.prototype._fields = ['x', 'y'];

      LineView.prototype._properties = ['line'];

      LineView.prototype._map_data = function() {
        var _ref1;
        return _ref1 = this.renderer.map_to_screen(this.x, this.glyph.x.units, this.y, this.glyph.y.units), this.sx = _ref1[0], this.sy = _ref1[1], _ref1;
      };

      LineView.prototype._render = function(ctx, indices) {
        var drawing, i, _i, _len;
        drawing = false;
        this.props.line.set(ctx, this.props);
        for (_i = 0, _len = indices.length; _i < _len; _i++) {
          i = indices[_i];
          if (isNaN(this.sx[i] + this.sy[i]) && drawing) {
            ctx.stroke();
            ctx.beginPath();
            drawing = false;
            continue;
          }
          if (drawing) {
            ctx.lineTo(this.sx[i], this.sy[i]);
          } else {
            ctx.beginPath();
            ctx.moveTo(this.sx[i], this.sy[i]);
            drawing = true;
          }
        }
        if (drawing) {
          return ctx.stroke();
        }
      };

      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(_super) {
      __extends(Line, _super);

      function Line() {
        _ref1 = Line.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Line.prototype.default_view = LineView;

      Line.prototype.type = 'Line';

      Line.prototype.display_defaults = function() {
        return _.extend({}, Line.__super__.display_defaults.call(this), this.line_defaults);
      };

      return Line;

    })(Glyph.Model);
    Lines = (function(_super) {
      __extends(Lines, _super);

      function Lines() {
        _ref2 = Lines.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Lines.prototype.model = Line;

      return Lines;

    })(Glyph.Collection);
    return {
      Model: Line,
      View: LineView,
      Collection: new Lines()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=line.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/multi_line',["underscore", "renderer/properties", "./glyph"], function(_, Properties, Glyph) {
    var MultiLine, MultiLineView, MultiLines, _ref, _ref1, _ref2;
    MultiLineView = (function(_super) {
      __extends(MultiLineView, _super);

      function MultiLineView() {
        _ref = MultiLineView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      MultiLineView.prototype._fields = ['xs', 'ys'];

      MultiLineView.prototype._properties = ['line'];

      MultiLineView.prototype._render = function(ctx, indices) {
        var i, j, sx, sy, x, y, _i, _j, _len, _ref1, _ref2, _results;
        _results = [];
        for (_i = 0, _len = indices.length; _i < _len; _i++) {
          i = indices[_i];
          x = this.xs[i];
          y = this.ys[i];
          _ref1 = this.renderer.map_to_screen(this.xs[i], this.glyph.xs.units, this.ys[i], this.glyph.ys.units), sx = _ref1[0], sy = _ref1[1];
          this.props.line.set_vectorize(ctx, i);
          for (j = _j = 0, _ref2 = sx.length; 0 <= _ref2 ? _j < _ref2 : _j > _ref2; j = 0 <= _ref2 ? ++_j : --_j) {
            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(_super) {
      __extends(MultiLine, _super);

      function MultiLine() {
        _ref1 = MultiLine.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      MultiLine.prototype.default_view = MultiLineView;

      MultiLine.prototype.type = 'MultiLine';

      MultiLine.prototype.display_defaults = function() {
        return _.extend({}, MultiLine.__super__.display_defaults.call(this), this.line_defaults);
      };

      return MultiLine;

    })(Glyph.Model);
    MultiLines = (function(_super) {
      __extends(MultiLines, _super);

      function MultiLines() {
        _ref2 = MultiLines.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      MultiLines.prototype.model = MultiLine;

      return MultiLines;

    })(Glyph.Collection);
    return {
      Model: MultiLine,
      View: MultiLineView,
      Collection: new MultiLines()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=multi_line.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/oval',["underscore", "renderer/properties", "./glyph"], function(_, Properties, Glyph) {
    var Oval, OvalView, Ovals, _ref, _ref1, _ref2;
    OvalView = (function(_super) {
      __extends(OvalView, _super);

      function OvalView() {
        _ref = OvalView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      OvalView.prototype._fields = ['x', 'y', 'width', 'height', 'angle'];

      OvalView.prototype._properties = ['line', 'fill'];

      OvalView.prototype._map_data = function() {
        var _ref1;
        _ref1 = this.renderer.map_to_screen(this.x, this.glyph.x.units, this.y, this.glyph.y.units), this.sx = _ref1[0], this.sy = _ref1[1];
        this.sw = this.distance_vector('x', 'width', 'center');
        return this.sh = this.distance_vector('y', 'height', 'center');
      };

      OvalView.prototype._render = function(ctx, indices, sx, sy, sw, sh) {
        var i, _i, _len, _results;
        if (sx == null) {
          sx = this.sx;
        }
        if (sy == null) {
          sy = this.sy;
        }
        if (sw == null) {
          sw = this.sw;
        }
        if (sh == null) {
          sh = this.sh;
        }
        _results = [];
        for (_i = 0, _len = indices.length; _i < _len; _i++) {
          i = indices[_i];
          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.props.fill.do_fill) {
            this.props.fill.set_vectorize(ctx, i);
            ctx.fill();
          }
          if (this.props.line.do_stroke) {
            this.props.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, reference_point, scale, sh, sw, sx, sy, _ref1;
        reference_point = (_ref1 = this.get_reference_point()) != null ? _ref1 : 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);
      };

      return OvalView;

    })(Glyph.View);
    Oval = (function(_super) {
      __extends(Oval, _super);

      function Oval() {
        _ref1 = Oval.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Oval.prototype.default_view = OvalView;

      Oval.prototype.type = 'Oval';

      Oval.prototype.display_defaults = function() {
        return _.extend({}, Oval.__super__.display_defaults.call(this), this.line_defaults, this.fill_defaults, {
          angle: 0.0
        });
      };

      return Oval;

    })(Glyph.Model);
    Ovals = (function(_super) {
      __extends(Ovals, _super);

      function Ovals() {
        _ref2 = Ovals.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Ovals.prototype.model = Oval;

      return Ovals;

    })(Glyph.Collection);
    return {
      Model: Oval,
      View: OvalView,
      Collection: new Ovals()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=oval.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/patch',["underscore", "renderer/properties", "./glyph"], function(_, Properties, Glyph) {
    var Patch, PatchView, Patches, _ref, _ref1, _ref2;
    PatchView = (function(_super) {
      __extends(PatchView, _super);

      function PatchView() {
        _ref = PatchView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      PatchView.prototype._fields = ['x', 'y'];

      PatchView.prototype._properties = ['line', 'fill'];

      PatchView.prototype._map_data = function() {
        var _ref1;
        return _ref1 = this.renderer.map_to_screen(this.x, this.glyph.x.units, this.y, this.glyph.y.units), this.sx = _ref1[0], this.sy = _ref1[1], _ref1;
      };

      PatchView.prototype._render = function(ctx, indices) {
        var i, _i, _j, _len, _len1;
        if (this.props.fill.do_fill) {
          this.props.fill.set(ctx, this.props);
          for (_i = 0, _len = indices.length; _i < _len; _i++) {
            i = indices[_i];
            if (i === 0) {
              ctx.beginPath();
              ctx.moveTo(this.sx[i], this.sy[i]);
              continue;
            } else if (isNaN(this.sx[i] + this.sy[i])) {
              ctx.closePath();
              ctx.fill();
              ctx.beginPath();
              continue;
            } else {
              ctx.lineTo(this.sx[i], this.sy[i]);
            }
          }
          ctx.closePath();
          ctx.fill();
        }
        if (this.props.line.do_stroke) {
          this.props.line.set(ctx, this.props);
          for (_j = 0, _len1 = indices.length; _j < _len1; _j++) {
            i = indices[_j];
            if (i === 0) {
              ctx.beginPath();
              ctx.moveTo(this.sx[i], this.sy[i]);
              continue;
            } else if (isNaN(this.sx[i] + this.sy[i])) {
              ctx.closePath();
              ctx.stroke();
              ctx.beginPath();
              continue;
            } else {
              ctx.lineTo(this.sx[i], this.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(_super) {
      __extends(Patch, _super);

      function Patch() {
        _ref1 = Patch.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Patch.prototype.default_view = PatchView;

      Patch.prototype.type = 'Patch';

      Patch.prototype.display_defaults = function() {
        return _.extend({}, Patch.__super__.display_defaults.call(this), this.line_defaults, this.fill_defaults);
      };

      return Patch;

    })(Glyph.Model);
    Patches = (function(_super) {
      __extends(Patches, _super);

      function Patches() {
        _ref2 = Patches.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Patches.prototype.model = Patch;

      return Patches;

    })(Glyph.Collection);
    return {
      Model: Patch,
      View: PatchView,
      Collection: new Patches()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=patch.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/patches',["underscore", "rbush", "renderer/properties", "./glyph"], function(_, rbush, Properties, Glyph) {
    var Patches, PatchesView, Patcheses, point_in_poly, _ref, _ref1, _ref2;
    point_in_poly = function(x, y, px, py) {
      var i, inside, x1, x2, y1, y2, _i, _ref;
      inside = false;
      x1 = px[px.length - 1];
      y1 = py[py.length - 1];
      for (i = _i = 0, _ref = px.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
        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;
    };
    PatchesView = (function(_super) {
      __extends(PatchesView, _super);

      function PatchesView() {
        _ref = PatchesView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      PatchesView.prototype._fields = ['xs', 'ys'];

      PatchesView.prototype._properties = ['line', 'fill'];

      PatchesView.prototype._set_data = function() {
        var i, pts, x, xs, y, ys, _i, _ref1;
        this.max_size = _.max(this.size);
        this.index = rbush();
        pts = [];
        for (i = _i = 0, _ref1 = this.xs.length; 0 <= _ref1 ? _i < _ref1 : _i > _ref1; i = 0 <= _ref1 ? ++_i : --_i) {
          xs = (function() {
            var _j, _len, _ref2, _results;
            _ref2 = this.xs[i];
            _results = [];
            for (_j = 0, _len = _ref2.length; _j < _len; _j++) {
              x = _ref2[_j];
              if (!_.isNaN(x)) {
                _results.push(x);
              }
            }
            return _results;
          }).call(this);
          ys = (function() {
            var _j, _len, _ref2, _results;
            _ref2 = this.ys[i];
            _results = [];
            for (_j = 0, _len = _ref2.length; _j < _len; _j++) {
              y = _ref2[_j];
              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
            }
          ]);
        }
        return this.index.load(pts);
      };

      PatchesView.prototype._map_data = function() {
        var i, sx, sy, _i, _ref1, _ref2, _results;
        this.sxs = [];
        this.sys = [];
        _results = [];
        for (i = _i = 0, _ref1 = this.xs.length; 0 <= _ref1 ? _i < _ref1 : _i > _ref1; i = 0 <= _ref1 ? ++_i : --_i) {
          _ref2 = this.renderer.map_to_screen(this.xs[i], this.glyph.xs.units, this.ys[i], this.glyph.ys.units), sx = _ref2[0], sy = _ref2[1];
          this.sxs.push(sx);
          _results.push(this.sys.push(sy));
        }
        return _results;
      };

      PatchesView.prototype._mask_data = function() {
        var x, x0, x1, xr, y0, y1, yr, _ref1, _ref2;
        if (this.glyph.xs.units === "screen" || this.glyph.ys.units === "screen") {
          return this.all_indices;
        }
        xr = this.renderer.plot_view.x_range;
        _ref1 = [xr.get('start'), xr.get('end')], x0 = _ref1[0], x1 = _ref1[1];
        yr = this.renderer.plot_view.y_range;
        _ref2 = [yr.get('start'), yr.get('end')], y0 = _ref2[0], y1 = _ref2[1];
        return (function() {
          var _i, _len, _ref3, _results;
          _ref3 = this.index.search([x0, y0, x1, y1]);
          _results = [];
          for (_i = 0, _len = _ref3.length; _i < _len; _i++) {
            x = _ref3[_i];
            _results.push(x[4].i);
          }
          return _results;
        }).call(this);
      };

      PatchesView.prototype._render = function(ctx, indices) {
        var i, j, sx, sy, _i, _j, _k, _len, _ref1, _ref2, _ref3, _results;
        _results = [];
        for (_i = 0, _len = indices.length; _i < _len; _i++) {
          i = indices[_i];
          _ref1 = [this.sxs[i], this.sys[i]], sx = _ref1[0], sy = _ref1[1];
          if (this.props.fill.do_fill) {
            this.props.fill.set_vectorize(ctx, i);
            for (j = _j = 0, _ref2 = sx.length; 0 <= _ref2 ? _j < _ref2 : _j > _ref2; j = 0 <= _ref2 ? ++_j : --_j) {
              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.props.line.do_stroke) {
            this.props.line.set_vectorize(ctx, i);
            for (j = _k = 0, _ref3 = sx.length; 0 <= _ref3 ? _k < _ref3 : _k > _ref3; j = 0 <= _ref3 ? ++_k : --_k) {
              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, sx, sy, vx, vy, x, y, _i, _ref1, _ref2;
        _ref1 = [geometry.vx, geometry.vy], vx = _ref1[0], vy = _ref1[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);
        y = this.renderer.ymapper.map_from_target(vy);
        candidates = (function() {
          var _i, _len, _ref2, _results;
          _ref2 = this.index.search([x, y, x, y]);
          _results = [];
          for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
            x = _ref2[_i];
            _results.push(x[4].i);
          }
          return _results;
        }).call(this);
        hits = [];
        for (i = _i = 0, _ref2 = candidates.length; 0 <= _ref2 ? _i < _ref2 : _i > _ref2; i = 0 <= _ref2 ? ++_i : --_i) {
          idx = candidates[i];
          if (point_in_poly(sx, sy, this.sxs[idx], this.sys[idx])) {
            hits.push(idx);
          }
        }
        return hits;
      };

      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(_super) {
      __extends(Patches, _super);

      function Patches() {
        _ref1 = Patches.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Patches.prototype.default_view = PatchesView;

      Patches.prototype.type = 'Patches';

      Patches.prototype.display_defaults = function() {
        return _.extend({}, Patches.__super__.display_defaults.call(this), this.line_defaults, this.fill_defaults);
      };

      return Patches;

    })(Glyph.Model);
    Patcheses = (function(_super) {
      __extends(Patcheses, _super);

      function Patcheses() {
        _ref2 = Patcheses.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Patcheses.prototype.model = Patches;

      return Patcheses;

    })(Glyph.Collection);
    return {
      Model: Patches,
      View: PatchesView,
      Collection: new Patcheses()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=patches.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/quad',["underscore", "rbush", "renderer/properties", "./glyph"], function(_, rbush, Properties, Glyph) {
    var Quad, QuadView, Quads, _ref, _ref1, _ref2;
    QuadView = (function(_super) {
      __extends(QuadView, _super);

      function QuadView() {
        _ref = QuadView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      QuadView.prototype._fields = ['right', 'left', 'bottom', 'top'];

      QuadView.prototype._properties = ['line', 'fill'];

      QuadView.prototype._map_data = function() {
        var _ref1, _ref2;
        _ref1 = this.renderer.map_to_screen(this.left, this.glyph.left.units, this.top, this.glyph.top.units), this.sx0 = _ref1[0], this.sy0 = _ref1[1];
        return _ref2 = this.renderer.map_to_screen(this.right, this.glyph.right.units, this.bottom, this.glyph.bottom.units), this.sx1 = _ref2[0], this.sy1 = _ref2[1], _ref2;
      };

      QuadView.prototype._render = function(ctx, indices, sx0, sx1, sy0, sy1) {
        var i, _i, _len, _results;
        if (sx0 == null) {
          sx0 = this.sx0;
        }
        if (sx1 == null) {
          sx1 = this.sx1;
        }
        if (sy0 == null) {
          sy0 = this.sy0;
        }
        if (sy1 == null) {
          sy1 = this.sy1;
        }
        _results = [];
        for (_i = 0, _len = indices.length; _i < _len; _i++) {
          i = indices[_i];
          if (isNaN(sx0[i] + sy0[i] + sx1[i] + sy1[i])) {
            continue;
          }
          if (this.props.fill.do_fill) {
            this.props.fill.set_vectorize(ctx, i);
            ctx.fillRect(sx0[i], sy0[i], sx1[i] - sx0[i], sy1[i] - sy0[i]);
          }
          if (this.props.line.do_stroke) {
            ctx.beginPath();
            ctx.rect(sx0[i], sy0[i], sx1[i] - sx0[i], sy1[i] - sy0[i]);
            this.props.line.set_vectorize(ctx, i);
            _results.push(ctx.stroke());
          } else {
            _results.push(void 0);
          }
        }
        return _results;
      };

      QuadView.prototype._hit_point = function(geometry) {
        var hits, i, sx, sy, vx, vy, _i, _ref1, _ref2;
        _ref1 = [geometry.vx, geometry.vy], vx = _ref1[0], vy = _ref1[1];
        sx = this.renderer.plot_view.canvas.vx_to_sx(vx);
        sy = this.renderer.plot_view.canvas.vy_to_sy(vy);
        hits = [];
        for (i = _i = 0, _ref2 = this.sx0.length; 0 <= _ref2 ? _i < _ref2 : _i > _ref2; i = 0 <= _ref2 ? ++_i : --_i) {
          if (sx >= this.sx0[i] && sx <= this.sx1[i] && sy >= this.sy0[i] && sy < this.sy1[i]) {
            hits.push(i);
          }
        }
        return hits;
      };

      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(_super) {
      __extends(Quad, _super);

      function Quad() {
        _ref1 = Quad.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Quad.prototype.default_view = QuadView;

      Quad.prototype.type = 'Quad';

      Quad.prototype.display_defaults = function() {
        return _.extend({}, Quad.__super__.display_defaults.call(this), this.line_defaults, this.fill_defaults);
      };

      return Quad;

    })(Glyph.Model);
    Quads = (function(_super) {
      __extends(Quads, _super);

      function Quads() {
        _ref2 = Quads.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Quads.prototype.model = Quad;

      return Quads;

    })(Glyph.Collection);
    return {
      Model: Quad,
      View: QuadView,
      Collection: new Quads()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=quad.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/quadratic',["underscore", "renderer/properties", "./glyph"], function(_, Properties, Glyph) {
    var Quadratic, QuadraticView, Quadratics, _ref, _ref1, _ref2;
    QuadraticView = (function(_super) {
      __extends(QuadraticView, _super);

      function QuadraticView() {
        _ref = QuadraticView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      QuadraticView.prototype._fields = ['x0', 'y0', 'x1', 'y1', 'cx', 'cy'];

      QuadraticView.prototype._properties = ['line'];

      QuadraticView.prototype._map_data = function() {
        var _ref1, _ref2, _ref3;
        _ref1 = this.renderer.map_to_screen(this.x0, this.glyph.x0.units, this.y0, this.glyph.y0.units), this.sx0 = _ref1[0], this.sy0 = _ref1[1];
        _ref2 = this.renderer.map_to_screen(this.x1, this.glyph.x1.units, this.y1, this.glyph.y1.units), this.sx1 = _ref2[0], this.sy1 = _ref2[1];
        return _ref3 = this.renderer.map_to_screen(this.cx, this.glyph.cx.units, this.cy, this.glyph.cy.units), this.scx = _ref3[0], this.scy = _ref3[1], _ref3;
      };

      QuadraticView.prototype._render = function(ctx, indices) {
        var i, _i, _len, _results;
        if (this.props.line.do_stroke) {
          _results = [];
          for (_i = 0, _len = indices.length; _i < _len; _i++) {
            i = indices[_i];
            if (isNaN(this.sx0[i] + this.sy0[i] + this.sx1[i] + this.sy1[i] + this.scx[i] + this.scy[i])) {
              continue;
            }
            ctx.beginPath();
            ctx.moveTo(this.sx0[i], this.sy0[i]);
            ctx.quadraticCurveTo(this.scx[i], this.scy[i], this.sx1[i], this.sy1[i]);
            this.props.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(_super) {
      __extends(Quadratic, _super);

      function Quadratic() {
        _ref1 = Quadratic.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Quadratic.prototype.default_view = QuadraticView;

      Quadratic.prototype.type = 'Quadratic';

      Quadratic.prototype.display_defaults = function() {
        return _.extend({}, Quadratic.__super__.display_defaults.call(this), this.line_defaults);
      };

      return Quadratic;

    })(Glyph.Model);
    Quadratics = (function(_super) {
      __extends(Quadratics, _super);

      function Quadratics() {
        _ref2 = Quadratics.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Quadratics.prototype.model = Quadratic;

      return Quadratics;

    })(Glyph.Collection);
    return {
      Model: Quadratic,
      View: QuadraticView,
      Collection: new Quadratics()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=quadratic.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/ray',["underscore", "renderer/properties", "./glyph"], function(_, Properties, Glyph) {
    var Ray, RayView, Rays, _ref, _ref1, _ref2;
    RayView = (function(_super) {
      __extends(RayView, _super);

      function RayView() {
        _ref = RayView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      RayView.prototype._fields = ['x', 'y', 'angle', 'length'];

      RayView.prototype._properties = ['line'];

      RayView.prototype._map_data = function() {
        var height, i, inf_len, width, _i, _ref1, _ref2, _results;
        _ref1 = this.renderer.map_to_screen(this.x, this.glyph.x.units, this.y, this.glyph.y.units), this.sx = _ref1[0], this.sy = _ref1[1];
        this.length = this.distance_vector('x', 'length', 'edge');
        width = this.renderer.plot_view.frame.get('width');
        height = this.renderer.plot_view.frame.get('height');
        inf_len = 2 * (width + height);
        _results = [];
        for (i = _i = 0, _ref2 = this.length.length; 0 <= _ref2 ? _i < _ref2 : _i > _ref2; i = 0 <= _ref2 ? ++_i : --_i) {
          if (this.length[i] === 0) {
            _results.push(this.length[i] = inf_len);
          } else {
            _results.push(void 0);
          }
        }
        return _results;
      };

      RayView.prototype._render = function(ctx, indices) {
        var i, _i, _len, _results;
        if (this.props.line.do_stroke) {
          _results = [];
          for (_i = 0, _len = indices.length; _i < _len; _i++) {
            i = indices[_i];
            if (isNaN(this.sx[i] + this.sy[i] + this.angle[i] + this.length[i])) {
              continue;
            }
            ctx.translate(this.sx[i], this.sy[i]);
            ctx.rotate(this.angle[i]);
            ctx.beginPath();
            ctx.moveTo(0, 0);
            ctx.lineTo(this.length[i], 0);
            this.props.line.set_vectorize(ctx, i);
            ctx.stroke();
            ctx.rotate(-this.angle[i]);
            _results.push(ctx.translate(-this.sx[i], -this.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(_super) {
      __extends(Ray, _super);

      function Ray() {
        _ref1 = Ray.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Ray.prototype.default_view = RayView;

      Ray.prototype.type = 'Ray';

      Ray.prototype.display_defaults = function() {
        return _.extend({}, Ray.__super__.display_defaults.call(this), this.line_defaults);
      };

      return Ray;

    })(Glyph.Model);
    Rays = (function(_super) {
      __extends(Rays, _super);

      function Rays() {
        _ref2 = Rays.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Rays.prototype.model = Ray;

      return Rays;

    })(Glyph.Collection);
    return {
      Model: Ray,
      View: RayView,
      Collection: new Rays()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=ray.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/rect',["underscore", "rbush", "renderer/properties", "./glyph"], function(_, rbush, Properties, Glyph) {
    var Rect, RectView, Rects, _ref, _ref1, _ref2;
    RectView = (function(_super) {
      __extends(RectView, _super);

      function RectView() {
        _ref = RectView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      RectView.prototype._fields = ['x', 'y', 'width', 'height', 'angle'];

      RectView.prototype._properties = ['line', 'fill'];

      RectView.prototype._map_data = function() {
        var i, sxi, syi, _i, _ref1, _ref2;
        _ref1 = this.renderer.map_to_screen(this.x, this.glyph.x.units, this.y, this.glyph.y.units), sxi = _ref1[0], syi = _ref1[1];
        this.sw = this.distance_vector('x', 'width', 'center', this.mget('dilate'));
        this.sh = this.distance_vector('y', 'height', 'center', this.mget('dilate'));
        this.sx = new Array(sxi.length);
        this.sy = new Array(sxi.length);
        for (i = _i = 0, _ref2 = sxi.length; 0 <= _ref2 ? _i < _ref2 : _i > _ref2; i = 0 <= _ref2 ? ++_i : --_i) {
          if (Math.abs(sxi[i] - this.sw[i]) < 2) {
            this.sx[i] = Math.round(sxi[i]);
          } else {
            this.sx[i] = sxi[i];
          }
          if (Math.abs(syi[i] - this.sh[i]) < 2) {
            this.sy[i] = Math.round(syi[i]);
          } else {
            this.sy[i] = syi[i];
          }
        }
        this.max_width = _.max(this.width);
        return this.max_height = _.max(this.height);
      };

      RectView.prototype._set_data = function() {
        var i, pts, _i, _ref1;
        this.index = rbush();
        pts = [];
        for (i = _i = 0, _ref1 = this.x.length; 0 <= _ref1 ? _i < _ref1 : _i > _ref1; i = 0 <= _ref1 ? ++_i : --_i) {
          if (!isNaN(this.x[i] + this.y[i])) {
            pts.push([
              this.x[i], this.y[i], this.x[i], this.y[i], {
                'i': i
              }
            ]);
          }
        }
        return this.index.load(pts);
      };

      RectView.prototype._render = function(ctx, indices, sx, sy, sw, sh) {
        var i, _i, _j, _len, _len1;
        if (sx == null) {
          sx = this.sx;
        }
        if (sy == null) {
          sy = this.sy;
        }
        if (sw == null) {
          sw = this.sw;
        }
        if (sh == null) {
          sh = this.sh;
        }
        if (this.props.fill.do_fill) {
          for (_i = 0, _len = indices.length; _i < _len; _i++) {
            i = indices[_i];
            if (isNaN(sx[i] + sy[i] + sw[i] + sh[i] + this.angle[i])) {
              continue;
            }
            this.props.fill.set_vectorize(ctx, i);
            if (this.angle[i]) {
              ctx.translate(sx[i], sy[i]);
              ctx.rotate(this.angle[i]);
              ctx.fillRect(-sw[i] / 2, -sh[i] / 2, sw[i], sh[i]);
              ctx.rotate(-this.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.props.line.do_stroke) {
          ctx.beginPath();
          for (_j = 0, _len1 = indices.length; _j < _len1; _j++) {
            i = indices[_j];
            if (isNaN(sx[i] + sy[i] + sw[i] + sh[i] + this.angle[i])) {
              continue;
            }
            if (sw[i] === 0 || sh[i] === 0) {
              continue;
            }
            if (this.angle[i]) {
              ctx.translate(sx[i], sy[i]);
              ctx.rotate(this.angle[i]);
              ctx.rect(-sw[i] / 2, -sh[i] / 2, sw[i], sh[i]);
              ctx.rotate(-this.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.props.line.set_vectorize(ctx, i);
            ctx.stroke();
            ctx.beginPath();
          }
          return ctx.stroke();
        }
      };

      RectView.prototype._hit_rect = function(geometry) {
        var x, x0, x1, y0, y1, _ref1, _ref2;
        _ref1 = this.renderer.xmapper.v_map_from_target([geometry.vx0, geometry.vx1]), x0 = _ref1[0], x1 = _ref1[1];
        _ref2 = this.renderer.ymapper.v_map_from_target([geometry.vy0, geometry.vy1]), y0 = _ref2[0], y1 = _ref2[1];
        return (function() {
          var _i, _len, _ref3, _results;
          _ref3 = this.index.search([x0, y0, x1, y1]);
          _results = [];
          for (_i = 0, _len = _ref3.length; _i < _len; _i++) {
            x = _ref3[_i];
            _results.push(x[4].i);
          }
          return _results;
        }).call(this);
      };

      RectView.prototype._hit_point = function(geometry) {
        var c, candidates, d, height_in, hits, i, max_height, max_width, pt, px, py, s, sx, sy, vx, vx0, vx1, vy, vy0, vy1, width_in, x, x0, x1, xcat, y, y0, y1, ycat, _i, _len, _ref1, _ref2, _ref3;
        _ref1 = [geometry.vx, geometry.vy], vx = _ref1[0], vy = _ref1[1];
        x = this.renderer.xmapper.map_from_target(vx);
        y = this.renderer.ymapper.map_from_target(vy);
        xcat = typeof x === "string";
        ycat = typeof y === "string";
        if (xcat || ycat) {
          candidates = (function() {
            var _i, _ref2, _results;
            _results = [];
            for (i = _i = 0, _ref2 = this.x.length; 0 <= _ref2 ? _i < _ref2 : _i > _ref2; i = 0 <= _ref2 ? ++_i : --_i) {
              _results.push(i);
            }
            return _results;
          }).call(this);
        } else {
          if (this.width_units === "screen" || xcat) {
            max_width = this.max_width;
            if (xcat) {
              max_width = this.renderer.xmapper.map_to_target(max_width);
            }
            vx0 = vx - 2 * max_width;
            vx1 = vx + 2 * max_width;
            _ref2 = this.renderer.xmapper.v_map_from_target([vx0, vx1]), x0 = _ref2[0], x1 = _ref2[1];
          } else {
            x0 = x - 2 * this.max_width;
            x1 = x + 2 * this.max_width;
          }
          if (this.height_units === "screen" || ycat) {
            max_height = this.max_height;
            if (ycat) {
              max_height = this.renderer.ymapper.map_to_target(max_height);
            }
            vy0 = vy - 2 * max_height;
            vy1 = vy + 2 * max_height;
            _ref3 = this.renderer.ymapper.v_map_from_target([vy0, vy1]), y0 = _ref3[0], y1 = _ref3[1];
          } else {
            y0 = y - 2 * this.max_height;
            y1 = y + 2 * this.max_height;
          }
          candidates = (function() {
            var _i, _len, _ref4, _results;
            _ref4 = this.index.search([x0, y0, x1, y1]);
            _results = [];
            for (_i = 0, _len = _ref4.length; _i < _len; _i++) {
              pt = _ref4[_i];
              _results.push(pt[4].i);
            }
            return _results;
          }).call(this);
        }
        hits = [];
        for (_i = 0, _len = candidates.length; _i < _len; _i++) {
          i = candidates[_i];
          if (this.width_units === "screen" || xcat) {
            sx = this.renderer.plot_view.canvas.vx_to_sx(vx);
          } else {
            sx = this.renderer.plot_view.canvas.vx_to_sx(this.renderer.xmapper.map_to_target(x));
          }
          if (this.height_units === "screen" || ycat) {
            sy = this.renderer.plot_view.canvas.vy_to_sy(vy);
          } else {
            sy = this.renderer.plot_view.canvas.vy_to_sy(this.renderer.ymapper.map_to_target(y));
          }
          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);
          }
        }
        return hits;
      };

      RectView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
        return this._generic_area_legend(ctx, x0, x1, y0, y1);
      };

      return RectView;

    })(Glyph.View);
    Rect = (function(_super) {
      __extends(Rect, _super);

      function Rect() {
        _ref1 = Rect.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Rect.prototype.default_view = RectView;

      Rect.prototype.type = 'Rect';

      Rect.prototype.display_defaults = function() {
        return _.extend({}, Rect.__super__.display_defaults.call(this), this.line_defaults, this.fill_defaults, {
          angle: 0.0,
          dilate: false
        });
      };

      return Rect;

    })(Glyph.Model);
    Rects = (function(_super) {
      __extends(Rects, _super);

      function Rects() {
        _ref2 = Rects.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Rects.prototype.model = Rect;

      return Rects;

    })(Glyph.Collection);
    return {
      Model: Rect,
      View: RectView,
      Collection: new Rects()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=rect.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/segment',["underscore", "renderer/properties", "./glyph"], function(_, Properties, Glyph) {
    var Segment, SegmentView, Segments, _ref, _ref1, _ref2;
    SegmentView = (function(_super) {
      __extends(SegmentView, _super);

      function SegmentView() {
        _ref = SegmentView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      SegmentView.prototype._fields = ['x0', 'y0', 'x1', 'y1'];

      SegmentView.prototype._properties = ['line'];

      SegmentView.prototype._map_data = function() {
        var _ref1, _ref2;
        _ref1 = this.renderer.map_to_screen(this.x0, this.glyph.x0.units, this.y0, this.glyph.y0.units), this.sx0 = _ref1[0], this.sy0 = _ref1[1];
        return _ref2 = this.renderer.map_to_screen(this.x1, this.glyph.x1.units, this.y1, this.glyph.y1.units), this.sx1 = _ref2[0], this.sy1 = _ref2[1], _ref2;
      };

      SegmentView.prototype._render = function(ctx, indices) {
        var i, _i, _len, _results;
        if (this.props.line.do_stroke) {
          _results = [];
          for (_i = 0, _len = indices.length; _i < _len; _i++) {
            i = indices[_i];
            if (isNaN(this.sx0[i] + this.sy0[i] + this.sx1[i] + this.sy1[i])) {
              continue;
            }
            ctx.beginPath();
            ctx.moveTo(this.sx0[i], this.sy0[i]);
            ctx.lineTo(this.sx1[i], this.sy1[i]);
            this.props.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(_super) {
      __extends(Segment, _super);

      function Segment() {
        _ref1 = Segment.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Segment.prototype.default_view = SegmentView;

      Segment.prototype.type = 'Segment';

      Segment.prototype.display_defaults = function() {
        return _.extend({}, Segment.__super__.display_defaults.call(this), this.line_defaults);
      };

      return Segment;

    })(Glyph.Model);
    Segments = (function(_super) {
      __extends(Segments, _super);

      function Segments() {
        _ref2 = Segments.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Segments.prototype.model = Segment;

      return Segments;

    })(Glyph.Collection);
    return {
      Model: Segment,
      View: SegmentView,
      Collection: new Segments()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=segment.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/text',["underscore", "./glyph"], function(_, Glyph) {
    var Text, TextView, Texts, _ref, _ref1, _ref2;
    TextView = (function(_super) {
      __extends(TextView, _super);

      function TextView() {
        _ref = TextView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      TextView.prototype._fields = ['x', 'y', 'angle', 'text:string', 'x_offset', 'y_offset'];

      TextView.prototype._properties = ['text'];

      TextView.prototype._map_data = function() {
        var _ref1;
        _ref1 = this.renderer.map_to_screen(this.x, this.glyph.x.units, this.y, this.glyph.y.units), this.sx = _ref1[0], this.sy = _ref1[1];
        this.sx_offset = this.distance_vector('x', 'x_offset', 'edge');
        return this.sy_offset = this.distance_vector('y', 'y_offset', 'edge');
      };

      TextView.prototype._render = function(ctx, indices) {
        var i, _i, _len, _results;
        _results = [];
        for (_i = 0, _len = indices.length; _i < _len; _i++) {
          i = indices[_i];
          if (isNaN(this.sx[i] + this.sy[i] + this.sx_offset[i] + this.sy_offset[i] + this.angle[i]) || (this.text[i] == null)) {
            continue;
          }
          ctx.save();
          ctx.translate(this.sx[i] + this.sx_offset[i], this.sy[i] + this.sy_offset[i]);
          ctx.rotate(this.angle[i]);
          this.props.text.set_vectorize(ctx, i);
          ctx.fillText(this.text[i], 0, 0);
          _results.push(ctx.restore());
        }
        return _results;
      };

      TextView.prototype.draw_legend = function(ctx, x1, x2, y1, y2) {
        var glyph_settings, reference_point, text_props;
        ctx.save();
        reference_point = this.get_reference_point();
        if (reference_point != null) {
          glyph_settings = reference_point;
        } else {
          glyph_settings = this.props;
        }
        text_props = this.props.text;
        text_props.set(ctx, glyph_settings);
        ctx.font = text_props.font(12);
        ctx.textAlign = "right";
        ctx.textBaseline = "middle";
        ctx.fillText("txt", x2, (y1 + y2) / 2);
        return ctx.restore();
      };

      return TextView;

    })(Glyph.View);
    Text = (function(_super) {
      __extends(Text, _super);

      function Text() {
        _ref1 = Text.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Text.prototype.default_view = TextView;

      Text.prototype.type = 'Text';

      Text.prototype.defaults = function() {
        return _.extend({}, Text.__super__.defaults.call(this), {
          angle: 0,
          x_offset: {
            value: 0,
            units: "screen"
          },
          y_offset: {
            value: 0,
            units: "screen"
          }
        });
      };

      Text.prototype.display_defaults = function() {
        return _.extend({}, Text.__super__.display_defaults.call(this), {
          text_font: "helvetica",
          text_font_size: "12pt",
          text_font_style: "normal",
          text_color: "#444444",
          text_alpha: 1.0,
          text_align: "left",
          text_baseline: "bottom"
        });
      };

      return Text;

    })(Glyph.Model);
    Texts = (function(_super) {
      __extends(Texts, _super);

      function Texts() {
        _ref2 = Texts.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Texts.prototype.model = Text;

      return Texts;

    })(Glyph.Collection);
    return {
      Model: Text,
      View: TextView,
      Collection: new Texts()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=text.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/wedge',["underscore", "rbush", "common/mathutils", "renderer/properties", "./glyph"], function(_, rbush, mathutils, Properties, Glyph) {
    var Wedge, WedgeView, Wedges, _ref, _ref1, _ref2;
    WedgeView = (function(_super) {
      __extends(WedgeView, _super);

      function WedgeView() {
        _ref = WedgeView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      WedgeView.prototype._fields = ['x', 'y', 'radius', 'start_angle', 'end_angle', 'direction:string'];

      WedgeView.prototype._properties = ['line', 'fill'];

      WedgeView.prototype._set_data = function() {
        var i, pts, _i, _ref1;
        this.max_radius = _.max(this.radius);
        this.index = rbush();
        pts = [];
        for (i = _i = 0, _ref1 = this.x.length; 0 <= _ref1 ? _i < _ref1 : _i > _ref1; i = 0 <= _ref1 ? ++_i : --_i) {
          if (!isNaN(this.x[i] + this.y[i])) {
            pts.push([
              this.x[i], this.y[i], this.x[i], this.y[i], {
                'i': i
              }
            ]);
          }
        }
        return this.index.load(pts);
      };

      WedgeView.prototype._map_data = function() {
        var _ref1;
        _ref1 = this.renderer.map_to_screen(this.x, this.glyph.x.units, this.y, this.glyph.y.units), this.sx = _ref1[0], this.sy = _ref1[1];
        return this.radius = this.distance_vector('x', 'radius', 'edge');
      };

      WedgeView.prototype._render = function(ctx, indices, sx, sy, radius) {
        var i, _i, _len, _results;
        if (sx == null) {
          sx = this.sx;
        }
        if (sy == null) {
          sy = this.sy;
        }
        if (radius == null) {
          radius = this.radius;
        }
        _results = [];
        for (_i = 0, _len = indices.length; _i < _len; _i++) {
          i = indices[_i];
          if (isNaN(sx[i] + sy[i] + radius[i] + this.start_angle[i] + this.end_angle[i] + this.direction[i])) {
            continue;
          }
          ctx.beginPath();
          ctx.arc(sx[i], sy[i], radius[i], this.start_angle[i], this.end_angle[i], this.direction[i]);
          ctx.lineTo(sx[i], sy[i]);
          ctx.closePath();
          if (this.props.fill.do_fill) {
            this.props.fill.set_vectorize(ctx, i);
            ctx.fill();
          }
          if (this.props.line.do_stroke) {
            this.props.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, candidates2, dist, hits, i, pt, r2, sx, sx0, sx1, sy, sy0, sy1, vx, vx0, vx1, vy, vy0, vy1, x, x0, x1, y, y0, y1, _i, _j, _k, _len, _len1, _len2, _ref1, _ref2, _ref3, _ref4;
        _ref1 = [geometry.vx, geometry.vy], vx = _ref1[0], vy = _ref1[1];
        x = this.renderer.xmapper.map_from_target(vx);
        y = this.renderer.ymapper.map_from_target(vy);
        if (this.radius_units === "screen") {
          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];
          vy0 = vy - this.max_radius;
          vy1 = vy + this.max_radius;
          _ref3 = this.renderer.ymapper.v_map_from_target([vy0, vy1]), y0 = _ref3[0], y1 = _ref3[1];
        } else {
          x0 = x - this.max_radius;
          x1 = x + this.max_radius;
          y0 = y - this.max_radius;
          y1 = y + this.max_radius;
        }
        candidates = (function() {
          var _i, _len, _ref4, _results;
          _ref4 = this.index.search([x0, y0, x1, y1]);
          _results = [];
          for (_i = 0, _len = _ref4.length; _i < _len; _i++) {
            pt = _ref4[_i];
            _results.push(pt[4].i);
          }
          return _results;
        }).call(this);
        candidates2 = [];
        if (this.radius_units === "screen") {
          sx = this.renderer.plot_view.canvas.vx_to_sx(vx);
          sy = this.renderer.plot_view.canvas.vy_to_sy(vy);
          for (_i = 0, _len = candidates.length; _i < _len; _i++) {
            i = candidates[_i];
            r2 = Math.pow(this.radius[i], 2);
            dist = Math.pow(this.sx[i] - sx, 2) + Math.pow(this.sy[i] - sy, 2);
            if (dist <= r2) {
              candidates2.push([i, dist]);
            }
          }
        } else {
          for (_j = 0, _len1 = candidates.length; _j < _len1; _j++) {
            i = candidates[_j];
            r2 = Math.pow(this.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 <= r2) {
              candidates2.push([i, dist]);
            }
          }
        }
        hits = [];
        for (_k = 0, _len2 = candidates2.length; _k < _len2; _k++) {
          _ref4 = candidates2[_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]);
          }
        }
        hits = _.chain(hits).sortBy(function(elt) {
          return elt[1];
        }).map(function(elt) {
          return elt[0];
        }).value();
        return hits;
      };

      WedgeView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
        var indices, radius, reference_point, sx, sy, _ref1;
        reference_point = (_ref1 = this.get_reference_point()) != null ? _ref1 : 0;
        indices = [reference_point];
        sx = {};
        sx[reference_point] = (x0 + x1) / 2;
        sy = {};
        sy[reference_point] = (y0 + y1) / 2;
        radius = {};
        radius[reference_point] = Math.min(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 0.4;
        return this._render(ctx, indices, sx, sy, radius);
      };

      return WedgeView;

    })(Glyph.View);
    Wedge = (function(_super) {
      __extends(Wedge, _super);

      function Wedge() {
        _ref1 = Wedge.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Wedge.prototype.default_view = WedgeView;

      Wedge.prototype.type = 'Wedge';

      Wedge.prototype.display_defaults = function() {
        return _.extend({}, Wedge.__super__.display_defaults.call(this), this.line_defaults, this.fill_defaults, {
          direction: 'anticlock'
        });
      };

      return Wedge;

    })(Glyph.Model);
    Wedges = (function(_super) {
      __extends(Wedges, _super);

      function Wedges() {
        _ref2 = Wedges.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Wedges.prototype.model = Wedge;

      return Wedges;

    })(Glyph.Collection);
    return {
      Model: Wedge,
      View: WedgeView,
      Collection: new Wedges()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=wedge.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/marker/marker',["underscore", "rbush", "../glyph"], function(_, rbush, Glyph) {
    var Marker, MarkerView, Markers, point_in_poly, _ref, _ref1, _ref2;
    point_in_poly = function(x, y, px, py) {
      var i, inside, x1, x2, y1, y2, _i, _ref;
      inside = false;
      x1 = px[px.length - 1];
      y1 = py[py.length - 1];
      for (i = _i = 0, _ref = px.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
        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;
    };
    MarkerView = (function(_super) {
      __extends(MarkerView, _super);

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

      MarkerView.prototype._fields = ['x', 'y', 'size'];

      MarkerView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
        var indices, reference_point, size, sx, sy, _ref1;
        reference_point = (_ref1 = this.get_reference_point()) != null ? _ref1 : 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;
        return this._render(ctx, indices, sx, sy, size);
      };

      MarkerView.prototype._set_data = function() {
        var i, pts, _i, _ref1;
        this.max_size = _.max(this.size);
        this.index = rbush();
        pts = [];
        for (i = _i = 0, _ref1 = this.x.length; 0 <= _ref1 ? _i < _ref1 : _i > _ref1; i = 0 <= _ref1 ? ++_i : --_i) {
          if (!isNaN(this.x[i] + this.y[i])) {
            pts.push([
              this.x[i], this.y[i], this.x[i], this.y[i], {
                'i': i
              }
            ]);
          }
        }
        return this.index.load(pts);
      };

      MarkerView.prototype._map_data = function() {
        var _ref1;
        return _ref1 = this.renderer.map_to_screen(this.x, this.glyph.x.units, this.y, this.glyph.y.units), this.sx = _ref1[0], this.sy = _ref1[1], _ref1;
      };

      MarkerView.prototype._mask_data = function() {
        var hr, vr, vx0, vx1, vy0, vy1, x, x0, x1, y0, y1, _ref1, _ref2;
        hr = this.renderer.plot_view.frame.get('h_range');
        vx0 = hr.get('start') - this.max_size;
        vx1 = hr.get('end') + this.max_size;
        _ref1 = this.renderer.xmapper.v_map_from_target([vx0, vx1]), 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]), y0 = _ref2[0], y1 = _ref2[1];
        return (function() {
          var _i, _len, _ref3, _results;
          _ref3 = this.index.search([x0, y0, x1, y1]);
          _results = [];
          for (_i = 0, _len = _ref3.length; _i < _len; _i++) {
            x = _ref3[_i];
            _results.push(x[4].i);
          }
          return _results;
        }).call(this);
      };

      MarkerView.prototype._hit_point = function(geometry) {
        var candidates, dist, hits, i, s2, sx, sy, vx, vx0, vx1, vy, vy0, vy1, x, x0, x1, y0, y1, _i, _len, _ref1, _ref2, _ref3;
        _ref1 = [geometry.vx, geometry.vy], vx = _ref1[0], vy = _ref1[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;
        _ref2 = this.renderer.xmapper.v_map_from_target([vx0, vx1]), 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]), y0 = _ref3[0], y1 = _ref3[1];
        candidates = (function() {
          var _i, _len, _ref4, _results;
          _ref4 = this.index.search([x0, y0, x1, y1]);
          _results = [];
          for (_i = 0, _len = _ref4.length; _i < _len; _i++) {
            x = _ref4[_i];
            _results.push(x[4].i);
          }
          return _results;
        }).call(this);
        hits = [];
        for (_i = 0, _len = candidates.length; _i < _len; _i++) {
          i = candidates[_i];
          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]);
          }
        }
        hits = _.chain(hits).sortBy(function(elt) {
          return elt[1];
        }).map(function(elt) {
          return elt[0];
        }).value();
        return hits;
      };

      MarkerView.prototype._hit_rect = function(geometry) {
        var x, x0, x1, y0, y1, _ref1, _ref2;
        _ref1 = this.renderer.xmapper.v_map_from_target([geometry.vx0, geometry.vx1]), x0 = _ref1[0], x1 = _ref1[1];
        _ref2 = this.renderer.ymapper.v_map_from_target([geometry.vy0, geometry.vy1]), y0 = _ref2[0], y1 = _ref2[1];
        return (function() {
          var _i, _len, _ref3, _results;
          _ref3 = this.index.search([x0, y0, x1, y1]);
          _results = [];
          for (_i = 0, _len = _ref3.length; _i < _len; _i++) {
            x = _ref3[_i];
            _results.push(x[4].i);
          }
          return _results;
        }).call(this);
      };

      MarkerView.prototype._hit_poly = function(geometry) {
        var candidates, hits, i, idx, sx, sy, vx, vy, _i, _j, _ref1, _ref2, _ref3, _results;
        _ref1 = [geometry.vx, geometry.vy], vx = _ref1[0], vy = _ref1[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 _i = 0, _ref2 = this.sx.length; 0 <= _ref2 ? _i < _ref2 : _i > _ref2; 0 <= _ref2 ? _i++ : _i--){ _results.push(_i); }
          return _results;
        }).apply(this);
        hits = [];
        for (i = _j = 0, _ref3 = candidates.length; 0 <= _ref3 ? _j < _ref3 : _j > _ref3; i = 0 <= _ref3 ? ++_j : --_j) {
          idx = candidates[i];
          if (point_in_poly(this.sx[i], this.sy[i], sx, sy)) {
            hits.push(idx);
          }
        }
        return hits;
      };

      return MarkerView;

    })(Glyph.View);
    Marker = (function(_super) {
      __extends(Marker, _super);

      function Marker() {
        _ref1 = Marker.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Marker.prototype.display_defaults = function() {
        return _.extend({}, Marker.__super__.display_defaults.call(this), {
          size: 4
        });
      };

      return Marker;

    })(Glyph.Model);
    Markers = (function(_super) {
      __extends(Markers, _super);

      function Markers() {
        _ref2 = Markers.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      return Markers;

    })(Glyph.Collection);
    return {
      Model: Marker,
      View: MarkerView,
      Collection: Markers
    };
  });

}).call(this);

/*
//@ sourceMappingURL=marker.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/marker/asterisk',["underscore", "./marker"], function(_, Marker) {
    var Asterisk, AsteriskView, Asterisks, _ref, _ref1, _ref2;
    AsteriskView = (function(_super) {
      __extends(AsteriskView, _super);

      function AsteriskView() {
        _ref = AsteriskView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      AsteriskView.prototype._properties = ['line'];

      AsteriskView.prototype._render = function(ctx, indices, sx, sy, size) {
        var i, r, r2, _i, _len, _results;
        if (sx == null) {
          sx = this.sx;
        }
        if (sy == null) {
          sy = this.sy;
        }
        if (size == null) {
          size = this.size;
        }
        _results = [];
        for (_i = 0, _len = indices.length; _i < _len; _i++) {
          i = indices[_i];
          if (isNaN(sx[i] + sy[i] + size[i])) {
            continue;
          }
          r = size[i] / 2;
          r2 = r * 0.65;
          ctx.beginPath();
          ctx.moveTo(sx[i], sy[i] + r);
          ctx.lineTo(sx[i], sy[i] - r);
          ctx.moveTo(sx[i] - r, sy[i]);
          ctx.lineTo(sx[i] + r, sy[i]);
          ctx.moveTo(sx[i] - r2, sy[i] + r2);
          ctx.lineTo(sx[i] + r2, sy[i] - r2);
          ctx.moveTo(sx[i] - r2, sy[i] - r2);
          ctx.lineTo(sx[i] + r2, sy[i] + r2);
          if (this.props.line.do_stroke) {
            this.props.line.set_vectorize(ctx, i);
            _results.push(ctx.stroke());
          } else {
            _results.push(void 0);
          }
        }
        return _results;
      };

      return AsteriskView;

    })(Marker.View);
    Asterisk = (function(_super) {
      __extends(Asterisk, _super);

      function Asterisk() {
        _ref1 = Asterisk.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Asterisk.prototype.default_view = AsteriskView;

      Asterisk.prototype.type = 'Asterisk';

      Asterisk.prototype.display_defaults = function() {
        return _.extend({}, Asterisk.__super__.display_defaults.call(this), this.line_defaults);
      };

      return Asterisk;

    })(Marker.Model);
    Asterisks = (function(_super) {
      __extends(Asterisks, _super);

      function Asterisks() {
        _ref2 = Asterisks.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Asterisks.prototype.model = Asterisk;

      return Asterisks;

    })(Marker.Collection);
    return {
      Model: Asterisk,
      View: AsteriskView,
      Collection: new Asterisks()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=asterisk.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/marker/circle_cross',["underscore", "./marker"], function(_, Marker) {
    var CircleCross, CircleCrossView, CircleCrosses, _ref, _ref1, _ref2;
    CircleCrossView = (function(_super) {
      __extends(CircleCrossView, _super);

      function CircleCrossView() {
        _ref = CircleCrossView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      CircleCrossView.prototype._properties = ['line', 'fill'];

      CircleCrossView.prototype._render = function(ctx, indices, sx, sy, size) {
        var i, r, _i, _len, _results;
        if (sx == null) {
          sx = this.sx;
        }
        if (sy == null) {
          sy = this.sy;
        }
        if (size == null) {
          size = this.size;
        }
        _results = [];
        for (_i = 0, _len = indices.length; _i < _len; _i++) {
          i = indices[_i];
          if (isNaN(sx[i] + sy[i] + size[i])) {
            continue;
          }
          ctx.beginPath();
          r = size[i] / 2;
          ctx.arc(sx[i], sy[i], r, 0, 2 * Math.PI, false);
          if (this.props.fill.do_fill) {
            this.props.fill.set_vectorize(ctx, i);
            ctx.fill();
          }
          if (this.props.line.do_stroke) {
            this.props.line.set_vectorize(ctx, i);
            ctx.moveTo(sx[i], sy[i] + r);
            ctx.lineTo(sx[i], sy[i] - r);
            ctx.moveTo(sx[i] - r, sy[i]);
            ctx.lineTo(sx[i] + r, sy[i]);
            _results.push(ctx.stroke());
          } else {
            _results.push(void 0);
          }
        }
        return _results;
      };

      return CircleCrossView;

    })(Marker.View);
    CircleCross = (function(_super) {
      __extends(CircleCross, _super);

      function CircleCross() {
        _ref1 = CircleCross.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      CircleCross.prototype.default_view = CircleCrossView;

      CircleCross.prototype.type = 'CircleCross';

      CircleCross.prototype.display_defaults = function() {
        return _.extend({}, CircleCross.__super__.display_defaults.call(this), this.line_defaults, this.fill_defaults);
      };

      return CircleCross;

    })(Marker.Model);
    CircleCrosses = (function(_super) {
      __extends(CircleCrosses, _super);

      function CircleCrosses() {
        _ref2 = CircleCrosses.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      CircleCrosses.prototype.model = CircleCross;

      return CircleCrosses;

    })(Marker.Collection);
    return {
      Model: CircleCross,
      View: CircleCrossView,
      Collection: new CircleCrosses()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=circle_cross.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/marker/circle_x',["underscore", "./marker"], function(_, Marker) {
    var CircleX, CircleXView, CircleXs, _ref, _ref1, _ref2;
    CircleXView = (function(_super) {
      __extends(CircleXView, _super);

      function CircleXView() {
        _ref = CircleXView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      CircleXView.prototype._properties = ['line', 'fill'];

      CircleXView.prototype._render = function(ctx, indices, sx, sy, size) {
        var i, r, _i, _len, _results;
        if (sx == null) {
          sx = this.sx;
        }
        if (sy == null) {
          sy = this.sy;
        }
        if (size == null) {
          size = this.size;
        }
        _results = [];
        for (_i = 0, _len = indices.length; _i < _len; _i++) {
          i = indices[_i];
          if (isNaN(sx[i] + sy[i] + size[i])) {
            continue;
          }
          ctx.beginPath();
          r = size[i] / 2;
          ctx.arc(sx[i], sy[i], r, 0, 2 * Math.PI, false);
          if (this.props.fill.do_fill) {
            this.props.fill.set_vectorize(ctx, i);
            ctx.fill();
          }
          if (this.props.line.do_stroke) {
            this.props.line.set_vectorize(ctx, i);
            ctx.moveTo(sx[i] - r, sy[i] + r);
            ctx.lineTo(sx[i] + r, sy[i] - r);
            ctx.moveTo(sx[i] - r, sy[i] - r);
            ctx.lineTo(sx[i] + r, sy[i] + r);
            _results.push(ctx.stroke());
          } else {
            _results.push(void 0);
          }
        }
        return _results;
      };

      return CircleXView;

    })(Marker.View);
    CircleX = (function(_super) {
      __extends(CircleX, _super);

      function CircleX() {
        _ref1 = CircleX.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      CircleX.prototype.default_view = CircleXView;

      CircleX.prototype.type = 'CircleX';

      CircleX.prototype.display_defaults = function() {
        return _.extend({}, CircleX.__super__.display_defaults.call(this), this.line_defaults, this.fill_defaults);
      };

      return CircleX;

    })(Marker.Model);
    CircleXs = (function(_super) {
      __extends(CircleXs, _super);

      function CircleXs() {
        _ref2 = CircleXs.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      CircleXs.prototype.model = CircleX;

      return CircleXs;

    })(Marker.Collection);
    return {
      Model: CircleX,
      View: CircleXView,
      Collection: new CircleXs()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=circle_x.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/marker/cross',["underscore", "./marker"], function(_, Marker) {
    var Cross, CrossView, Crosses, _ref, _ref1, _ref2;
    CrossView = (function(_super) {
      __extends(CrossView, _super);

      function CrossView() {
        _ref = CrossView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      CrossView.prototype._properties = ['line'];

      CrossView.prototype._render = function(ctx, indices, sx, sy, size) {
        var i, r, _i, _len, _results;
        if (sx == null) {
          sx = this.sx;
        }
        if (sy == null) {
          sy = this.sy;
        }
        if (size == null) {
          size = this.size;
        }
        _results = [];
        for (_i = 0, _len = indices.length; _i < _len; _i++) {
          i = indices[_i];
          if (isNaN(sx[i] + sy[i] + size[i])) {
            continue;
          }
          r = size[i] / 2;
          ctx.beginPath();
          ctx.moveTo(sx[i], sy[i] + r);
          ctx.lineTo(sx[i], sy[i] - r);
          ctx.moveTo(sx[i] - r, sy[i]);
          ctx.lineTo(sx[i] + r, sy[i]);
          if (this.props.line.do_stroke) {
            this.props.line.set_vectorize(ctx, i);
            _results.push(ctx.stroke());
          } else {
            _results.push(void 0);
          }
        }
        return _results;
      };

      return CrossView;

    })(Marker.View);
    Cross = (function(_super) {
      __extends(Cross, _super);

      function Cross() {
        _ref1 = Cross.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Cross.prototype.default_view = CrossView;

      Cross.prototype.type = 'Cross';

      Cross.prototype.display_defaults = function() {
        return _.extend({}, Cross.__super__.display_defaults.call(this), this.line_defaults);
      };

      return Cross;

    })(Marker.Model);
    Crosses = (function(_super) {
      __extends(Crosses, _super);

      function Crosses() {
        _ref2 = Crosses.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Crosses.prototype.model = Cross;

      return Crosses;

    })(Marker.Collection);
    return {
      Model: Cross,
      View: CrossView,
      Collection: new Crosses()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=cross.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/marker/diamond',["underscore", "./marker"], function(_, Marker) {
    var Diamond, DiamondView, Diamonds, _ref, _ref1, _ref2;
    DiamondView = (function(_super) {
      __extends(DiamondView, _super);

      function DiamondView() {
        _ref = DiamondView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      DiamondView.prototype._properties = ['line', 'fill'];

      DiamondView.prototype._render = function(ctx, indices, sx, sy, size) {
        var i, r, _i, _len, _results;
        if (sx == null) {
          sx = this.sx;
        }
        if (sy == null) {
          sy = this.sy;
        }
        if (size == null) {
          size = this.size;
        }
        _results = [];
        for (_i = 0, _len = indices.length; _i < _len; _i++) {
          i = indices[_i];
          if (isNaN(sx[i] + sy[i] + size[i])) {
            continue;
          }
          r = size[i] / 2;
          ctx.beginPath();
          ctx.moveTo(sx[i], sy[i] + r);
          ctx.lineTo(sx[i] + r, sy[i]);
          ctx.lineTo(sx[i], sy[i] - r);
          ctx.lineTo(sx[i] - r, sy[i]);
          ctx.closePath();
          if (this.props.fill.do_fill) {
            this.props.fill.set_vectorize(ctx, i);
            ctx.fill();
          }
          if (this.props.line.do_stroke) {
            this.props.line.set_vectorize(ctx, i);
            _results.push(ctx.stroke());
          } else {
            _results.push(void 0);
          }
        }
        return _results;
      };

      return DiamondView;

    })(Marker.View);
    Diamond = (function(_super) {
      __extends(Diamond, _super);

      function Diamond() {
        _ref1 = Diamond.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Diamond.prototype.default_view = DiamondView;

      Diamond.prototype.type = 'Diamond';

      Diamond.prototype.display_defaults = function() {
        return _.extend({}, Diamond.__super__.display_defaults.call(this), this.line_defaults, this.fill_defaults);
      };

      return Diamond;

    })(Marker.Model);
    Diamonds = (function(_super) {
      __extends(Diamonds, _super);

      function Diamonds() {
        _ref2 = Diamonds.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Diamonds.prototype.model = Diamond;

      return Diamonds;

    })(Marker.Collection);
    return {
      Model: Diamond,
      View: DiamondView,
      Collection: new Diamonds()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=diamond.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/marker/diamond_cross',["underscore", "./marker"], function(_, Marker) {
    var DiamondCross, DiamondCrossView, DiamondCrosses, _ref, _ref1, _ref2;
    DiamondCrossView = (function(_super) {
      __extends(DiamondCrossView, _super);

      function DiamondCrossView() {
        _ref = DiamondCrossView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      DiamondCrossView.prototype._properties = ['line', 'fill'];

      DiamondCrossView.prototype._render = function(ctx, indices, sx, sy, size) {
        var i, r, _i, _len, _results;
        if (sx == null) {
          sx = this.sx;
        }
        if (sy == null) {
          sy = this.sy;
        }
        if (size == null) {
          size = this.size;
        }
        _results = [];
        for (_i = 0, _len = indices.length; _i < _len; _i++) {
          i = indices[_i];
          if (isNaN(sx[i] + sy[i] + size[i])) {
            continue;
          }
          r = size[i] / 2;
          ctx.beginPath();
          ctx.moveTo(sx[i], sy[i] + r);
          ctx.lineTo(sx[i] + r, sy[i]);
          ctx.lineTo(sx[i], sy[i] - r);
          ctx.lineTo(sx[i] - r, sy[i]);
          ctx.closePath();
          if (this.props.fill.do_fill) {
            this.props.fill.set_vectorize(ctx, i);
            ctx.fill();
          }
          if (this.props.line.do_stroke) {
            this.props.line.set_vectorize(ctx, i);
            ctx.moveTo(sx[i], sy[i] + r);
            ctx.lineTo(sx[i], sy[i] - r);
            ctx.moveTo(sx[i] - r, sy[i]);
            ctx.lineTo(sx[i] + r, sy[i]);
            _results.push(ctx.stroke());
          } else {
            _results.push(void 0);
          }
        }
        return _results;
      };

      return DiamondCrossView;

    })(Marker.View);
    DiamondCross = (function(_super) {
      __extends(DiamondCross, _super);

      function DiamondCross() {
        _ref1 = DiamondCross.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      DiamondCross.prototype.default_view = DiamondCrossView;

      DiamondCross.prototype.type = 'DiamondCross';

      DiamondCross.prototype.display_defaults = function() {
        return _.extend({}, DiamondCross.__super__.display_defaults.call(this), this.line_defaults, this.fill_defaults);
      };

      return DiamondCross;

    })(Marker.Model);
    DiamondCrosses = (function(_super) {
      __extends(DiamondCrosses, _super);

      function DiamondCrosses() {
        _ref2 = DiamondCrosses.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      DiamondCrosses.prototype.model = DiamondCross;

      return DiamondCrosses;

    })(Marker.Collection);
    return {
      Model: DiamondCross,
      View: DiamondCrossView,
      Collection: new DiamondCrosses()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=diamond_cross.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/marker/inverted_triangle',["underscore", "./marker"], function(_, Marker) {
    var InvertedTriangle, InvertedTriangleView, InvertedTriangles, _ref, _ref1, _ref2;
    InvertedTriangleView = (function(_super) {
      __extends(InvertedTriangleView, _super);

      function InvertedTriangleView() {
        _ref = InvertedTriangleView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      InvertedTriangleView.prototype._properties = ['line', 'fill'];

      InvertedTriangleView.prototype._render = function(ctx, indices, sx, sy, size) {
        var a, h, i, r, _i, _len, _results;
        if (sx == null) {
          sx = this.sx;
        }
        if (sy == null) {
          sy = this.sy;
        }
        if (size == null) {
          size = this.size;
        }
        _results = [];
        for (_i = 0, _len = indices.length; _i < _len; _i++) {
          i = indices[_i];
          if (isNaN(sx[i] + sy[i] + size[i])) {
            continue;
          }
          a = size[i] * Math.sqrt(3) / 6;
          r = size[i] / 2;
          h = size[i] * Math.sqrt(3) / 2;
          ctx.beginPath();
          ctx.moveTo(sx[i] - r, sy[i] - a);
          ctx.lineTo(sx[i] + r, sy[i] - a);
          ctx.lineTo(sx[i], sy[i] - a + h);
          ctx.closePath();
          if (this.props.fill.do_fill) {
            this.props.fill.set_vectorize(ctx, i);
            ctx.fill();
          }
          if (this.props.line.do_stroke) {
            this.props.line.set_vectorize(ctx, i);
            _results.push(ctx.stroke());
          } else {
            _results.push(void 0);
          }
        }
        return _results;
      };

      return InvertedTriangleView;

    })(Marker.View);
    InvertedTriangle = (function(_super) {
      __extends(InvertedTriangle, _super);

      function InvertedTriangle() {
        _ref1 = InvertedTriangle.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      InvertedTriangle.prototype.default_view = InvertedTriangleView;

      InvertedTriangle.prototype.type = 'InvertedTriangle';

      InvertedTriangle.prototype.display_defaults = function() {
        return _.extend({}, InvertedTriangle.__super__.display_defaults.call(this), this.line_defaults, this.fill_defaults);
      };

      return InvertedTriangle;

    })(Marker.Model);
    InvertedTriangles = (function(_super) {
      __extends(InvertedTriangles, _super);

      function InvertedTriangles() {
        _ref2 = InvertedTriangles.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      InvertedTriangles.prototype.model = InvertedTriangle;

      return InvertedTriangles;

    })(Marker.Collection);
    return {
      Model: InvertedTriangle,
      View: InvertedTriangleView,
      Collection: new InvertedTriangles()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=inverted_triangle.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/marker/square',["underscore", "./marker"], function(_, Marker) {
    var Square, SquareView, Squares, _ref, _ref1, _ref2;
    SquareView = (function(_super) {
      __extends(SquareView, _super);

      function SquareView() {
        _ref = SquareView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      SquareView.prototype._properties = ['line', 'fill'];

      SquareView.prototype._render = function(ctx, indices, sx, sy, size) {
        var i, _i, _len, _results;
        if (sx == null) {
          sx = this.sx;
        }
        if (sy == null) {
          sy = this.sy;
        }
        if (size == null) {
          size = this.size;
        }
        _results = [];
        for (_i = 0, _len = indices.length; _i < _len; _i++) {
          i = indices[_i];
          if (isNaN(sx[i] + sy[i] + size[i])) {
            continue;
          }
          ctx.translate(sx[i], sy[i]);
          ctx.beginPath();
          ctx.rect(-size[i] / 2, -size[i] / 2, size[i], size[i]);
          if (this.props.fill.do_fill) {
            this.props.fill.set_vectorize(ctx, i);
            ctx.fill();
          }
          if (this.props.line.do_stroke) {
            this.props.line.set_vectorize(ctx, i);
            ctx.stroke();
          }
          _results.push(ctx.translate(-sx[i], -sy[i]));
        }
        return _results;
      };

      return SquareView;

    })(Marker.View);
    Square = (function(_super) {
      __extends(Square, _super);

      function Square() {
        _ref1 = Square.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Square.prototype.default_view = SquareView;

      Square.prototype.type = 'Square';

      Square.prototype.display_defaults = function() {
        return _.extend({}, Square.__super__.display_defaults.call(this), this.line_defaults, this.fill_defaults);
      };

      return Square;

    })(Marker.Model);
    Squares = (function(_super) {
      __extends(Squares, _super);

      function Squares() {
        _ref2 = Squares.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Squares.prototype.model = Square;

      return Squares;

    })(Marker.Collection);
    return {
      Model: Square,
      View: SquareView,
      Collection: new Squares()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=square.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/marker/square_cross',["underscore", "./marker"], function(_, Marker) {
    var SquareCross, SquareCrossView, SquareCrosses, _ref, _ref1, _ref2;
    SquareCrossView = (function(_super) {
      __extends(SquareCrossView, _super);

      function SquareCrossView() {
        _ref = SquareCrossView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      SquareCrossView.prototype._properties = ['line', 'fill'];

      SquareCrossView.prototype._render = function(ctx, indices, sx, sy, size) {
        var i, r, _i, _len, _results;
        if (sx == null) {
          sx = this.sx;
        }
        if (sy == null) {
          sy = this.sy;
        }
        if (size == null) {
          size = this.size;
        }
        _results = [];
        for (_i = 0, _len = indices.length; _i < _len; _i++) {
          i = indices[_i];
          if (isNaN(sx[i] + sy[i] + size[i])) {
            continue;
          }
          ctx.translate(sx[i], sy[i]);
          ctx.beginPath();
          ctx.rect(-size[i] / 2, -size[i] / 2, size[i], size[i]);
          if (this.props.fill.do_fill) {
            this.props.fill.set_vectorize(ctx, i);
            ctx.fill();
          }
          if (this.props.line.do_stroke) {
            this.props.line.set_vectorize(ctx, i);
            r = size[i] / 2;
            ctx.moveTo(0, +r);
            ctx.lineTo(0, -r);
            ctx.moveTo(-r, 0);
            ctx.lineTo(+r, 0);
            ctx.stroke();
          }
          _results.push(ctx.translate(-sx[i], -sy[i]));
        }
        return _results;
      };

      return SquareCrossView;

    })(Marker.View);
    SquareCross = (function(_super) {
      __extends(SquareCross, _super);

      function SquareCross() {
        _ref1 = SquareCross.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      SquareCross.prototype.default_view = SquareCrossView;

      SquareCross.prototype.type = 'SquareCross';

      SquareCross.prototype.display_defaults = function() {
        return _.extend({}, SquareCross.__super__.display_defaults.call(this), this.line_defaults, this.fill_defaults);
      };

      return SquareCross;

    })(Marker.Model);
    SquareCrosses = (function(_super) {
      __extends(SquareCrosses, _super);

      function SquareCrosses() {
        _ref2 = SquareCrosses.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      SquareCrosses.prototype.model = SquareCross;

      return SquareCrosses;

    })(Marker.Collection);
    return {
      Model: SquareCross,
      View: SquareCrossView,
      Collection: new SquareCrosses()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=square_cross.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/marker/square_x',["underscore", "./marker"], function(_, Marker) {
    var SquareX, SquareXView, SquareXs, _ref, _ref1, _ref2;
    SquareXView = (function(_super) {
      __extends(SquareXView, _super);

      function SquareXView() {
        _ref = SquareXView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      SquareXView.prototype._properties = ['line', 'fill'];

      SquareXView.prototype._render = function(ctx, indices, sx, sy, size) {
        var i, r, _i, _len, _results;
        if (sx == null) {
          sx = this.sx;
        }
        if (sy == null) {
          sy = this.sy;
        }
        if (size == null) {
          size = this.size;
        }
        _results = [];
        for (_i = 0, _len = indices.length; _i < _len; _i++) {
          i = indices[_i];
          if (isNaN(sx[i] + sy[i] + size[i])) {
            continue;
          }
          ctx.translate(sx[i], sy[i]);
          ctx.beginPath();
          ctx.rect(-size[i] / 2, -size[i] / 2, size[i], size[i]);
          if (this.props.fill.do_fill) {
            this.props.fill.set_vectorize(ctx, i);
            ctx.fill();
          }
          if (this.props.line.do_stroke) {
            this.props.line.set_vectorize(ctx, i);
            ctx.stroke();
            r = size[i] / 2;
            ctx.moveTo(-r, +r);
            ctx.lineTo(+r, -r);
            ctx.moveTo(-r, -r);
            ctx.lineTo(+r, +r);
            ctx.stroke();
          }
          _results.push(ctx.translate(-sx[i], -sy[i]));
        }
        return _results;
      };

      return SquareXView;

    })(Marker.View);
    SquareX = (function(_super) {
      __extends(SquareX, _super);

      function SquareX() {
        _ref1 = SquareX.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      SquareX.prototype.default_view = SquareXView;

      SquareX.prototype.type = 'SquareX';

      SquareX.prototype.display_defaults = function() {
        return _.extend({}, SquareX.__super__.display_defaults.call(this), this.line_defaults, this.fill_defaults);
      };

      return SquareX;

    })(Marker.Model);
    SquareXs = (function(_super) {
      __extends(SquareXs, _super);

      function SquareXs() {
        _ref2 = SquareXs.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      SquareXs.prototype.model = SquareX;

      return SquareXs;

    })(Marker.Collection);
    return {
      Model: SquareX,
      View: SquareXView,
      Collection: new SquareXs()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=square_x.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/marker/triangle',["underscore", "./marker"], function(_, Marker) {
    var Triangle, TriangleView, Triangles, _ref, _ref1, _ref2;
    TriangleView = (function(_super) {
      __extends(TriangleView, _super);

      function TriangleView() {
        _ref = TriangleView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      TriangleView.prototype._properties = ['line', 'fill'];

      TriangleView.prototype._render = function(ctx, indices, sx, sy, size) {
        var a, h, i, r, _i, _len, _results;
        if (sx == null) {
          sx = this.sx;
        }
        if (sy == null) {
          sy = this.sy;
        }
        if (size == null) {
          size = this.size;
        }
        _results = [];
        for (_i = 0, _len = indices.length; _i < _len; _i++) {
          i = indices[_i];
          if (isNaN(sx[i] + sy[i] + size[i])) {
            continue;
          }
          a = size[i] * Math.sqrt(3) / 6;
          r = size[i] / 2;
          h = size[i] * Math.sqrt(3) / 2;
          ctx.beginPath();
          ctx.moveTo(sx[i] - r, sy[i] + a);
          ctx.lineTo(sx[i] + r, sy[i] + a);
          ctx.lineTo(sx[i], sy[i] + a - h);
          ctx.closePath();
          if (this.props.fill.do_fill) {
            this.props.fill.set_vectorize(ctx, i);
            ctx.fill();
          }
          if (this.props.line.do_stroke) {
            this.props.line.set_vectorize(ctx, i);
            _results.push(ctx.stroke());
          } else {
            _results.push(void 0);
          }
        }
        return _results;
      };

      return TriangleView;

    })(Marker.View);
    Triangle = (function(_super) {
      __extends(Triangle, _super);

      function Triangle() {
        _ref1 = Triangle.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Triangle.prototype.default_view = TriangleView;

      Triangle.prototype.type = 'Triangle';

      Triangle.prototype.display_defaults = function() {
        return _.extend({}, Triangle.__super__.display_defaults.call(this), this.line_defaults, this.fill_defaults);
      };

      return Triangle;

    })(Marker.Model);
    Triangles = (function(_super) {
      __extends(Triangles, _super);

      function Triangles() {
        _ref2 = Triangles.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Triangles.prototype.model = Triangle;

      return Triangles;

    })(Marker.Collection);
    return {
      Model: Triangle,
      View: TriangleView,
      Collection: new Triangles()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=triangle.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/glyph/marker/x',["underscore", "./marker"], function(_, Marker) {
    var X, XView, Xs, _ref, _ref1, _ref2;
    XView = (function(_super) {
      __extends(XView, _super);

      function XView() {
        _ref = XView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      XView.prototype._properties = ['line'];

      XView.prototype._render = function(ctx, indices, sx, sy, size) {
        var i, r, _i, _len, _results;
        if (sx == null) {
          sx = this.sx;
        }
        if (sy == null) {
          sy = this.sy;
        }
        if (size == null) {
          size = this.size;
        }
        _results = [];
        for (_i = 0, _len = indices.length; _i < _len; _i++) {
          i = indices[_i];
          if (isNaN(sx[i] + sy[i] + size[i])) {
            continue;
          }
          r = size[i] / 2;
          ctx.beginPath();
          ctx.moveTo(sx[i] - r, sy[i] + r);
          ctx.lineTo(sx[i] + r, sy[i] - r);
          ctx.moveTo(sx[i] - r, sy[i] - r);
          ctx.lineTo(sx[i] + r, sy[i] + r);
          if (this.props.line.do_stroke) {
            this.props.line.set_vectorize(ctx, i);
            _results.push(ctx.stroke());
          } else {
            _results.push(void 0);
          }
        }
        return _results;
      };

      return XView;

    })(Marker.View);
    X = (function(_super) {
      __extends(X, _super);

      function X() {
        _ref1 = X.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      X.prototype.default_view = XView;

      X.prototype.type = 'X';

      X.prototype.display_defaults = function() {
        return _.extend({}, X.__super__.display_defaults.call(this), this.line_defaults);
      };

      return X;

    })(Marker.Model);
    Xs = (function(_super) {
      __extends(Xs, _super);

      function Xs() {
        _ref2 = Xs.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Xs.prototype.model = X;

      return Xs;

    })(Marker.Collection);
    return {
      Model: X,
      View: XView,
      Collection: new Xs()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=x.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/guide/axis',["underscore", "kiwi", "common/has_parent", "common/layout_box", "common/logging", "common/plot_widget", "renderer/properties"], function(_, kiwi, HasParent, LayoutBox, Logging, PlotWidget, properties) {
    var ALPHABETIC, Axis, AxisView, CENTER, HANGING, LEFT, MIDDLE, RIGHT, logger, pi2, _align_lookup, _align_lookup_negative, _align_lookup_positive, _angle_lookup, _apply_location_heuristics, _baseline_lookup, _ref, _ref1;
    logger = Logging.logger;
    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(_super) {
      __extends(AxisView, _super);

      function AxisView() {
        _ref = AxisView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      AxisView.prototype.initialize = function(options) {
        AxisView.__super__.initialize.call(this, options);
        this.rule_props = new properties.Line(this, 'axis_');
        this.major_tick_props = new properties.Line(this, 'major_tick_');
        this.minor_tick_props = new properties.Line(this, 'minor_tick_');
        this.major_label_props = new properties.Text(this, 'major_label_');
        this.axis_label_props = new properties.Text(this, '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, nx, ny, sx, sy, x, xoff, y, yoff, _i, _ref1, _ref2, _ref3, _ref4, _ref5;
        if (!this.rule_props.do_stroke) {
          return;
        }
        _ref1 = coords = this.mget('rule_coords'), x = _ref1[0], y = _ref1[1];
        _ref2 = this.plot_view.map_to_screen(x, "data", y, "data", this.x_range_name, this.y_range_name), sx = _ref2[0], sy = _ref2[1];
        _ref3 = this.mget('normals'), nx = _ref3[0], ny = _ref3[1];
        _ref4 = this.mget('offsets'), xoff = _ref4[0], yoff = _ref4[1];
        this.rule_props.set(ctx, this);
        ctx.beginPath();
        ctx.moveTo(Math.round(sx[0] + nx * xoff), Math.round(sy[0] + ny * yoff));
        for (i = _i = 1, _ref5 = sx.length; 1 <= _ref5 ? _i < _ref5 : _i > _ref5; i = 1 <= _ref5 ? ++_i : --_i) {
          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, nx, ny, sx, sy, tin, tout, x, xoff, y, yoff, _i, _ref1, _ref2, _ref3, _ref4, _ref5, _results;
        if (!this.major_tick_props.do_stroke) {
          return;
        }
        coords = this.mget('tick_coords');
        _ref1 = coords.major, x = _ref1[0], y = _ref1[1];
        _ref2 = this.plot_view.map_to_screen(x, "data", y, "data", this.x_range_name, this.y_range_name), sx = _ref2[0], sy = _ref2[1];
        _ref3 = this.mget('normals'), nx = _ref3[0], ny = _ref3[1];
        _ref4 = this.mget('offsets'), xoff = _ref4[0], yoff = _ref4[1];
        tin = this.mget('major_tick_in');
        tout = this.mget('major_tick_out');
        this.major_tick_props.set(ctx, this);
        _results = [];
        for (i = _i = 0, _ref5 = sx.length; 0 <= _ref5 ? _i < _ref5 : _i > _ref5; i = 0 <= _ref5 ? ++_i : --_i) {
          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, nx, ny, sx, sy, tin, tout, x, xoff, y, yoff, _i, _ref1, _ref2, _ref3, _ref4, _ref5, _results;
        if (!this.minor_tick_props.do_stroke) {
          return;
        }
        coords = this.mget('tick_coords');
        _ref1 = coords.minor, x = _ref1[0], y = _ref1[1];
        _ref2 = this.plot_view.map_to_screen(x, "data", y, "data", this.x_range_name, this.y_range_name), sx = _ref2[0], sy = _ref2[1];
        _ref3 = this.mget('normals'), nx = _ref3[0], ny = _ref3[1];
        _ref4 = this.mget('offsets'), xoff = _ref4[0], yoff = _ref4[1];
        tin = this.mget('minor_tick_in');
        tout = this.mget('minor_tick_out');
        this.minor_tick_props.set(ctx, this);
        _results = [];
        for (i = _i = 0, _ref5 = sx.length; 0 <= _ref5 ? _i < _ref5 : _i > _ref5; i = 0 <= _ref5 ? ++_i : --_i) {
          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, labels, nx, ny, orient, side, standoff, sx, sy, x, xoff, y, yoff, _i, _ref1, _ref2, _ref3, _ref4, _ref5, _results;
        coords = this.mget('tick_coords');
        _ref1 = coords.major, x = _ref1[0], y = _ref1[1];
        _ref2 = this.plot_view.map_to_screen(x, "data", y, "data", this.x_range_name, this.y_range_name), sx = _ref2[0], sy = _ref2[1];
        _ref3 = this.mget('normals'), nx = _ref3[0], ny = _ref3[1];
        _ref4 = this.mget('offsets'), xoff = _ref4[0], yoff = _ref4[1];
        dim = this.mget('dimension');
        side = this.mget('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(ctx, this);
        _apply_location_heuristics(ctx, side, orient);
        _results = [];
        for (i = _i = 0, _ref5 = sx.length; 0 <= _ref5 ? _i < _ref5 : _i > _ref5; i = 0 <= _ref5 ? ++_i : --_i) {
          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, side, standoff, sx, sy, x, xoff, y, yoff, _ref1, _ref2, _ref3, _ref4;
        label = this.mget('axis_label');
        if (label == null) {
          return;
        }
        _ref1 = this.mget('rule_coords'), x = _ref1[0], y = _ref1[1];
        _ref2 = this.plot_view.map_to_screen(x, "data", y, "data", this.x_range_name, this.y_range_name), sx = _ref2[0], sy = _ref2[1];
        _ref3 = this.mget('normals'), nx = _ref3[0], ny = _ref3[1];
        _ref4 = this.mget('offsets'), xoff = _ref4[0], yoff = _ref4[1];
        side = this.mget('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(ctx, this);
        _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(_super) {
      __extends(Axis, _super);

      function Axis() {
        _ref1 = Axis.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      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', '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.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('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, side, xoff, yoff, _ref2;
        side = this.get('location');
        _ref2 = [0, 0], xoff = _ref2[0], yoff = _ref2[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, start, user_bounds, _ref2, _ref3;
        _ref2 = this.get('ranges'), range = _ref2[0], cross_range = _ref2[1];
        user_bounds = (_ref3 = this.get('bounds')) != null ? _ref3 : '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, start, xs, ys, _ref2, _ref3;
        i = this.get('dimension');
        j = (i + 1) % 2;
        _ref2 = this.get('ranges'), range = _ref2[0], cross_range = _ref2[1];
        _ref3 = this.get('computed_bounds'), start = _ref3[0], end = _ref3[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, loc, majors, minor_coords, minor_xs, minor_ys, minors, range, range_max, range_min, start, ticks, xs, ys, _i, _j, _k, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7;
        i = this.get('dimension');
        j = (i + 1) % 2;
        _ref2 = this.get('ranges'), range = _ref2[0], cross_range = _ref2[1];
        _ref3 = this.get('computed_bounds'), start = _ref3[0], end = _ref3[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 = _i = 0, _ref4 = majors.length; 0 <= _ref4 ? _i < _ref4 : _i > _ref4; ii = 0 <= _ref4 ? ++_i : --_i) {
            coords[i].push(majors[ii]);
            coords[j].push(loc);
          }
        } else {
          _ref5 = [range.get('min'), range.get('max')], range_min = _ref5[0], range_max = _ref5[1];
          for (ii = _j = 0, _ref6 = majors.length; 0 <= _ref6 ? _j < _ref6 : _j > _ref6; ii = 0 <= _ref6 ? ++_j : --_j) {
            if (majors[ii] < range_min || majors[ii] > range_max) {
              continue;
            }
            coords[i].push(majors[ii]);
            coords[j].push(loc);
          }
          for (ii = _k = 0, _ref7 = minors.length; 0 <= _ref7 ? _k < _ref7 : _k > _ref7; ii = 0 <= _ref7 ? ++_k : --_k) {
            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('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, labels, orient, s, side, val, w, wfactor, _i, _ref2;
        extent = 0;
        dim = this.get('dimension');
        ctx = view.plot_view.canvas_view.ctx;
        coords = this.get('tick_coords').major;
        side = this.get('location');
        orient = this.get('major_label_orientation');
        labels = this.get('formatter').format(coords[dim]);
        view.major_label_props.set(ctx, view);
        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 = _i = 0, _ref2 = labels.length; 0 <= _ref2 ? _i < _ref2 : _i > _ref2; i = 0 <= _ref2 ? ++_i : --_i) {
          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('location');
        orient = 'parallel';
        ctx = view.plot_view.canvas_view.ctx;
        view.axis_label_props.set(ctx, view);
        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(ctx, view);
          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), {
          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);
    return {
      "Model": Axis,
      "View": AxisView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=axis.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('ticking/categorical_ticker',["common/collection", "common/has_properties"], function(Collection, HasProperties) {
    var CategoricalTicker, CategoricalTickers, _ref, _ref1;
    CategoricalTicker = (function(_super) {
      __extends(CategoricalTicker, _super);

      function CategoricalTicker() {
        _ref = CategoricalTicker.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      CategoricalTicker.prototype.type = 'CategoricalTicker';

      CategoricalTicker.prototype.get_ticks = function(start, end, range, _arg) {
        var desired_n_ticks, factors, i, majors, _i, _ref1;
        desired_n_ticks = _arg.desired_n_ticks;
        majors = [];
        factors = range.get("factors");
        for (i = _i = 0, _ref1 = factors.length; 0 <= _ref1 ? _i < _ref1 : _i > _ref1; i = 0 <= _ref1 ? ++_i : --_i) {
          if ((i + 1) > start && (i + 1) < end) {
            majors.push(factors[i]);
          }
        }
        return {
          "major": majors,
          "minor": []
        };
      };

      return CategoricalTicker;

    })(HasProperties);
    CategoricalTickers = (function(_super) {
      __extends(CategoricalTickers, _super);

      function CategoricalTickers() {
        _ref1 = CategoricalTickers.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      CategoricalTickers.prototype.model = CategoricalTicker;

      return CategoricalTickers;

    })(Collection);
    return {
      "Model": CategoricalTicker,
      "Collection": new CategoricalTickers()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=categorical_ticker.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('ticking/categorical_tick_formatter',["common/collection", "common/has_properties"], function(Collection, HasProperties) {
    var CategoricalTickFormatter, CategoricalTickFormatters, _ref, _ref1;
    CategoricalTickFormatter = (function(_super) {
      __extends(CategoricalTickFormatter, _super);

      function CategoricalTickFormatter() {
        _ref = CategoricalTickFormatter.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      CategoricalTickFormatter.prototype.type = 'CategoricalTickFormatter';

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

      CategoricalTickFormatter.prototype.format = function(ticks) {
        return ticks;
      };

      return CategoricalTickFormatter;

    })(HasProperties);
    CategoricalTickFormatters = (function(_super) {
      __extends(CategoricalTickFormatters, _super);

      function CategoricalTickFormatters() {
        _ref1 = CategoricalTickFormatters.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      CategoricalTickFormatters.prototype.model = CategoricalTickFormatter;

      return CategoricalTickFormatters;

    })(Collection);
    return {
      "Model": CategoricalTickFormatter,
      "Collection": new CategoricalTickFormatters()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=categorical_tick_formatter.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/guide/categorical_axis',["common/collection", "./axis", "common/logging", "range/factor_range", "ticking/categorical_ticker", "ticking/categorical_tick_formatter"], function(Collection, Axis, Logging, FactorRange, CategoricalTicker, CategoricalTickFormatter) {
    var CategoricalAxes, CategoricalAxis, CategoricalAxisView, logger, _ref, _ref1, _ref2;
    logger = Logging.logger;
    CategoricalAxisView = (function(_super) {
      __extends(CategoricalAxisView, _super);

      function CategoricalAxisView() {
        _ref = CategoricalAxisView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      return CategoricalAxisView;

    })(Axis.View);
    CategoricalAxis = (function(_super) {
      __extends(CategoricalAxis, _super);

      function CategoricalAxis() {
        _ref1 = CategoricalAxis.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      CategoricalAxis.prototype.default_view = CategoricalAxisView;

      CategoricalAxis.prototype.type = 'CategoricalAxis';

      CategoricalAxis.prototype.initialize = function(attrs, objects) {
        CategoricalAxis.__super__.initialize.call(this, attrs, objects);
        if (this.get('ticker') == null) {
          this.set_obj('ticker', CategoricalTicker.Collection.create());
        }
        if (this.get('formatter') == null) {
          return this.set_obj('formatter', CategoricalTickFormatter.Collection.create());
        }
      };

      CategoricalAxis.prototype._computed_bounds = function() {
        var cross_range, range, range_bounds, user_bounds, _ref2, _ref3;
        _ref2 = this.get('ranges'), range = _ref2[0], cross_range = _ref2[1];
        user_bounds = (_ref3 = this.get('bounds')) != null ? _ref3 : '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);
    CategoricalAxes = (function(_super) {
      __extends(CategoricalAxes, _super);

      function CategoricalAxes() {
        _ref2 = CategoricalAxes.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      CategoricalAxes.prototype.model = CategoricalAxis;

      return CategoricalAxes;

    })(Collection);
    return {
      "Model": CategoricalAxis,
      "Collection": new CategoricalAxes(),
      "View": CategoricalAxisView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=categorical_axis.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('ticking/abstract_ticker',["underscore", "common/collection", "common/has_properties"], function(_, Collection, HasProperties) {
    var AbstractTicker, AbstractTickers, DEFAULT_DESIRED_N_TICKS, repr, _ref, _ref1;
    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 _i, _len, _results;
          _results = [];
          for (_i = 0, _len = obj.length; _i < _len; _i++) {
            elem = obj[_i];
            _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_N_TICKS = 6;
    AbstractTicker = (function(_super) {
      __extends(AbstractTicker, _super);

      function AbstractTicker() {
        _ref = AbstractTicker.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      AbstractTicker.prototype.type = 'AbstractTicker';

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

      AbstractTicker.prototype.get_ticks = function(data_low, data_high, range, _arg) {
        var desired_n_ticks;
        desired_n_ticks = _arg.desired_n_ticks;
        if (desired_n_ticks == null) {
          desired_n_ticks = DEFAULT_DESIRED_N_TICKS;
        }
        return this.get_ticks_no_defaults(data_low, data_high, desired_n_ticks);
      };

      AbstractTicker.prototype.get_ticks_no_defaults = function(data_low, data_high, desired_n_ticks) {
        var end_factor, factor, factors, i, interval, minor_interval, minor_offsets, minor_ticks, num_minor_ticks, start_factor, tick, ticks, x, _i, _j, _k, _len, _len1, _len2;
        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 _i, _len, _results;
          _results = [];
          for (_i = 0, _len = factors.length; _i < _len; _i++) {
            factor = factors[_i];
            _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 _i, _results;
            _results = [];
            for (i = _i = 1; 1 <= num_minor_ticks ? _i <= num_minor_ticks : _i >= num_minor_ticks; i = 1 <= num_minor_ticks ? ++_i : --_i) {
              _results.push(i * minor_interval);
            }
            return _results;
          })();
          for (_i = 0, _len = minor_offsets.length; _i < _len; _i++) {
            x = minor_offsets[_i];
            minor_ticks.push(ticks[0] - x);
          }
          for (_j = 0, _len1 = ticks.length; _j < _len1; _j++) {
            tick = ticks[_j];
            for (_k = 0, _len2 = minor_offsets.length; _k < _len2; _k++) {
              x = minor_offsets[_k];
              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 _i, _len, _results;
          _results = [];
          for (_i = 0, _len = props.length; _i < _len; _i++) {
            key = props[_i];
            _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
        });
      };

      return AbstractTicker;

    })(HasProperties);
    AbstractTickers = (function(_super) {
      __extends(AbstractTickers, _super);

      function AbstractTickers() {
        _ref1 = AbstractTickers.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      AbstractTickers.prototype.model = AbstractTicker;

      return AbstractTickers;

    })(Collection);
    return {
      "Model": AbstractTicker,
      "Collection": new AbstractTickers()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=abstract_ticker.js.map
*/;
(function() {
  define('ticking/util',["underscore"], function(_) {
    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;
    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;
    };
    return {
      "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
    };
  });

}).call(this);

/*
//@ sourceMappingURL=util.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('ticking/adaptive_ticker',["underscore", "common/collection", "ticking/abstract_ticker", "ticking/util"], function(_, Collection, AbstractTicker, util) {
    var AdaptiveTicker, AdaptiveTickers, argmin, clamp, log, _ref, _ref1;
    argmin = 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(_super) {
      __extends(AdaptiveTicker, _super);

      function AdaptiveTicker() {
        _ref = AdaptiveTicker.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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);
    AdaptiveTickers = (function(_super) {
      __extends(AdaptiveTickers, _super);

      function AdaptiveTickers() {
        _ref1 = AdaptiveTickers.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      AdaptiveTickers.prototype.model = AdaptiveTicker;

      return AdaptiveTickers;

    })(Collection);
    return {
      "Model": AdaptiveTicker,
      "Collection": new AdaptiveTickers()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=adaptive_ticker.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('ticking/composite_ticker',["underscore", "common/collection", "ticking/abstract_ticker", "ticking/util"], function(_, Collection, AbstractTicker, util) {
    var CompositeTicker, CompositeTickers, argmin, _ref, _ref1;
    argmin = util.argmin;
    CompositeTicker = (function(_super) {
      __extends(CompositeTicker, _super);

      function CompositeTicker() {
        _ref = CompositeTicker.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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);
    CompositeTickers = (function(_super) {
      __extends(CompositeTickers, _super);

      function CompositeTickers() {
        _ref1 = CompositeTickers.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      CompositeTickers.prototype.model = CompositeTicker;

      return CompositeTickers;

    })(Collection);
    return {
      "Model": CompositeTicker,
      "Collection": new CompositeTickers()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=composite_ticker.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('ticking/single_interval_ticker',["underscore", "common/collection", "ticking/abstract_ticker"], function(_, Collection, AbstractTicker) {
    var SingleIntervalTicker, SingleIntervalTickers, _ref, _ref1;
    SingleIntervalTicker = (function(_super) {
      __extends(SingleIntervalTicker, _super);

      function SingleIntervalTicker() {
        _ref = SingleIntervalTicker.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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);
    SingleIntervalTickers = (function(_super) {
      __extends(SingleIntervalTickers, _super);

      function SingleIntervalTickers() {
        _ref1 = SingleIntervalTickers.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      SingleIntervalTickers.prototype.model = SingleIntervalTicker;

      return SingleIntervalTickers;

    })(Collection);
    return {
      "Model": SingleIntervalTicker,
      "Collection": new SingleIntervalTickers()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=single_interval_ticker.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('ticking/days_ticker',["underscore", "common/collection", "ticking/single_interval_ticker", "ticking/util"], function(_, Collection, SingleIntervalTicker, util) {
    var DaysTicker, DaysTickers, ONE_DAY, copy_date, date_range_by_month, last_month_no_later_than, _ref, _ref1;
    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(_super) {
      __extends(DaysTicker, _super);

      function DaysTicker() {
        _ref = DaysTicker.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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,
          _this = this;
        month_dates = date_range_by_month(data_low, data_high);
        days = this.get('days');
        days_of_month = 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;
        };
        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);
    DaysTickers = (function(_super) {
      __extends(DaysTickers, _super);

      function DaysTickers() {
        _ref1 = DaysTickers.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      DaysTickers.prototype.model = DaysTicker;

      return DaysTickers;

    })(Collection);
    return {
      "Model": DaysTicker,
      "Collection": new DaysTickers()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=days_ticker.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('ticking/months_ticker',["underscore", "common/collection", "ticking/single_interval_ticker", "ticking/util"], function(_, Collection, SingleIntervalTicker, util) {
    var MonthsTicker, MonthsTickers, ONE_MONTH, copy_date, date_range_by_year, last_year_no_later_than, _ref, _ref1;
    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(_super) {
      __extends(MonthsTicker, _super);

      function MonthsTicker() {
        _ref = MonthsTicker.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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);
    MonthsTickers = (function(_super) {
      __extends(MonthsTickers, _super);

      function MonthsTickers() {
        _ref1 = MonthsTickers.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      MonthsTickers.prototype.model = MonthsTicker;

      return MonthsTickers;

    })(Collection);
    return {
      "Model": MonthsTicker,
      "Collection": new MonthsTickers()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=months_ticker.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('ticking/basic_ticker',["common/collection", "ticking/adaptive_ticker"], function(Collection, AdaptiveTicker) {
    var BasicTicker, BasicTickers, _ref, _ref1;
    BasicTicker = (function(_super) {
      __extends(BasicTicker, _super);

      function BasicTicker() {
        _ref = BasicTicker.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      BasicTicker.prototype.type = 'BasicTicker';

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

      BasicTicker.prototype.defaults = function() {
        return _.extend({}, BasicTicker.__super__.defaults.call(this), {
          mantissas: [1, 2, 5]
        });
      };

      return BasicTicker;

    })(AdaptiveTicker.Model);
    BasicTickers = (function(_super) {
      __extends(BasicTickers, _super);

      function BasicTickers() {
        _ref1 = BasicTickers.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      BasicTickers.prototype.model = BasicTicker;

      return BasicTickers;

    })(Collection);
    return {
      "Model": BasicTicker,
      "Collection": new BasicTickers()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=basic_ticker.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('ticking/years_ticker',["underscore", "common/collection", "ticking/basic_ticker", "ticking/single_interval_ticker", "ticking/util"], function(_, Collection, BasicTicker, SingleIntervalTicker, util) {
    var ONE_YEAR, YearsTicker, YearsTickers, last_year_no_later_than, _ref, _ref1;
    last_year_no_later_than = util.last_year_no_later_than;
    ONE_YEAR = util.ONE_YEAR;
    YearsTicker = (function(_super) {
      __extends(YearsTicker, _super);

      function YearsTicker() {
        _ref = YearsTicker.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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);
    YearsTickers = (function(_super) {
      __extends(YearsTickers, _super);

      function YearsTickers() {
        _ref1 = YearsTickers.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      YearsTickers.prototype.model = YearsTicker;

      return YearsTickers;

    })(Collection);
    return {
      "Model": YearsTicker,
      "Collection": new YearsTickers()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=years_ticker.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('ticking/datetime_ticker',["underscore", "common/collection", "ticking/adaptive_ticker", "ticking/composite_ticker", "ticking/days_ticker", "ticking/months_ticker", "ticking/years_ticker", "ticking/util"], function(_, Collection, AdaptiveTicker, CompositeTicker, DaysTicker, MonthsTicker, YearsTicker, util) {
    var DatetimeTicker, DatetimeTickers, ONE_HOUR, ONE_MILLI, ONE_MINUTE, ONE_MONTH, ONE_SECOND, _ref, _ref1;
    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(_super) {
      __extends(DatetimeTicker, _super);

      function DatetimeTicker() {
        _ref = DatetimeTicker.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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);
    DatetimeTickers = (function(_super) {
      __extends(DatetimeTickers, _super);

      function DatetimeTickers() {
        _ref1 = DatetimeTickers.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      DatetimeTickers.prototype.model = DatetimeTicker;

      return DatetimeTickers;

    })(Collection);
    return {
      "Model": DatetimeTicker,
      "Collection": new DatetimeTickers()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=datetime_ticker.js.map
*/;
!function (definition) {
  if (typeof module == "object" && module.exports) module.exports = definition();
  else if (typeof define == "function") define('timezone',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.23";

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

(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('ticking/datetime_tick_formatter',["underscore", "common/collection", "sprintf", "timezone", "common/has_properties", "common/logging"], function(_, Collection, sprintf, tz, HasProperties, Logging) {
    var DatetimeTickFormatter, DatetimeTickFormatters, logger, _array, _four_digit_year, _ms_dot_us, _ref, _ref1, _strftime, _two_digit_year, _us;
    logger = Logging.logger;
    _us = function(t) {
      return sprintf("%3dus", Math.floor((t % 1) * 1000));
    };
    _ms_dot_us = function(t) {
      var ms, us;
      ms = Math.floor(((t / 1000) % 1) * 1000);
      us = Math.floor((t % 1) * 1000);
      return sprintf("%3d.%3dms", ms, us);
    };
    _two_digit_year = function(t) {
      var dt, year;
      dt = new Date(t);
      year = dt.getFullYear();
      if (dt.getMonth() >= 7) {
        year += 1;
      }
      return 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("%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) {
      if (_.isFunction(format)) {
        return format(t);
      } else {
        return tz(t, format);
      }
    };
    DatetimeTickFormatter = (function(_super) {
      __extends(DatetimeTickFormatter, _super);

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

      DatetimeTickFormatter.prototype.type = 'DatetimeTickFormatter';

      DatetimeTickFormatter.prototype.format_order = ['microseconds', 'milliseconds', 'seconds', 'minsec', 'minutes', 'hourmin', 'hours', 'days', 'months', 'years'];

      DatetimeTickFormatter.prototype._formats = {
        'microseconds': [_us, _ms_dot_us],
        '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, sizes, sorted, _results;
        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 _i, _len, _results1;
            _results1 = [];
            for (_i = 0, _len = fmt_strings.length; _i < _len; _i++) {
              fmt_string = fmt_strings[_i];
              _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, fmt, format, formats, good_formats, hybrid_handled, i, labels, next_format, next_ndx, r, resol, resol_ndx, s, span, ss, t, time_tuple_ndx_for_resol, tm, widths, _i, _j, _k, _len, _len1, _ref1, _ref2, _ref3;
        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);
        _ref1 = this.formats[resol], widths = _ref1[0], formats = _ref1[1];
        format = formats[0];
        if (char_width) {
          good_formats = [];
          for (i = _i = 0, _ref2 = widths.length; 0 <= _ref2 ? _i < _ref2 : _i > _ref2; i = 0 <= _ref2 ? ++_i : --_i) {
            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 = {};
        _ref3 = this.format_order;
        for (_j = 0, _len = _ref3.length; _j < _len; _j++) {
          fmt = _ref3[_j];
          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 (_k = 0, _len1 = ticks.length; _k < _len1; _k++) {
          t = ticks[_k];
          try {
            tm = _array(t);
            s = _strftime(t, format);
          } catch (_error) {
            error = _error;
            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 && (ss === '' || !isFinite(ss[0]))) {
              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);
    DatetimeTickFormatters = (function(_super) {
      __extends(DatetimeTickFormatters, _super);

      function DatetimeTickFormatters() {
        _ref1 = DatetimeTickFormatters.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      DatetimeTickFormatters.prototype.model = DatetimeTickFormatter;

      return DatetimeTickFormatters;

    })(Collection);
    return {
      "Model": DatetimeTickFormatter,
      "Collection": new DatetimeTickFormatters()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=datetime_tick_formatter.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/guide/datetime_axis',["common/collection", "./axis", "ticking/datetime_ticker", "ticking/datetime_tick_formatter"], function(Collection, Axis, DatetimeTicker, DatetimeTickFormatter) {
    var DatetimeAxes, DatetimeAxis, DatetimeAxisView, _ref, _ref1, _ref2;
    DatetimeAxisView = (function(_super) {
      __extends(DatetimeAxisView, _super);

      function DatetimeAxisView() {
        _ref = DatetimeAxisView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      return DatetimeAxisView;

    })(Axis.View);
    DatetimeAxis = (function(_super) {
      __extends(DatetimeAxis, _super);

      function DatetimeAxis() {
        _ref1 = DatetimeAxis.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      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', DatetimeTicker.Collection.create());
        }
        if (this.get('formatter') == null) {
          return this.set_obj('formatter', DatetimeTickFormatter.Collection.create());
        }
      };

      return DatetimeAxis;

    })(Axis.Model);
    DatetimeAxes = (function(_super) {
      __extends(DatetimeAxes, _super);

      function DatetimeAxes() {
        _ref2 = DatetimeAxes.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      DatetimeAxes.prototype.model = DatetimeAxis;

      return DatetimeAxes;

    })(Collection);
    return {
      "Model": DatetimeAxis,
      "Collection": new DatetimeAxes(),
      "View": DatetimeAxisView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=datetime_axis.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/guide/grid',["underscore", "common/has_parent", "common/collection", "renderer/properties", "common/plot_widget"], function(_, HasParent, Collection, properties, PlotWidget) {
    var Grid, GridView, Grids, _ref, _ref1, _ref2;
    GridView = (function(_super) {
      __extends(GridView, _super);

      function GridView() {
        _ref = GridView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      GridView.prototype.initialize = function(attrs, options) {
        GridView.__super__.initialize.call(this, attrs, options);
        this.grid_props = new properties.Line(this, 'grid_');
        this.band_props = new properties.Fill(this, '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_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, sx0, sx1, sy0, sy1, xs, ys, _i, _ref1, _ref2, _ref3, _ref4;
        if (!this.band_props.do_fill) {
          return;
        }
        _ref1 = this.mget('grid_coords'), xs = _ref1[0], ys = _ref1[1];
        this.band_props.set(ctx, this);
        for (i = _i = 0, _ref2 = xs.length - 1; 0 <= _ref2 ? _i < _ref2 : _i > _ref2; i = 0 <= _ref2 ? ++_i : --_i) {
          if (i % 2 === 1) {
            _ref3 = this.plot_view.map_to_screen(xs[i], "data", ys[i], "data", this.x_range_name, this.y_range_name), sx0 = _ref3[0], sy0 = _ref3[1];
            _ref4 = this.plot_view.map_to_screen(xs[i + 1], "data", ys[i + 1], "data", this.x_range_name, this.y_range_name), sx1 = _ref4[0], sy1 = _ref4[1];
            ctx.fillRect(sx0[0], sy0[0], sx1[1] - sx0[0], sy1[1] - sy0[0]);
            ctx.fill();
          }
        }
      };

      GridView.prototype._draw_grids = function(ctx) {
        var i, sx, sy, xs, ys, _i, _j, _ref1, _ref2, _ref3, _ref4;
        if (!this.grid_props.do_stroke) {
          return;
        }
        _ref1 = this.mget('grid_coords'), xs = _ref1[0], ys = _ref1[1];
        this.grid_props.set(ctx, this);
        for (i = _i = 0, _ref2 = xs.length; 0 <= _ref2 ? _i < _ref2 : _i > _ref2; i = 0 <= _ref2 ? ++_i : --_i) {
          _ref3 = this.plot_view.map_to_screen(xs[i], "data", ys[i], "data", this.x_range_name, this.y_range_name), sx = _ref3[0], sy = _ref3[1];
          ctx.beginPath();
          ctx.moveTo(Math.round(sx[0]), Math.round(sy[0]));
          for (i = _j = 1, _ref4 = sx.length; 1 <= _ref4 ? _j < _ref4 : _j > _ref4; i = 1 <= _ref4 ? ++_j : --_j) {
            ctx.lineTo(Math.round(sx[i]), Math.round(sy[i]));
          }
          ctx.stroke();
        }
      };

      return GridView;

    })(PlotWidget);
    Grid = (function(_super) {
      __extends(Grid, _super);

      function Grid() {
        _ref1 = Grid.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      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']);
        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, start, user_bounds, _ref2, _ref3;
        _ref2 = this.get('ranges'), range = _ref2[0], cross_range = _ref2[1];
        user_bounds = (_ref3 = this.get('bounds')) != null ? _ref3 : '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() {
        var N, cmax, cmin, coords, cross_range, dim_i, dim_j, end, i, ii, j, loc, max, min, n, range, start, ticks, tmp, _i, _j, _ref2, _ref3, _ref4;
        i = this.get('dimension');
        j = (i + 1) % 2;
        _ref2 = this.get('ranges'), range = _ref2[0], cross_range = _ref2[1];
        _ref3 = this.get('computed_bounds'), start = _ref3[0], end = _ref3[1];
        tmp = Math.min(start, end);
        end = Math.max(start, end);
        start = tmp;
        ticks = this.get('ticker').get_ticks(start, end, range, {}).major;
        min = range.get('min');
        max = range.get('max');
        cmin = cross_range.get('min');
        cmax = cross_range.get('max');
        coords = [[], []];
        for (ii = _i = 0, _ref4 = ticks.length; 0 <= _ref4 ? _i < _ref4 : _i > _ref4; ii = 0 <= _ref4 ? ++_i : --_i) {
          if (ticks[ii] === min || ticks[ii] === max) {
            continue;
          }
          dim_i = [];
          dim_j = [];
          N = 2;
          for (n = _j = 0; 0 <= N ? _j < N : _j > N; n = 0 <= N ? ++_j : --_j) {
            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
        });
      };

      return Grid;

    })(HasParent);
    Grids = (function(_super) {
      __extends(Grids, _super);

      function Grids() {
        _ref2 = Grids.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Grids.prototype.model = Grid;

      return Grids;

    })(Collection);
    return {
      "Model": Grid,
      "Collection": new Grids(),
      "View": GridView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=grid.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('ticking/basic_tick_formatter',["underscore", "common/collection", "common/has_properties"], function(_, Collection, HasProperties) {
    var BasicTickFormatter, BasicTickFormatters, _ref, _ref1;
    BasicTickFormatter = (function(_super) {
      __extends(BasicTickFormatter, _super);

      function BasicTickFormatter() {
        _ref = BasicTickFormatter.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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, labels, need_sci, precision, tick, tick_abs, x, zero_eps, _i, _j, _k, _l, _len, _m, _n, _ref1, _ref2, _ref3, _ref4, _ref5;
        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 (_i = 0, _len = ticks.length; _i < _len; _i++) {
            tick = ticks[_i];
            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 = _j = 0, _ref1 = ticks.length; 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i = 0 <= _ref1 ? ++_j : --_j) {
              labels[i] = ticks[i].toExponential(precision || void 0);
            }
          } else {
            for (i = _k = 0, _ref2 = ticks.length; 0 <= _ref2 ? _k < _ref2 : _k > _ref2; i = 0 <= _ref2 ? ++_k : --_k) {
              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 = _l = _ref3 = this.last_precision; _ref3 <= 15 ? _l <= 15 : _l >= 15; x = _ref3 <= 15 ? ++_l : --_l) {
            is_ok = true;
            if (need_sci) {
              for (i = _m = 0, _ref4 = ticks.length; 0 <= _ref4 ? _m < _ref4 : _m > _ref4; i = 0 <= _ref4 ? ++_m : --_m) {
                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 = _n = 0, _ref5 = ticks.length; 0 <= _ref5 ? _n < _ref5 : _n > _ref5; i = 0 <= _ref5 ? ++_n : --_n) {
                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);
    BasicTickFormatters = (function(_super) {
      __extends(BasicTickFormatters, _super);

      function BasicTickFormatters() {
        _ref1 = BasicTickFormatters.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      BasicTickFormatters.prototype.model = BasicTickFormatter;

      return BasicTickFormatters;

    })(Collection);
    return {
      "Model": BasicTickFormatter,
      "Collection": new BasicTickFormatters()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=basic_tick_formatter.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/guide/linear_axis',["underscore", "common/collection", "./axis", "ticking/basic_ticker", "ticking/basic_tick_formatter"], function(_, Collection, Axis, BasicTicker, BasicTickFormatter) {
    var LinearAxes, LinearAxis, LinearAxisView, _ref, _ref1, _ref2;
    LinearAxisView = (function(_super) {
      __extends(LinearAxisView, _super);

      function LinearAxisView() {
        _ref = LinearAxisView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      return LinearAxisView;

    })(Axis.View);
    LinearAxis = (function(_super) {
      __extends(LinearAxis, _super);

      function LinearAxis() {
        _ref1 = LinearAxis.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      LinearAxis.prototype.default_view = LinearAxisView;

      LinearAxis.prototype.type = 'LinearAxis';

      LinearAxis.prototype.initialize = function(attrs, objects) {
        LinearAxis.__super__.initialize.call(this, attrs, objects);
        if (this.get('ticker') == null) {
          this.set_obj('ticker', BasicTicker.Collection.create());
        }
        if (this.get('formatter') == null) {
          return this.set_obj('formatter', BasicTickFormatter.Collection.create());
        }
      };

      return LinearAxis;

    })(Axis.Model);
    LinearAxes = (function(_super) {
      __extends(LinearAxes, _super);

      function LinearAxes() {
        _ref2 = LinearAxes.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      LinearAxes.prototype.model = LinearAxis;

      return LinearAxes;

    })(Collection);
    return {
      "Model": LinearAxis,
      "Collection": new LinearAxes(),
      "View": LinearAxisView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=linear_axis.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('ticking/log_ticker',["common/collection", "ticking/adaptive_ticker"], function(Collection, AdaptiveTicker) {
    var LogTicker, LogTickers, range, _ref, _ref1;
    range = function(start, stop, step) {
      var i, result;
      if (typeof stop === "undefined") {
        stop = start;
        start = 0;
      }
      if (typeof step === "undefined") {
        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(_super) {
      __extends(LogTicker, _super);

      function LogTicker() {
        _ref = LogTicker.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      LogTicker.prototype.type = 'LogTicker';

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

      LogTicker.prototype.get_ticks_no_defaults = function(data_low, data_high, desired_n_ticks) {
        var base, end_factor, endlog, factor, factors, i, interval, log_high, log_interval, log_low, minor_interval, minor_offsets, minor_ticks, num_minor_ticks, start_factor, startlog, tick, ticks, x, _i, _j, _k, _l, _len, _len1, _len2, _len3, _len4, _len5, _m, _n, _ref1;
        num_minor_ticks = this.get('num_minor_ticks');
        minor_ticks = [];
        if (data_low <= 0) {
          data_low = 1;
        }
        if (data_low > data_high) {
          _ref1 = [data_high, data_low], data_low = _ref1[0], data_high = _ref1[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 _i, _len, _results;
            _results = [];
            for (_i = 0, _len = factors.length; _i < _len; _i++) {
              factor = factors[_i];
              if (factor !== 0) {
                _results.push(factor * interval);
              }
            }
            return _results;
          })();
          if (num_minor_ticks > 1) {
            minor_interval = interval / num_minor_ticks;
            minor_offsets = (function() {
              var _i, _results;
              _results = [];
              for (i = _i = 1; 1 <= num_minor_ticks ? _i <= num_minor_ticks : _i >= num_minor_ticks; i = 1 <= num_minor_ticks ? ++_i : --_i) {
                _results.push(i * minor_interval);
              }
              return _results;
            })();
            for (_i = 0, _len = minor_offsets.length; _i < _len; _i++) {
              x = minor_offsets[_i];
              minor_ticks.push(ticks[0] - x);
            }
            for (_j = 0, _len1 = ticks.length; _j < _len1; _j++) {
              tick = ticks[_j];
              for (_k = 0, _len2 = minor_offsets.length; _k < _len2; _k++) {
                x = minor_offsets[_k];
                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 _l, _results;
              _results = [];
              for (i = _l = 1; 1 <= num_minor_ticks ? _l <= num_minor_ticks : _l >= num_minor_ticks; i = 1 <= num_minor_ticks ? ++_l : --_l) {
                _results.push(i * minor_interval);
              }
              return _results;
            })();
            for (_l = 0, _len3 = minor_offsets.length; _l < _len3; _l++) {
              x = minor_offsets[_l];
              minor_ticks.push(ticks[0] / x);
            }
            for (_m = 0, _len4 = ticks.length; _m < _len4; _m++) {
              tick = ticks[_m];
              for (_n = 0, _len5 = minor_offsets.length; _n < _len5; _n++) {
                x = minor_offsets[_n];
                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);
    LogTickers = (function(_super) {
      __extends(LogTickers, _super);

      function LogTickers() {
        _ref1 = LogTickers.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      LogTickers.prototype.model = LogTicker;

      return LogTickers;

    })(Collection);
    return {
      "Model": LogTicker,
      "Collection": new LogTickers()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=log_ticker.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('ticking/log_tick_formatter',["underscore", "common/collection", "common/has_properties", "common/logging", "ticking/basic_tick_formatter"], function(_, Collection, HasProperties, Logging, BasicTickFormatter) {
    var LogTickFormatter, LogTickFormatters, logger, _ref, _ref1;
    logger = Logging.logger;
    LogTickFormatter = (function(_super) {
      __extends(LogTickFormatter, _super);

      function LogTickFormatter() {
        _ref = LogTickFormatter.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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, labels, small_interval, _i, _ref1;
        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 = _i = 0, _ref1 = ticks.length; 0 <= _ref1 ? _i < _ref1 : _i > _ref1; i = 0 <= _ref1 ? ++_i : --_i) {
          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);
    LogTickFormatters = (function(_super) {
      __extends(LogTickFormatters, _super);

      function LogTickFormatters() {
        _ref1 = LogTickFormatters.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      LogTickFormatters.prototype.model = LogTickFormatter;

      return LogTickFormatters;

    })(Collection);
    return {
      "Model": LogTickFormatter,
      "Collection": new LogTickFormatters()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=log_tick_formatter.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/guide/log_axis',["underscore", "common/collection", "./axis", "ticking/log_ticker", "ticking/log_tick_formatter"], function(_, Collection, Axis, LogTicker, LogTickFormatter) {
    var LogAxes, LogAxis, LogAxisView, _ref, _ref1, _ref2;
    LogAxisView = (function(_super) {
      __extends(LogAxisView, _super);

      function LogAxisView() {
        _ref = LogAxisView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      return LogAxisView;

    })(Axis.View);
    LogAxis = (function(_super) {
      __extends(LogAxis, _super);

      function LogAxis() {
        _ref1 = LogAxis.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      LogAxis.prototype.default_view = LogAxisView;

      LogAxis.prototype.type = 'LogAxis';

      LogAxis.prototype.initialize = function(attrs, objects) {
        LogAxis.__super__.initialize.call(this, attrs, objects);
        if (this.get('ticker') == null) {
          this.set_obj('ticker', LogTicker.Collection.create());
        }
        if (this.get('formatter') == null) {
          return this.set_obj('formatter', LogTickFormatter.Collection.create());
        }
      };

      return LogAxis;

    })(Axis.Model);
    LogAxes = (function(_super) {
      __extends(LogAxes, _super);

      function LogAxes() {
        _ref2 = LogAxes.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      LogAxes.prototype.model = LogAxis;

      return LogAxes;

    })(Collection);
    return {
      "Model": LogAxis,
      "Collection": new LogAxes(),
      "View": LogAxisView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=log_axis.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/overlay/box_selection',["underscore", "common/has_parent", "common/collection", "common/plot_widget"], function(_, HasParent, Collection, PlotWidget) {
    var BoxSelection, BoxSelectionView, BoxSelections, _ref, _ref1, _ref2;
    BoxSelectionView = (function(_super) {
      __extends(BoxSelectionView, _super);

      function BoxSelectionView() {
        _ref = BoxSelectionView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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(_super) {
      __extends(BoxSelection, _super);

      function BoxSelection() {
        _ref1 = BoxSelection.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      BoxSelection.prototype.default_view = BoxSelectionView;

      BoxSelection.prototype.type = "BoxSelection";

      BoxSelection.prototype.defaults = function() {
        return _.extend({}, BoxSelection.__super__.defaults.call(this), {
          level: 'overlay',
          data: {}
        });
      };

      return BoxSelection;

    })(HasParent);
    BoxSelections = (function(_super) {
      __extends(BoxSelections, _super);

      function BoxSelections() {
        _ref2 = BoxSelections.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      BoxSelections.prototype.model = BoxSelection;

      return BoxSelections;

    })(Collection);
    return {
      "Model": BoxSelection,
      "Collection": new BoxSelections(),
      "View": BoxSelectionView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=box_selection.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('renderer/overlay/poly_selection',["underscore", "common/has_parent", "common/collection", "common/plot_widget", "renderer/properties"], function(_, HasParent, Collection, PlotWidget, properties) {
    var PolySelection, PolySelectionView, PolySelections, _ref, _ref1, _ref2;
    PolySelectionView = (function(_super) {
      __extends(PolySelectionView, _super);

      function PolySelectionView() {
        _ref = PolySelectionView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      PolySelectionView.prototype.initialize = function(options) {
        PolySelectionView.__super__.initialize.call(this, options);
        return this.props = {
          line: new properties.Line(this),
          fill: new properties.Fill(this)
        };
      };

      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, sx, sy, _i, _ref1;
        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 = _i = 0, _ref1 = data.vx.length; 0 <= _ref1 ? _i < _ref1 : _i > _ref1; i = 0 <= _ref1 ? ++_i : --_i) {
          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.props.line.do_stroke) {
          this.props.line.set(ctx);
          ctx.stroke();
        }
        if (this.props.fill.do_fill && this.mget('auto_close')) {
          this.props.fill.set(ctx);
          return ctx.fill();
        }
      };

      return PolySelectionView;

    })(PlotWidget);
    PolySelection = (function(_super) {
      __extends(PolySelection, _super);

      function PolySelection() {
        _ref1 = PolySelection.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      PolySelection.prototype.default_view = PolySelectionView;

      PolySelection.prototype.type = "PolySelection";

      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);
    PolySelections = (function(_super) {
      __extends(PolySelections, _super);

      function PolySelections() {
        _ref2 = PolySelections.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      PolySelections.prototype.model = PolySelection;

      return PolySelections;

    })(Collection);
    return {
      "Model": PolySelection,
      "Collection": new PolySelections(),
      "View": PolySelectionView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=poly_selection.js.map
*/;
(function() {
  var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('source/ajax_data_source',["underscore", "backbone", "common/logging", "./remote_data_source"], function(_, Backbone, Logging, RemoteDataSource) {
    var AjaxDataSource, AjaxDataSources, logger, _ref, _ref1;
    logger = Logging.logger;
    AjaxDataSource = (function(_super) {
      __extends(AjaxDataSource, _super);

      function AjaxDataSource() {
        this.update = __bind(this.update, this);
        this.setup = __bind(this.setup, this);
        this.destroy = __bind(this.destroy, this);
        _ref = AjaxDataSource.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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.update();
        if (this.get('polling_interval')) {
          return this.interval = setInterval(this.update, this.get('polling_interval'));
        }
      };

      AjaxDataSource.prototype.update = function() {
        var _this = this;
        $.ajax({
          dataType: 'json',
          url: this.get('data_url'),
          xhrField: {
            withCredentials: true
          },
          method: this.get('method'),
          contentType: 'application/json'
        }).done(function(data) {
          _this.set('data', data);
          console.log(data);
          return null;
        }).error(function() {
          return console.log(arguments);
        });
        return null;
      };

      return AjaxDataSource;

    })(RemoteDataSource.RemoteDataSource);
    AjaxDataSources = (function(_super) {
      __extends(AjaxDataSources, _super);

      function AjaxDataSources() {
        _ref1 = AjaxDataSources.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      AjaxDataSources.prototype.model = AjaxDataSource;

      AjaxDataSources.prototype.defaults = {
        url: "",
        expr: null
      };

      return AjaxDataSources;

    })(Backbone.Collection);
    return {
      "Model": AjaxDataSource,
      "Collection": new AjaxDataSources()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=ajax_data_source.js.map
*/;
(function() {
  var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('source/blaze_data_source',["underscore", "backbone", "common/logging", "./remote_data_source"], function(_, Backbone, Logging, RemoteDataSource) {
    var BlazeDataSource, BlazeDataSources, logger, _ref, _ref1;
    logger = Logging.logger;
    BlazeDataSource = (function(_super) {
      __extends(BlazeDataSource, _super);

      function BlazeDataSource() {
        this.update = __bind(this.update, this);
        this.setup = __bind(this.setup, this);
        this.destroy = __bind(this.destroy, this);
        _ref = BlazeDataSource.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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,
          _this = this;
        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(data) {
          var colname, columns_of_data, data_dict, idx, orig_data, _i, _len, _ref1;
          columns_of_data = _.zip.apply(_, data.data);
          data_dict = {};
          _ref1 = data.names;
          for (idx = _i = 0, _len = _ref1.length; _i < _len; idx = ++_i) {
            colname = _ref1[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;
        });
      };

      return BlazeDataSource;

    })(RemoteDataSource.RemoteDataSource);
    BlazeDataSources = (function(_super) {
      __extends(BlazeDataSources, _super);

      function BlazeDataSources() {
        _ref1 = BlazeDataSources.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      BlazeDataSources.prototype.model = BlazeDataSource;

      BlazeDataSources.prototype.defaults = {
        url: "",
        expr: null
      };

      return BlazeDataSources;

    })(Backbone.Collection);
    return {
      "Model": BlazeDataSource,
      "Collection": new BlazeDataSources()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=blaze_data_source.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, 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(fn, me){ return function(){ return fn.apply(me, arguments); }; };

  define('source/server_data_source',["backbone", "underscore", "./remote_data_source", "common/collection", "common/has_properties", "common/logging", "range/range1d", "range/data_range1d"], function(Backbone, _, RemoteDataSource, Collection, HasProperties, Logging, Range1d, DataRange1d) {
    var AbstractRenderingSource, HeatmapSource, Line1dSource, ServerDataSource, ServerDataSources, ServerSourceUpdater, ajax_throttle, logger, _ref, _ref1, _ref2, _ref3, _ref4, _ref5;
    logger = Logging.logger;
    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(_super) {
      __extends(ServerSourceUpdater, _super);

      function ServerSourceUpdater() {
        _ref = ServerSourceUpdater.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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, _ref1, _results;
        _ref1 = this.callbacks;
        _results = [];
        for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
          entry = _ref1[_i];
          _results.push(this.stopListening.apply(this, entry));
        }
        return _results;
      };

      ServerSourceUpdater.prototype.listen_for_updates = function() {
        var callback, param, ranges, _i, _len,
          _this = this;
        this.stoplistening_for_updates();
        callback = ajax_throttle(function() {
          return _this.update();
        });
        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, sendable_plot_state, _ref1;
        sendable_plot_state = {};
        _ref1 = this.plot_state;
        for (key in _ref1) {
          item = _ref1[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(_super) {
      __extends(AbstractRenderingSource, _super);

      function AbstractRenderingSource() {
        _ref1 = AbstractRenderingSource.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      AbstractRenderingSource.prototype.update = function() {
        var data, plot_state, render_state, resp,
          _this = this;
        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(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;
          }
        });
        return resp;
      };

      return AbstractRenderingSource;

    })(ServerSourceUpdater);
    Line1dSource = (function(_super) {
      __extends(Line1dSource, _super);

      function Line1dSource() {
        _ref2 = Line1dSource.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Line1dSource.prototype.update = function() {
        var data, plot_state, render_state, resp,
          _this = this;
        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(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;
          }
        });
        return resp;
      };

      return Line1dSource;

    })(ServerSourceUpdater);
    HeatmapSource = (function(_super) {
      __extends(HeatmapSource, _super);

      function HeatmapSource() {
        _ref3 = HeatmapSource.__super__.constructor.apply(this, arguments);
        return _ref3;
      }

      HeatmapSource.prototype.update = function() {
        var data, plot_state, render_state, resp,
          _this = this;
        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(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;
          }
        });
        return resp;
      };

      return HeatmapSource;

    })(ServerSourceUpdater);
    ServerDataSource = (function(_super) {
      __extends(ServerDataSource, _super);

      function ServerDataSource() {
        this.setup_proxy = __bind(this.setup_proxy, this);
        this.setup = __bind(this.setup, this);
        this.initialize = __bind(this.initialize, this);
        _ref4 = ServerDataSource.__super__.constructor.apply(this, arguments);
        return _ref4;
      }

      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);
    ServerDataSources = (function(_super) {
      __extends(ServerDataSources, _super);

      function ServerDataSources() {
        _ref5 = ServerDataSources.__super__.constructor.apply(this, arguments);
        return _ref5;
      }

      ServerDataSources.prototype.model = ServerDataSource;

      return ServerDataSources;

    })(Collection);
    return {
      "Model": ServerDataSource,
      "Collection": new ServerDataSources()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=server_data_source.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('ticking/numeral_tick_formatter',["underscore", "numeral", "common/collection", "common/has_properties"], function(_, Numeral, Collection, HasProperties) {
    var NumeralTickFormatter, NumeralTickFormatters, _ref, _ref1;
    NumeralTickFormatter = (function(_super) {
      __extends(NumeralTickFormatter, _super);

      function NumeralTickFormatter() {
        _ref = NumeralTickFormatter.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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);
    NumeralTickFormatters = (function(_super) {
      __extends(NumeralTickFormatters, _super);

      function NumeralTickFormatters() {
        _ref1 = NumeralTickFormatters.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      NumeralTickFormatters.prototype.model = NumeralTickFormatter;

      return NumeralTickFormatters;

    })(Collection);
    return {
      Model: NumeralTickFormatter,
      Collection: new NumeralTickFormatters()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=numeral_tick_formatter.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('ticking/printf_tick_formatter',["underscore", "sprintf", "common/collection", "common/has_properties"], function(_, sprintf, Collection, HasProperties) {
    var PrintfTickFormatter, PrintfTickFormatters, _ref, _ref1;
    PrintfTickFormatter = (function(_super) {
      __extends(PrintfTickFormatter, _super);

      function PrintfTickFormatter() {
        _ref = PrintfTickFormatter.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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(format, tick));
          }
          return _results;
        })();
        return labels;
      };

      PrintfTickFormatter.prototype.defaults = function() {
        return _.extend({}, PrintfTickFormatter.__super__.defaults.call(this), {
          format: '%s'
        });
      };

      return PrintfTickFormatter;

    })(HasProperties);
    PrintfTickFormatters = (function(_super) {
      __extends(PrintfTickFormatters, _super);

      function PrintfTickFormatters() {
        _ref1 = PrintfTickFormatters.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      PrintfTickFormatters.prototype.model = PrintfTickFormatter;

      return PrintfTickFormatters;

    })(Collection);
    return {
      Model: PrintfTickFormatter,
      Collection: new PrintfTickFormatters()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=printf_tick_formatter.js.map
*/;
define('bootstrap/modal',["jquery"], function(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)
 * ======================================================================== */


+function ($) {
  

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

});

define('tool/actions/preview_save_tool_template',[],function(){
  var template = function(__obj) {
  var _safe = function(value) {
    if (typeof value === 'undefined' && value == null)
      value = '';
    var result = new String(value);
    result.ecoSafe = true;
    return result;
  };
  return (function() {
    var __out = [], __self = this, _print = function(value) {
      if (typeof value !== 'undefined' && value != null)
        __out.push(value.ecoSafe ? value : __self.escape(value));
    }, _capture = function(callback) {
      var out = __out, result;
      __out = [];
      callback.call(this);
      result = __out.join('');
      __out = out;
      return _safe(result);
    };
    (function() {
      _print(_safe('<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);
    
    return __out.join('');
  }).call((function() {
    var obj = {
      escape: function(value) {
        return ('' + value)
          .replace(/&/g, '&amp;')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;')
          .replace(/"/g, '&quot;');
      },
      safe: _safe
    }, key;
    for (key in __obj) obj[key] = __obj[key];
    return obj;
  })());
};
  return template;
});

(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('tool/actions/preview_save_tool',["underscore", "jquery", "bootstrap/modal", "common/collection", "./action_tool", "./preview_save_tool_template"], function(_, $, $$1, Collection, ActionTool, preview_save_tool_template) {
    var PreviewSaveTool, PreviewSaveToolView, PreviewSaveTools, _ref, _ref1, _ref2;
    PreviewSaveToolView = (function(_super) {
      __extends(PreviewSaveToolView, _super);

      function PreviewSaveToolView() {
        _ref = PreviewSaveToolView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      PreviewSaveToolView.prototype.className = "bk-bs-modal";

      PreviewSaveToolView.prototype.template = preview_save_tool_template;

      PreviewSaveToolView.prototype.initialize = function(options) {
        var _this = this;
        PreviewSaveToolView.__super__.initialize.call(this, options);
        this.$el.html(this.template());
        this.$el.attr("tabindex", "-1");
        $('body').append(this.$el);
        this.$el.on('hidden', function() {
          return _this.$el.modal('hide');
        });
        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(_super) {
      __extends(PreviewSaveTool, _super);

      function PreviewSaveTool() {
        _ref1 = PreviewSaveTool.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      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);
    PreviewSaveTools = (function(_super) {
      __extends(PreviewSaveTools, _super);

      function PreviewSaveTools() {
        _ref2 = PreviewSaveTools.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      PreviewSaveTools.prototype.model = PreviewSaveTool;

      return PreviewSaveTools;

    })(Collection);
    return {
      Model: PreviewSaveTool,
      Collection: new PreviewSaveTools(),
      View: PreviewSaveToolView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=preview_save_tool.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('tool/actions/reset_tool',["underscore", "common/collection", "./action_tool"], function(_, Collection, ActionTool) {
    var ResetTool, ResetToolView, ResetTools, _ref, _ref1, _ref2;
    ResetToolView = (function(_super) {
      __extends(ResetToolView, _super);

      function ResetToolView() {
        _ref = ResetToolView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      ResetToolView.prototype["do"] = function() {
        return this.plot_view.update_range();
      };

      return ResetToolView;

    })(ActionTool.View);
    ResetTool = (function(_super) {
      __extends(ResetTool, _super);

      function ResetTool() {
        _ref1 = ResetTool.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      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);
    ResetTools = (function(_super) {
      __extends(ResetTools, _super);

      function ResetTools() {
        _ref2 = ResetTools.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      ResetTools.prototype.model = ResetTool;

      return ResetTools;

    })(Collection);
    return {
      "Model": ResetTool,
      "Collection": new ResetTools(),
      "View": ResetToolView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=reset_tool.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('tool/gestures/select_tool',["common/logging", "./gesture_tool"], function(Logging, GestureTool) {
    var SelectTool, SelectToolView, logger, _ref, _ref1;
    logger = Logging.logger;
    SelectToolView = (function(_super) {
      __extends(SelectToolView, _super);

      function SelectToolView() {
        _ref = SelectToolView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      SelectToolView.prototype._keyup = function(e) {
        var ds, r, sm, _i, _len, _ref1, _results;
        if (e.keyCode === 27) {
          _ref1 = this.mget('renderers');
          _results = [];
          for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
            r = _ref1[_i];
            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, tool_events, xm, ym, _i, _ref1;
        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 = _i = 0, _ref1 = g.vx.length; 0 <= _ref1 ? _i < _ref1 : _i > _ref1; i = 0 <= _ref1 ? ++_i : --_i) {
            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);
          tool_events.save();
        }
        return null;
      };

      return SelectToolView;

    })(GestureTool.View);
    SelectTool = (function(_super) {
      __extends(SelectTool, _super);

      function SelectTool() {
        _ref1 = SelectTool.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      SelectTool.prototype.initialize = function(attrs, options) {
        var all_renderers, names, r, renderers, _i, _len;
        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 _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);
        for (_i = 0, _len = renderers.length; _i < _len; _i++) {
          r = renderers[_i];
          logger.debug("- " + r.type + " " + r.id);
        }
        return null;
      };

      SelectTool.prototype.defaults = function() {
        return _.extend({}, SelectTool.__super__.defaults.call(this), {
          renderers: [],
          names: [],
          multi_select_modifier: "shift"
        });
      };

      return SelectTool;

    })(GestureTool.Model);
    return {
      "Model": SelectTool,
      "View": SelectToolView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=select_tool.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('tool/gestures/box_select_tool',["underscore", "common/collection", "renderer/overlay/box_selection", "tool/gestures/select_tool"], function(_, Collection, BoxSelection, SelectTool) {
    var BoxSelectTool, BoxSelectToolView, BoxSelectTools, _ref, _ref1, _ref2;
    BoxSelectToolView = (function(_super) {
      __extends(BoxSelectToolView, _super);

      function BoxSelectToolView() {
        _ref = BoxSelectToolView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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, vxlim, vylim, _ref1, _ref2;
        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');
        _ref1 = this.model._get_dim_limits(this._baseboint, curpoint, frame, dims), vxlim = _ref1[0], vylim = _ref1[1];
        this.mget('overlay').set('data', {
          vxlim: vxlim,
          vylim: vylim
        });
        if (this.mget('select_every_mousemove')) {
          append = (_ref2 = e.srcEvent.shiftKey) != null ? _ref2 : false;
          this._select(vxlim, vylim, false, append);
        }
        return null;
      };

      BoxSelectToolView.prototype._pan_end = function(e) {
        var append, canvas, curpoint, dims, frame, vxlim, vylim, _ref1, _ref2;
        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');
        _ref1 = this.model._get_dim_limits(this._baseboint, curpoint, frame, dims), vxlim = _ref1[0], vylim = _ref1[1];
        append = (_ref2 = e.srcEvent.shiftKey) != null ? _ref2 : 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, r, sm, vx0, vx1, vy0, vy1, _i, _len, _ref1;
        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
        };
        _ref1 = this.mget('renderers');
        for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
          r = _ref1[_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 BoxSelectToolView;

    })(SelectTool.View);
    BoxSelectTool = (function(_super) {
      __extends(BoxSelectTool, _super);

      function BoxSelectTool() {
        _ref1 = BoxSelectTool.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      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);
    BoxSelectTools = (function(_super) {
      __extends(BoxSelectTools, _super);

      function BoxSelectTools() {
        _ref2 = BoxSelectTools.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      BoxSelectTools.prototype.model = BoxSelectTool;

      return BoxSelectTools;

    })(Collection);
    return {
      "Model": BoxSelectTool,
      "Collection": new BoxSelectTools(),
      "View": BoxSelectToolView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=box_select_tool.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('tool/gestures/box_zoom_tool',["underscore", "common/collection", "renderer/overlay/box_selection", "tool/gestures/gesture_tool"], function(_, Collection, BoxSelection, GestureTool) {
    var BoxZoomTool, BoxZoomToolView, BoxZoomTools, _ref, _ref1, _ref2;
    BoxZoomToolView = (function(_super) {
      __extends(BoxZoomToolView, _super);

      function BoxZoomToolView() {
        _ref = BoxZoomToolView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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, vxlim, vylim, _ref1;
        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');
        _ref1 = this.model._get_dim_limits(this._baseboint, curpoint, frame, dims), vxlim = _ref1[0], vylim = _ref1[1];
        this.mget('overlay').set('data', {
          vxlim: vxlim,
          vylim: vylim
        });
        return null;
      };

      BoxZoomToolView.prototype._pan_end = function(e) {
        var canvas, curpoint, dims, frame, vxlim, vylim, _ref1;
        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');
        _ref1 = this.model._get_dim_limits(this._baseboint, curpoint, frame, dims), vxlim = _ref1[0], vylim = _ref1[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, start, xrs, yrs, zoom_info, _ref1, _ref2, _ref3, _ref4;
        xrs = {};
        _ref1 = this.plot_view.frame.get('x_mappers');
        for (name in _ref1) {
          mapper = _ref1[name];
          _ref2 = mapper.v_map_from_target(vxlim, true), start = _ref2[0], end = _ref2[1];
          xrs[name] = {
            start: start,
            end: end
          };
        }
        yrs = {};
        _ref3 = this.plot_view.frame.get('y_mappers');
        for (name in _ref3) {
          mapper = _ref3[name];
          _ref4 = mapper.v_map_from_target(vylim, true), start = _ref4[0], end = _ref4[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(_super) {
      __extends(BoxZoomTool, _super);

      function BoxZoomTool() {
        _ref1 = BoxZoomTool.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      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);
    BoxZoomTools = (function(_super) {
      __extends(BoxZoomTools, _super);

      function BoxZoomTools() {
        _ref2 = BoxZoomTools.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      BoxZoomTools.prototype.model = BoxZoomTool;

      return BoxZoomTools;

    })(Collection);
    return {
      "Model": BoxZoomTool,
      "Collection": new BoxZoomTools(),
      "View": BoxZoomToolView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=box_zoom_tool.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('tool/gestures/lasso_select_tool',["underscore", "common/collection", "renderer/overlay/poly_selection", "tool/gestures/select_tool"], function(_, Collection, PolySelection, SelectTool) {
    var LassoSelectTool, LassoSelectToolView, LassoSelectTools, _ref, _ref1, _ref2;
    LassoSelectToolView = (function(_super) {
      __extends(LassoSelectToolView, _super);

      function LassoSelectToolView() {
        _ref = LassoSelectToolView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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, vx, vy, _ref1;
        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 = (_ref1 = e.srcEvent.shiftKey) != null ? _ref1 : false;
          return this._select(this.data.vx, this.data.vy, false, append);
        }
      };

      LassoSelectToolView.prototype._pan_end = function(e) {
        var append, _ref1;
        this._clear_overlay();
        append = (_ref1 = e.srcEvent.shiftKey) != null ? _ref1 : 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, r, sm, _i, _len, _ref1;
        geometry = {
          type: 'poly',
          vx: vx,
          vy: vy
        };
        _ref1 = this.mget('renderers');
        for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
          r = _ref1[_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(_super) {
      __extends(LassoSelectTool, _super);

      function LassoSelectTool() {
        _ref1 = LassoSelectTool.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      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);
    LassoSelectTools = (function(_super) {
      __extends(LassoSelectTools, _super);

      function LassoSelectTools() {
        _ref2 = LassoSelectTools.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      LassoSelectTools.prototype.model = LassoSelectTool;

      return LassoSelectTools;

    })(Collection);
    return {
      "Model": LassoSelectTool,
      "Collection": new LassoSelectTools(),
      "View": LassoSelectToolView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=lasso_select_tool.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('tool/gestures/pan_tool',["underscore", "common/collection", "common/logging", "tool/gestures/gesture_tool"], function(_, Collection, Logging, GestureTool) {
    var PanTool, PanToolView, PanTools, logger, _ref, _ref1, _ref2;
    logger = Logging.logger;
    PanToolView = (function(_super) {
      __extends(PanToolView, _super);

      function PanToolView() {
        _ref = PanToolView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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')) {
            return this.h_axis_only = true;
          }
        }
      };

      PanToolView.prototype._pan = function(e) {
        return this._update(e.deltaX, -e.deltaY);
      };

      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, sdx, sdy, start, sx0, sx1, sx_high, sx_low, sy0, sy1, sy_high, sy_low, vr, xrs, yrs, _ref1, _ref2, _ref3, _ref4;
        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 = {};
        _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
          };
        }
        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(_super) {
      __extends(PanTool, _super);

      function PanTool() {
        _ref1 = PanTool.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      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.defaults = function() {
        return _.extend({}, PanTool.__super__.defaults.call(this), {
          dimensions: ["width", "height"]
        });
      };

      return PanTool;

    })(GestureTool.Model);
    PanTools = (function(_super) {
      __extends(PanTools, _super);

      function PanTools() {
        _ref2 = PanTools.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      PanTools.prototype.model = PanTool;

      return PanTools;

    })(Collection);
    return {
      "Model": PanTool,
      "Collection": new PanTools(),
      "View": PanToolView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=pan_tool.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('tool/gestures/resize_tool',["underscore", "common/collection", "tool/gestures/gesture_tool"], function(_, Collection, GestureTool) {
    var ResizeTool, ResizeToolView, ResizeTools, _ref, _ref1, _ref2;
    ResizeToolView = (function(_super) {
      __extends(ResizeToolView, _super);

      function ResizeToolView() {
        _ref = ResizeToolView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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;");
          return this.$el.show();
        } else {
          return this.$el.hide();
        }
      };

      ResizeToolView.prototype._pan_start = function(e) {
        var canvas;
        canvas = this.plot_view.canvas;
        this.ch = canvas.get('height');
        this.cw = canvas.get('width');
        return null;
      };

      ResizeToolView.prototype._pan = function(e) {
        this._update(e.deltaX, e.deltaY);
        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(_super) {
      __extends(ResizeTool, _super);

      function ResizeTool() {
        _ref1 = ResizeTool.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      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;

      return ResizeTool;

    })(GestureTool.Model);
    ResizeTools = (function(_super) {
      __extends(ResizeTools, _super);

      function ResizeTools() {
        _ref2 = ResizeTools.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      ResizeTools.prototype.model = ResizeTool;

      ResizeTools.prototype.defaults = function() {
        return _.extend({}, ResizeTools.__super__.defaults.call(this), {
          level: 'overlay',
          data: {}
        });
      };

      return ResizeTools;

    })(Collection);
    return {
      "Model": ResizeTool,
      "Collection": new ResizeTools(),
      "View": ResizeToolView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=resize_tool.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('tool/gestures/tap_tool',["underscore", "common/collection", "tool/gestures/select_tool"], function(_, Collection, SelectTool) {
    var TapTool, TapToolView, TapTools, _ref, _ref1, _ref2;
    TapToolView = (function(_super) {
      __extends(TapToolView, _super);

      function TapToolView() {
        _ref = TapToolView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      TapToolView.prototype._tap = function(e) {
        var append, canvas, vx, vy, _ref1;
        canvas = this.plot_view.canvas;
        vx = canvas.sx_to_vx(e.bokeh.sx);
        vy = canvas.sy_to_vy(e.bokeh.sy);
        append = (_ref1 = e.srcEvent.shiftKey) != null ? _ref1 : false;
        return this._select(vx, vy, true, append);
      };

      TapToolView.prototype._select = function(vx, vy, final, append) {
        var action, ds, geometry, r, sm, _i, _len, _ref1;
        geometry = {
          type: 'point',
          vx: vx,
          vy: vy
        };
        action = this.mget("action");
        _ref1 = this.mget('renderers');
        for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
          r = _ref1[_i];
          ds = r.get('data_source');
          sm = ds.get('selection_manager');
          sm.select(this, this.plot_view.renderers[r.id], geometry, final, append);
          if (action != null) {
            action.execute(ds);
          }
        }
        this._save_geometry(geometry, final, append);
        return null;
      };

      return TapToolView;

    })(SelectTool.View);
    TapTool = (function(_super) {
      __extends(TapTool, _super);

      function TapTool() {
        _ref1 = TapTool.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      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);
    TapTools = (function(_super) {
      __extends(TapTools, _super);

      function TapTools() {
        _ref2 = TapTools.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      TapTools.prototype.model = TapTool;

      return TapTools;

    })(Collection);
    return {
      Model: TapTool,
      Collection: new TapTools(),
      View: TapToolView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=tap_tool.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('tool/gestures/wheel_zoom_tool',["underscore", "common/collection", "common/logging", "tool/gestures/gesture_tool"], function(_, Collection, Logging, GestureTool) {
    var WheelZoomTool, WheelZoomToolView, WheelZoomTools, logger, _ref, _ref1, _ref2;
    logger = Logging.logger;
    WheelZoomToolView = (function(_super) {
      __extends(WheelZoomToolView, _super);

      function WheelZoomToolView() {
        _ref = WheelZoomToolView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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, start, sx0, sx1, sy0, sy1, v_axis_only, vr, vx, vx_high, vx_low, vy, vy_high, vy_low, xrs, yrs, zoom_info, _ref1, _ref2, _ref3, _ref4, _ref5;
        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 (((_ref1 = e.originalEvent) != null ? _ref1.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 = {};
        _ref2 = frame.get('x_mappers');
        for (name in _ref2) {
          mapper = _ref2[name];
          _ref3 = mapper.v_map_from_target([sx0, sx1], true), start = _ref3[0], end = _ref3[1];
          xrs[name] = {
            start: start,
            end: end
          };
        }
        yrs = {};
        _ref4 = frame.get('y_mappers');
        for (name in _ref4) {
          mapper = _ref4[name];
          _ref5 = mapper.v_map_from_target([sy0, sy1], true), start = _ref5[0], end = _ref5[1];
          yrs[name] = {
            start: start,
            end: end
          };
        }
        zoom_info = {
          xrs: xrs,
          yrs: yrs,
          factor: factor
        };
        this.plot_view.update_range(zoom_info);
        return null;
      };

      return WheelZoomToolView;

    })(GestureTool.View);
    WheelZoomTool = (function(_super) {
      __extends(WheelZoomTool, _super);

      function WheelZoomTool() {
        _ref1 = WheelZoomTool.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      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 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.defaults = function() {
        return _.extend({}, WheelZoomTool.__super__.defaults.call(this), {
          dimensions: ["width", "height"],
          speed: 1 / 600
        });
      };

      return WheelZoomTool;

    })(GestureTool.Model);
    WheelZoomTools = (function(_super) {
      __extends(WheelZoomTools, _super);

      function WheelZoomTools() {
        _ref2 = WheelZoomTools.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      WheelZoomTools.prototype.model = WheelZoomTool;

      return WheelZoomTools;

    })(Collection);
    return {
      "Model": WheelZoomTool,
      "Collection": new WheelZoomTools(),
      "View": WheelZoomToolView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=wheel_zoom_tool.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('tool/inspectors/crosshair_tool',["underscore", "common/collection", "renderer/annotation/span", "./inspect_tool"], function(_, Collection, Span, InspectTool) {
    var CrosshairTool, CrosshairToolView, CrosshairTools, _ref, _ref1, _ref2;
    CrosshairToolView = (function(_super) {
      __extends(CrosshairToolView, _super);

      function CrosshairToolView() {
        _ref = CrosshairToolView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      CrosshairToolView.prototype._move = function(e) {
        var canvas, dim, frame, span, vx, vy, _i, _len, _ref1, _results;
        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);
        _ref1 = this.mget('dimensions');
        _results = [];
        for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
          dim = _ref1[_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, span, _i, _len, _ref1, _results;
        _ref1 = this.mget('dimensions');
        _results = [];
        for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
          dim = _ref1[_i];
          span = this.mget('spans')[dim];
          _results.push(span.unset('location'));
        }
        return _results;
      };

      return CrosshairToolView;

    })(InspectTool.View);
    CrosshairTool = (function(_super) {
      __extends(CrosshairTool, _super);

      function CrosshairTool() {
        _ref1 = CrosshairTool.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      CrosshairTool.prototype.default_view = CrosshairToolView;

      CrosshairTool.prototype.type = "CrosshairTool";

      CrosshairTool.prototype.tool_name = "Crosshair";

      CrosshairTool.prototype.initialize = function(attrs, options) {
        var 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"
          }),
          height: new Span.Model({
            dimension: "height"
          })
        });
        renderers = this.get('plot').get('renderers');
        renderers.push(this.get('spans').width);
        renderers.push(this.get('spans').height);
        return this.get('plot').set('renderers', renderers);
      };

      CrosshairTool.prototype.defaults = function() {
        return _.extend({}, CrosshairTool.__super__.defaults.call(this), {
          dimensions: ["width", "height"]
        });
      };

      return CrosshairTool;

    })(InspectTool.Model);
    CrosshairTools = (function(_super) {
      __extends(CrosshairTools, _super);

      function CrosshairTools() {
        _ref2 = CrosshairTools.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      CrosshairTools.prototype.model = CrosshairTool;

      return CrosshairTools;

    })(Collection);
    return {
      "Model": CrosshairTool,
      "Collection": new CrosshairTools(),
      "View": CrosshairToolView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=crosshair_tool.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('tool/inspectors/hover_tool',["underscore", "common/collection", "renderer/annotation/tooltip", "./inspect_tool", "util/util"], function(_, Collection, Tooltip, InspectTool, Util) {
    var HoverTool, HoverToolView, HoverTools, _color_to_hex, _ref, _ref1, _ref2;
    _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(_super) {
      __extends(HoverToolView, _super);

      function HoverToolView() {
        _ref = HoverToolView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      HoverToolView.prototype.bind_bokeh_events = function() {
        var r, _i, _len, _ref1;
        _ref1 = this.mget('renderers');
        for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
          r = _ref1[_i];
          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, rid, tt, vx, vy, _ref1;
        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)) {
          _ref1 = this.mget('ttmodels');
          for (rid in _ref1) {
            tt = _ref1[rid];
            tt.clear();
          }
          return;
        }
        return this._inspect(vx, vy);
      };

      HoverToolView.prototype._move_exit = function() {
        var rid, tt, _ref1, _results;
        _ref1 = this.mget('ttmodels');
        _results = [];
        for (rid in _ref1) {
          tt = _ref1[rid];
          _results.push(tt.clear());
        }
        return _results;
      };

      HoverToolView.prototype._inspect = function(vx, vy, e) {
        var geometry, r, sm, _i, _len, _ref1;
        geometry = {
          type: 'point',
          vx: vx,
          vy: vy
        };
        _ref1 = this.mget('renderers');
        for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
          r = _ref1[_i];
          sm = r.get('data_source').get('selection_manager');
          sm.inspect(this, this.plot_view.renderers[r.id], geometry, {
            "geometry": geometry
          });
        }
      };

      HoverToolView.prototype._update = function(indices, tool, renderer, ds, _arg) {
        var canvas, frame, geometry, i, rx, ry, sx, sy, tooltip, vars, vx, vy, x, xmapper, y, ymapper, _i, _len, _ref1, _ref2;
        geometry = _arg.geometry;
        tooltip = (_ref1 = this.mget('ttmodels')[renderer.model.id]) != null ? _ref1 : null;
        if (tooltip == null) {
          return;
        }
        tooltip.clear();
        if (indices.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);
        vars = {
          x: x,
          y: y,
          vx: vx,
          vy: vy,
          sx: sx,
          sy: sy
        };
        for (_i = 0, _len = indices.length; _i < _len; _i++) {
          i = indices[_i];
          if (this.mget('snap_to_data') && (renderer.glyph.sx != null) && (renderer.glyph.sy != null)) {
            rx = canvas.sx_to_vx(renderer.glyph.sx[i]);
            ry = canvas.sy_to_vy(renderer.glyph.sy[i]);
          } else {
            _ref2 = [vx, vy], rx = _ref2[0], ry = _ref2[1];
          }
          tooltip.add(rx, ry, this._render_tooltips(ds, i, vars));
        }
        return null;
      };

      HoverToolView.prototype._render_tooltips = function(ds, i, vars) {
        var colname, color, column, hex, label, match, opts, row, span, swatch, table, td, tooltips, value, _i, _len, _ref1, _ref2;
        tooltips = this.mget("tooltips");
        if (_.isString(tooltips)) {
          return $('<div>').html(Util.replace_placeholders(tooltips, ds, i, vars));
        } else {
          table = $('<table></table>');
          for (_i = 0, _len = tooltips.length; _i < _len; _i++) {
            _ref1 = tooltips[_i], label = _ref1[0], value = _ref1[1];
            row = $("<tr></tr>");
            row.append($("<td class='bk-tooltip-row-label'>" + label + ": </td>"));
            td = $("<td class='bk-tooltip-row-value'></td>");
            if (value.indexOf("$color") >= 0) {
              _ref2 = value.match(/\$color(\[.*\])?:(\w*)/), match = _ref2[0], opts = _ref2[1], colname = _ref2[2];
              column = ds.get_column(colname);
              if (column == null) {
                span = $("<span>" + colname + " unknown</span>");
                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>" + color + "</span>");
              td.append(span);
              if (swatch) {
                span = $("<span class='bk-tooltip-color-block'> </span>");
                span.css({
                  backgroundColor: color
                });
              }
              td.append(span);
            } else {
              value = Util.replace_placeholders(value, ds, i, vars);
              td.append($('<span>').text(value));
            }
            row.append(td);
            table.append(row);
          }
          return table;
        }
      };

      return HoverToolView;

    })(InspectTool.View);
    HoverTool = (function(_super) {
      var icon;

      __extends(HoverTool, _super);

      function HoverTool() {
        _ref1 = HoverTool.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      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 r, renderers, tooltip, ttmodels, _i, _len, _ref2;
        HoverTool.__super__.initialize.call(this, attrs, options);
        ttmodels = {};
        renderers = this.get('plot').get('renderers');
        _ref2 = this.get('renderers');
        for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
          r = _ref2[_i];
          tooltip = new Tooltip.Model();
          tooltip.set("custom", _.isString(this.get("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), {
          snap_to_data: true,
          tooltips: [["index", "$index"], ["data (x, y)", "($x, $y)"], ["canvas (x, y)", "($sx, $sy)"]]
        });
      };

      return HoverTool;

    })(InspectTool.Model);
    HoverTools = (function(_super) {
      __extends(HoverTools, _super);

      function HoverTools() {
        _ref2 = HoverTools.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      HoverTools.prototype.model = HoverTool;

      return HoverTools;

    })(Collection);
    return {
      Model: HoverTool,
      Collection: new HoverTools(),
      View: HoverToolView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=hover_tool.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('widget/cell_formatters',["underscore", "jquery", "common/has_properties", "common/collection", "numeral"], function(_, $, HasProperties, Collection, Numeral) {
    var BooleanFormatter, BooleanFormatters, CellFormatter, CellFormatterCollection, DateFormatter, DateFormatters, NumberFormatter, NumberFormatters, StringFormatter, StringFormatters, _ref, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8, _ref9;
    CellFormatter = (function(_super) {
      __extends(CellFormatter, _super);

      function CellFormatter() {
        _ref = CellFormatter.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      CellFormatter.prototype.format = function(row, cell, value, columnDef, dataContext) {
        if (value === null) {
          return "";
        } else {
          return (value + "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
        }
      };

      CellFormatter.prototype.formatterDefaults = {};

      CellFormatter.prototype.defaults = function() {
        return _.extend({}, CellFormatter.__super__.defaults.call(this), this.formatterDefaults);
      };

      return CellFormatter;

    })(HasProperties);
    CellFormatterCollection = (function(_super) {
      __extends(CellFormatterCollection, _super);

      function CellFormatterCollection() {
        _ref1 = CellFormatterCollection.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      return CellFormatterCollection;

    })(Collection);
    StringFormatter = (function(_super) {
      __extends(StringFormatter, _super);

      function StringFormatter() {
        _ref2 = StringFormatter.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      StringFormatter.prototype.type = 'StringFormatter';

      StringFormatter.prototype.formatterDefaults = {
        font_style: null,
        text_align: null,
        text_color: null
      };

      StringFormatter.prototype.format = function(row, cell, value, columnDef, dataContext) {
        var font_style, text, text_align, text_color;
        text = StringFormatter.__super__.format.call(this, row, cell, value, columnDef, dataContext);
        font_style = this.get("font_style");
        text_align = this.get("text_align");
        text_color = this.get("text_color");
        if ((font_style != null) || (text_align != null) || (text_color != null)) {
          text = $("<span>" + text + "</span>");
          switch (font_style) {
            case "bold":
              text = text.css("font-weight", "bold");
              break;
            case "italic":
              text = text.css("font-style", "italic");
          }
          if (text_align != null) {
            text = text.css("text-align", text_align);
          }
          if (text_color != null) {
            text = text.css("color", text_color);
          }
          text = text.prop('outerHTML');
        }
        return text;
      };

      return StringFormatter;

    })(CellFormatter);
    StringFormatters = (function(_super) {
      __extends(StringFormatters, _super);

      function StringFormatters() {
        _ref3 = StringFormatters.__super__.constructor.apply(this, arguments);
        return _ref3;
      }

      StringFormatters.prototype.model = StringFormatter;

      return StringFormatters;

    })(CellFormatterCollection);
    NumberFormatter = (function(_super) {
      __extends(NumberFormatter, _super);

      function NumberFormatter() {
        _ref4 = NumberFormatter.__super__.constructor.apply(this, arguments);
        return _ref4;
      }

      NumberFormatter.prototype.type = 'NumberFormatter';

      NumberFormatter.prototype.formatterDefaults = {
        font_style: null,
        text_align: null,
        text_color: null,
        format: '0,0',
        language: 'en',
        rounding: 'round'
      };

      NumberFormatter.prototype.format = function(row, cell, value, columnDef, dataContext) {
        var format, language, rounding;
        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);
        value = Numeral.format(value, format, language, rounding);
        return NumberFormatter.__super__.format.call(this, row, cell, value, columnDef, dataContext);
      };

      return NumberFormatter;

    })(StringFormatter);
    NumberFormatters = (function(_super) {
      __extends(NumberFormatters, _super);

      function NumberFormatters() {
        _ref5 = NumberFormatters.__super__.constructor.apply(this, arguments);
        return _ref5;
      }

      NumberFormatters.prototype.model = NumberFormatter;

      return NumberFormatters;

    })(CellFormatterCollection);
    BooleanFormatter = (function(_super) {
      __extends(BooleanFormatter, _super);

      function BooleanFormatter() {
        _ref6 = BooleanFormatter.__super__.constructor.apply(this, arguments);
        return _ref6;
      }

      BooleanFormatter.prototype.type = 'BooleanFormatter';

      BooleanFormatter.prototype.formatterDefaults = {
        icon: 'check'
      };

      BooleanFormatter.prototype.format = function(row, cell, value, columnDef, dataContext) {
        if (!!value) {
          return $('<i>').addClass(this.get("icon")).html();
        } else {
          return "";
        }
      };

      return BooleanFormatter;

    })(CellFormatter);
    BooleanFormatters = (function(_super) {
      __extends(BooleanFormatters, _super);

      function BooleanFormatters() {
        _ref7 = BooleanFormatters.__super__.constructor.apply(this, arguments);
        return _ref7;
      }

      BooleanFormatters.prototype.model = BooleanFormatter;

      return BooleanFormatters;

    })(CellFormatterCollection);
    DateFormatter = (function(_super) {
      __extends(DateFormatter, _super);

      function DateFormatter() {
        _ref8 = DateFormatter.__super__.constructor.apply(this, arguments);
        return _ref8;
      }

      DateFormatter.prototype.type = 'DateFormatter';

      DateFormatter.prototype.formatterDefaults = {
        format: 'yy M d'
      };

      DateFormatter.prototype.getFormat = function() {
        var format, name;
        format = this.get("format");
        name = (function() {
          switch (format) {
            case "ATOM":
            case "W3C":
            case "RFC-3339":
            case "ISO-8601":
              return "ISO-8601";
            case "COOKIE":
              return "COOKIE";
            case "RFC-850":
              return "RFC-850";
            case "RFC-1036":
              return "RFC-1036";
            case "RFC-1123":
              return "RFC-1123";
            case "RFC-2822":
              return "RFC-2822";
            case "RSS":
            case "RFC-822":
              return "RFC-822";
            case "TICKS":
              return "TICKS";
            case "TIMESTAMP":
              return "TIMESTAMP";
            default:
              return null;
          }
        })();
        if (name != null) {
          return $.datepicker[name];
        } else {
          return format;
        }
      };

      DateFormatter.prototype.format = function(row, cell, value, columnDef, dataContext) {
        var date;
        value = _.isString(value) ? parseInt(value, 10) : value;
        date = $.datepicker.formatDate(this.getFormat(), new Date(value));
        return DateFormatter.__super__.format.call(this, row, cell, date, columnDef, dataContext);
      };

      return DateFormatter;

    })(CellFormatter);
    DateFormatters = (function(_super) {
      __extends(DateFormatters, _super);

      function DateFormatters() {
        _ref9 = DateFormatters.__super__.constructor.apply(this, arguments);
        return _ref9;
      }

      DateFormatters.prototype.model = DateFormatter;

      return DateFormatters;

    })(CellFormatterCollection);
    return {
      String: {
        Model: StringFormatter,
        Collection: new StringFormatters()
      },
      Number: {
        Model: NumberFormatter,
        Collection: new NumberFormatters()
      },
      Boolean: {
        Model: BooleanFormatter,
        Collection: new BooleanFormatters()
      },
      Date: {
        Model: DateFormatter,
        Collection: new DateFormatters()
      }
    };
  });

}).call(this);

/*
//@ sourceMappingURL=cell_formatters.js.map
*/;
/*!
 * jQuery UI Core 1.11.2
 * http://jqueryui.com
 *
 * Copyright 2014 jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/category/ui-core/
 */
(function( factory ) {
	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( 'jquery_ui/core',[ "jquery" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
}(function( $ ) {

// $.ui might exist from components with no dependencies, e.g., $.ui.position
$.ui = $.ui || {};

$.extend( $.ui, {
	version: "1.11.2",

	keyCode: {
		BACKSPACE: 8,
		COMMA: 188,
		DELETE: 46,
		DOWN: 40,
		END: 35,
		ENTER: 13,
		ESCAPE: 27,
		HOME: 36,
		LEFT: 37,
		PAGE_DOWN: 34,
		PAGE_UP: 33,
		PERIOD: 190,
		RIGHT: 39,
		SPACE: 32,
		TAB: 9,
		UP: 38
	}
});

// plugins
$.fn.extend({
	scrollParent: function( includeHidden ) {
		var position = this.css( "position" ),
			excludeStaticParent = position === "absolute",
			overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/,
			scrollParent = this.parents().filter( function() {
				var parent = $( this );
				if ( excludeStaticParent && parent.css( "position" ) === "static" ) {
					return false;
				}
				return overflowRegex.test( parent.css( "overflow" ) + parent.css( "overflow-y" ) + parent.css( "overflow-x" ) );
			}).eq( 0 );

		return position === "fixed" || !scrollParent.length ? $( this[ 0 ].ownerDocument || document ) : scrollParent;
	},

	uniqueId: (function() {
		var uuid = 0;

		return function() {
			return this.each(function() {
				if ( !this.id ) {
					this.id = "bk-ui-id-" + ( ++uuid );
				}
			});
		};
	})(),

	removeUniqueId: function() {
		return this.each(function() {
			if ( /^bk-ui-id-\d+$/.test( this.id ) ) {
				$( this ).removeAttr( "id" );
			}
		});
	}
});

// selectors
function focusable( element, isTabIndexNotNaN ) {
	var map, mapName, img,
		nodeName = element.nodeName.toLowerCase();
	if ( "area" === nodeName ) {
		map = element.parentNode;
		mapName = map.name;
		if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
			return false;
		}
		img = $( "img[usemap='#" + mapName + "']" )[ 0 ];
		return !!img && visible( img );
	}
	return ( /input|select|textarea|button|object/.test( nodeName ) ?
		!element.disabled :
		"a" === nodeName ?
			element.href || isTabIndexNotNaN :
			isTabIndexNotNaN) &&
		// the element and all of its ancestors must be visible
		visible( element );
}

function visible( element ) {
	return $.expr.filters.visible( element ) &&
		!$( element ).parents().addBack().filter(function() {
			return $.css( this, "visibility" ) === "hidden";
		}).length;
}

$.extend( $.expr[ ":" ], {
	data: $.expr.createPseudo ?
		$.expr.createPseudo(function( dataName ) {
			return function( elem ) {
				return !!$.data( elem, dataName );
			};
		}) :
		// support: jQuery <1.8
		function( elem, i, match ) {
			return !!$.data( elem, match[ 3 ] );
		},

	focusable: function( element ) {
		return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) );
	},

	tabbable: function( element ) {
		var tabIndex = $.attr( element, "tabindex" ),
			isTabIndexNaN = isNaN( tabIndex );
		return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN );
	}
});

// support: jQuery <1.8
if ( !$( "<a>" ).outerWidth( 1 ).jquery ) {
	$.each( [ "Width", "Height" ], function( i, name ) {
		var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
			type = name.toLowerCase(),
			orig = {
				innerWidth: $.fn.innerWidth,
				innerHeight: $.fn.innerHeight,
				outerWidth: $.fn.outerWidth,
				outerHeight: $.fn.outerHeight
			};

		function reduce( elem, size, border, margin ) {
			$.each( side, function() {
				size -= parseFloat( $.css( elem, "padding" + this ) ) || 0;
				if ( border ) {
					size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0;
				}
				if ( margin ) {
					size -= parseFloat( $.css( elem, "margin" + this ) ) || 0;
				}
			});
			return size;
		}

		$.fn[ "inner" + name ] = function( size ) {
			if ( size === undefined ) {
				return orig[ "inner" + name ].call( this );
			}

			return this.each(function() {
				$( this ).css( type, reduce( this, size ) + "px" );
			});
		};

		$.fn[ "outer" + name] = function( size, margin ) {
			if ( typeof size !== "number" ) {
				return orig[ "outer" + name ].call( this, size );
			}

			return this.each(function() {
				$( this).css( type, reduce( this, size, true, margin ) + "px" );
			});
		};
	});
}

// support: jQuery <1.8
if ( !$.fn.addBack ) {
	$.fn.addBack = function( selector ) {
		return this.add( selector == null ?
			this.prevObject : this.prevObject.filter( selector )
		);
	};
}

// support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413)
if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) {
	$.fn.removeData = (function( removeData ) {
		return function( key ) {
			if ( arguments.length ) {
				return removeData.call( this, $.camelCase( key ) );
			} else {
				return removeData.call( this );
			}
		};
	})( $.fn.removeData );
}

// deprecated
$.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() );

$.fn.extend({
	focus: (function( orig ) {
		return function( delay, fn ) {
			return typeof delay === "number" ?
				this.each(function() {
					var elem = this;
					setTimeout(function() {
						$( elem ).focus();
						if ( fn ) {
							fn.call( elem );
						}
					}, delay );
				}) :
				orig.apply( this, arguments );
		};
	})( $.fn.focus ),

	disableSelection: (function() {
		var eventType = "onselectstart" in document.createElement( "div" ) ?
			"selectstart" :
			"mousedown";

		return function() {
			return this.bind( eventType + ".bk-ui-disableSelection", function( event ) {
				event.preventDefault();
			});
		};
	})(),

	enableSelection: function() {
		return this.unbind( ".bk-ui-disableSelection" );
	},

	zIndex: function( zIndex ) {
		if ( zIndex !== undefined ) {
			return this.css( "zIndex", zIndex );
		}

		if ( this.length ) {
			var elem = $( this[ 0 ] ), position, value;
			while ( elem.length && elem[ 0 ] !== document ) {
				// Ignore z-index if position is set to a value where z-index is ignored by the browser
				// This makes behavior of this function consistent across browsers
				// WebKit always returns auto if the element is positioned
				position = elem.css( "position" );
				if ( position === "absolute" || position === "relative" || position === "fixed" ) {
					// IE returns 0 when zIndex is not specified
					// other browsers return a string
					// we ignore the case of nested elements with an explicit value of 0
					// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
					value = parseInt( elem.css( "zIndex" ), 10 );
					if ( !isNaN( value ) && value !== 0 ) {
						return value;
					}
				}
				elem = elem.parent();
			}
		}

		return 0;
	}
});

// $.ui.plugin is deprecated. Use $.widget() extensions instead.
$.ui.plugin = {
	add: function( module, option, set ) {
		var i,
			proto = $.ui[ module ].prototype;
		for ( i in set ) {
			proto.plugins[ i ] = proto.plugins[ i ] || [];
			proto.plugins[ i ].push( [ option, set[ i ] ] );
		}
	},
	call: function( instance, name, args, allowDisconnected ) {
		var i,
			set = instance.plugins[ name ];

		if ( !set ) {
			return;
		}

		if ( !allowDisconnected && ( !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) ) {
			return;
		}

		for ( i = 0; i < set.length; i++ ) {
			if ( instance.options[ set[ i ][ 0 ] ] ) {
				set[ i ][ 1 ].apply( instance.element, args );
			}
		}
	}
};

}));

/*!
 * jQuery UI Widget 1.11.2
 * http://jqueryui.com
 *
 * Copyright 2014 jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/jQuery.widget/
 */
(function( factory ) {
	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( 'jquery_ui/widget',[ "jquery" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
}(function( $ ) {

var widget_uuid = 0,
	widget_slice = Array.prototype.slice;

$.cleanData = (function( orig ) {
	return function( elems ) {
		var events, elem, i;
		for ( i = 0; (elem = elems[i]) != null; i++ ) {
			try {

				// Only trigger remove when necessary to save time
				events = $._data( elem, "events" );
				if ( events && events.remove ) {
					$( elem ).triggerHandler( "remove" );
				}

			// http://bugs.jquery.com/ticket/8235
			} catch ( e ) {}
		}
		orig( elems );
	};
})( $.cleanData );

$.widget = function( name, base, prototype ) {
	var fullName, existingConstructor, constructor, basePrototype,
		// proxiedPrototype allows the provided prototype to remain unmodified
		// so that it can be used as a mixin for multiple widgets (#8876)
		proxiedPrototype = {},
		namespace = name.split( "." )[ 0 ];

	name = name.split( "." )[ 1 ];
	fullName = namespace + "-" + name;

	if ( !prototype ) {
		prototype = base;
		base = $.Widget;
	}

	// create selector for plugin
	$.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
		return !!$.data( elem, fullName );
	};

	$[ namespace ] = $[ namespace ] || {};
	existingConstructor = $[ namespace ][ name ];
	constructor = $[ namespace ][ name ] = function( options, element ) {
		// allow instantiation without "new" keyword
		if ( !this._createWidget ) {
			return new constructor( options, element );
		}

		// allow instantiation without initializing for simple inheritance
		// must use "new" keyword (the code above always passes args)
		if ( arguments.length ) {
			this._createWidget( options, element );
		}
	};
	// extend with the existing constructor to carry over any static properties
	$.extend( constructor, existingConstructor, {
		version: prototype.version,
		// copy the object used to create the prototype in case we need to
		// redefine the widget later
		_proto: $.extend( {}, prototype ),
		// track widgets that inherit from this widget in case this widget is
		// redefined after a widget inherits from it
		_childConstructors: []
	});

	basePrototype = new base();
	// we need to make the options hash a property directly on the new instance
	// otherwise we'll modify the options hash on the prototype that we're
	// inheriting from
	basePrototype.options = $.widget.extend( {}, basePrototype.options );
	$.each( prototype, function( prop, value ) {
		if ( !$.isFunction( value ) ) {
			proxiedPrototype[ prop ] = value;
			return;
		}
		proxiedPrototype[ prop ] = (function() {
			var _super = function() {
					return base.prototype[ prop ].apply( this, arguments );
				},
				_superApply = function( args ) {
					return base.prototype[ prop ].apply( this, args );
				};
			return function() {
				var __super = this._super,
					__superApply = this._superApply,
					returnValue;

				this._super = _super;
				this._superApply = _superApply;

				returnValue = value.apply( this, arguments );

				this._super = __super;
				this._superApply = __superApply;

				return returnValue;
			};
		})();
	});
	constructor.prototype = $.widget.extend( basePrototype, {
		// TODO: remove support for widgetEventPrefix
		// always use the name + a colon as the prefix, e.g., draggable:start
		// don't prefix for widgets that aren't DOM-based
		widgetEventPrefix: existingConstructor ? (basePrototype.widgetEventPrefix || name) : name
	}, proxiedPrototype, {
		constructor: constructor,
		namespace: namespace,
		widgetName: name,
		widgetFullName: fullName
	});

	// If this widget is being redefined then we need to find all widgets that
	// are inheriting from it and redefine all of them so that they inherit from
	// the new version of this widget. We're essentially trying to replace one
	// level in the prototype chain.
	if ( existingConstructor ) {
		$.each( existingConstructor._childConstructors, function( i, child ) {
			var childPrototype = child.prototype;

			// redefine the child widget using the same prototype that was
			// originally used, but inherit from the new version of the base
			$.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto );
		});
		// remove the list of existing child constructors from the old constructor
		// so the old child constructors can be garbage collected
		delete existingConstructor._childConstructors;
	} else {
		base._childConstructors.push( constructor );
	}

	$.widget.bridge( name, constructor );

	return constructor;
};

$.widget.extend = function( target ) {
	var input = widget_slice.call( arguments, 1 ),
		inputIndex = 0,
		inputLength = input.length,
		key,
		value;
	for ( ; inputIndex < inputLength; inputIndex++ ) {
		for ( key in input[ inputIndex ] ) {
			value = input[ inputIndex ][ key ];
			if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {
				// Clone objects
				if ( $.isPlainObject( value ) ) {
					target[ key ] = $.isPlainObject( target[ key ] ) ?
						$.widget.extend( {}, target[ key ], value ) :
						// Don't extend strings, arrays, etc. with objects
						$.widget.extend( {}, value );
				// Copy everything else by reference
				} else {
					target[ key ] = value;
				}
			}
		}
	}
	return target;
};

$.widget.bridge = function( name, object ) {
	var fullName = object.prototype.widgetFullName || name;
	$.fn[ name ] = function( options ) {
		var isMethodCall = typeof options === "string",
			args = widget_slice.call( arguments, 1 ),
			returnValue = this;

		// allow multiple hashes to be passed on init
		options = !isMethodCall && args.length ?
			$.widget.extend.apply( null, [ options ].concat(args) ) :
			options;

		if ( isMethodCall ) {
			this.each(function() {
				var methodValue,
					instance = $.data( this, fullName );
				if ( options === "instance" ) {
					returnValue = instance;
					return false;
				}
				if ( !instance ) {
					return $.error( "cannot call methods on " + name + " prior to initialization; " +
						"attempted to call method '" + options + "'" );
				}
				if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) {
					return $.error( "no such method '" + options + "' for " + name + " widget instance" );
				}
				methodValue = instance[ options ].apply( instance, args );
				if ( methodValue !== instance && methodValue !== undefined ) {
					returnValue = methodValue && methodValue.jquery ?
						returnValue.pushStack( methodValue.get() ) :
						methodValue;
					return false;
				}
			});
		} else {
			this.each(function() {
				var instance = $.data( this, fullName );
				if ( instance ) {
					instance.option( options || {} );
					if ( instance._init ) {
						instance._init();
					}
				} else {
					$.data( this, fullName, new object( options, this ) );
				}
			});
		}

		return returnValue;
	};
};

$.Widget = function( /* options, element */ ) {};
$.Widget._childConstructors = [];

$.Widget.prototype = {
	widgetName: "widget",
	widgetEventPrefix: "",
	defaultElement: "<div>",
	options: {
		disabled: false,

		// callbacks
		create: null
	},
	_createWidget: function( options, element ) {
		element = $( element || this.defaultElement || this )[ 0 ];
		this.element = $( element );
		this.uuid = widget_uuid++;
		this.eventNamespace = "." + this.widgetName + this.uuid;

		this.bindings = $();
		this.hoverable = $();
		this.focusable = $();

		if ( element !== this ) {
			$.data( element, this.widgetFullName, this );
			this._on( true, this.element, {
				remove: function( event ) {
					if ( event.target === element ) {
						this.destroy();
					}
				}
			});
			this.document = $( element.style ?
				// element within the document
				element.ownerDocument :
				// element is window or document
				element.document || element );
			this.window = $( this.document[0].defaultView || this.document[0].parentWindow );
		}

		this.options = $.widget.extend( {},
			this.options,
			this._getCreateOptions(),
			options );

		this._create();
		this._trigger( "create", null, this._getCreateEventData() );
		this._init();
	},
	_getCreateOptions: $.noop,
	_getCreateEventData: $.noop,
	_create: $.noop,
	_init: $.noop,

	destroy: function() {
		this._destroy();
		// we can probably remove the unbind calls in 2.0
		// all event bindings should go through this._on()
		this.element
			.unbind( this.eventNamespace )
			.removeData( this.widgetFullName )
			// support: jquery <1.6.3
			// http://bugs.jquery.com/ticket/9413
			.removeData( $.camelCase( this.widgetFullName ) );
		this.widget()
			.unbind( this.eventNamespace )
			.removeAttr( "aria-disabled" )
			.removeClass(
				this.widgetFullName + "-disabled " +
				"bk-ui-state-disabled" );

		// clean up events and states
		this.bindings.unbind( this.eventNamespace );
		this.hoverable.removeClass( "bk-ui-state-hover" );
		this.focusable.removeClass( "bk-ui-state-focus" );
	},
	_destroy: $.noop,

	widget: function() {
		return this.element;
	},

	option: function( key, value ) {
		var options = key,
			parts,
			curOption,
			i;

		if ( arguments.length === 0 ) {
			// don't return a reference to the internal hash
			return $.widget.extend( {}, this.options );
		}

		if ( typeof key === "string" ) {
			// handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
			options = {};
			parts = key.split( "." );
			key = parts.shift();
			if ( parts.length ) {
				curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
				for ( i = 0; i < parts.length - 1; i++ ) {
					curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
					curOption = curOption[ parts[ i ] ];
				}
				key = parts.pop();
				if ( arguments.length === 1 ) {
					return curOption[ key ] === undefined ? null : curOption[ key ];
				}
				curOption[ key ] = value;
			} else {
				if ( arguments.length === 1 ) {
					return this.options[ key ] === undefined ? null : this.options[ key ];
				}
				options[ key ] = value;
			}
		}

		this._setOptions( options );

		return this;
	},
	_setOptions: function( options ) {
		var key;

		for ( key in options ) {
			this._setOption( key, options[ key ] );
		}

		return this;
	},
	_setOption: function( key, value ) {
		this.options[ key ] = value;

		if ( key === "disabled" ) {
			this.widget()
				.toggleClass( this.widgetFullName + "-disabled", !!value );

			// If the widget is becoming disabled, then nothing is interactive
			if ( value ) {
				this.hoverable.removeClass( "bk-ui-state-hover" );
				this.focusable.removeClass( "bk-ui-state-focus" );
			}
		}

		return this;
	},

	enable: function() {
		return this._setOptions({ disabled: false });
	},
	disable: function() {
		return this._setOptions({ disabled: true });
	},

	_on: function( suppressDisabledCheck, element, handlers ) {
		var delegateElement,
			instance = this;

		// no suppressDisabledCheck flag, shuffle arguments
		if ( typeof suppressDisabledCheck !== "boolean" ) {
			handlers = element;
			element = suppressDisabledCheck;
			suppressDisabledCheck = false;
		}

		// no element argument, shuffle and use this.element
		if ( !handlers ) {
			handlers = element;
			element = this.element;
			delegateElement = this.widget();
		} else {
			element = delegateElement = $( element );
			this.bindings = this.bindings.add( element );
		}

		$.each( handlers, function( event, handler ) {
			function handlerProxy() {
				// allow widgets to customize the disabled handling
				// - disabled as an array instead of boolean
				// - disabled class as method for disabling individual parts
				if ( !suppressDisabledCheck &&
						( instance.options.disabled === true ||
							$( this ).hasClass( "bk-ui-state-disabled" ) ) ) {
					return;
				}
				return ( typeof handler === "string" ? instance[ handler ] : handler )
					.apply( instance, arguments );
			}

			// copy the guid so direct unbinding works
			if ( typeof handler !== "string" ) {
				handlerProxy.guid = handler.guid =
					handler.guid || handlerProxy.guid || $.guid++;
			}

			var match = event.match( /^([\w:-]*)\s*(.*)$/ ),
				eventName = match[1] + instance.eventNamespace,
				selector = match[2];
			if ( selector ) {
				delegateElement.delegate( selector, eventName, handlerProxy );
			} else {
				element.bind( eventName, handlerProxy );
			}
		});
	},

	_off: function( element, eventName ) {
		eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) +
			this.eventNamespace;
		element.unbind( eventName ).undelegate( eventName );

		// Clear the stack to avoid memory leaks (#10056)
		this.bindings = $( this.bindings.not( element ).get() );
		this.focusable = $( this.focusable.not( element ).get() );
		this.hoverable = $( this.hoverable.not( element ).get() );
	},

	_delay: function( handler, delay ) {
		function handlerProxy() {
			return ( typeof handler === "string" ? instance[ handler ] : handler )
				.apply( instance, arguments );
		}
		var instance = this;
		return setTimeout( handlerProxy, delay || 0 );
	},

	_hoverable: function( element ) {
		this.hoverable = this.hoverable.add( element );
		this._on( element, {
			mouseenter: function( event ) {
				$( event.currentTarget ).addClass( "bk-ui-state-hover" );
			},
			mouseleave: function( event ) {
				$( event.currentTarget ).removeClass( "bk-ui-state-hover" );
			}
		});
	},

	_focusable: function( element ) {
		this.focusable = this.focusable.add( element );
		this._on( element, {
			focusin: function( event ) {
				$( event.currentTarget ).addClass( "bk-ui-state-focus" );
			},
			focusout: function( event ) {
				$( event.currentTarget ).removeClass( "bk-ui-state-focus" );
			}
		});
	},

	_trigger: function( type, event, data ) {
		var prop, orig,
			callback = this.options[ type ];

		data = data || {};
		event = $.Event( event );
		event.type = ( type === this.widgetEventPrefix ?
			type :
			this.widgetEventPrefix + type ).toLowerCase();
		// the original event may come from any element
		// so we need to reset the target on the new event
		event.target = this.element[ 0 ];

		// copy original event properties over to the new event
		orig = event.originalEvent;
		if ( orig ) {
			for ( prop in orig ) {
				if ( !( prop in event ) ) {
					event[ prop ] = orig[ prop ];
				}
			}
		}

		this.element.trigger( event, data );
		return !( $.isFunction( callback ) &&
			callback.apply( this.element[0], [ event ].concat( data ) ) === false ||
			event.isDefaultPrevented() );
	}
};

$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
	$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
		if ( typeof options === "string" ) {
			options = { effect: options };
		}
		var hasOptions,
			effectName = !options ?
				method :
				options === true || typeof options === "number" ?
					defaultEffect :
					options.effect || defaultEffect;
		options = options || {};
		if ( typeof options === "number" ) {
			options = { duration: options };
		}
		hasOptions = !$.isEmptyObject( options );
		options.complete = callback;
		if ( options.delay ) {
			element.delay( options.delay );
		}
		if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
			element[ method ]( options );
		} else if ( effectName !== method && element[ effectName ] ) {
			element[ effectName ]( options.duration, options.easing, callback );
		} else {
			element.queue(function( next ) {
				$( this )[ method ]();
				if ( callback ) {
					callback.call( element[ 0 ] );
				}
				next();
			});
		}
	};
});

return $.widget;

}));

/*!
 * jQuery UI Position 1.11.2
 * http://jqueryui.com
 *
 * Copyright 2014 jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/position/
 */
(function( factory ) {
	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( 'jquery_ui/position',[ "jquery" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
}(function( $ ) {
(function() {

$.ui = $.ui || {};

var cachedScrollbarWidth, supportsOffsetFractions,
	max = Math.max,
	abs = Math.abs,
	round = Math.round,
	rhorizontal = /left|center|right/,
	rvertical = /top|center|bottom/,
	roffset = /[\+\-]\d+(\.[\d]+)?%?/,
	rposition = /^\w+/,
	rpercent = /%$/,
	_position = $.fn.position;

function getOffsets( offsets, width, height ) {
	return [
		parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ),
		parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 )
	];
}

function parseCss( element, property ) {
	return parseInt( $.css( element, property ), 10 ) || 0;
}

function getDimensions( elem ) {
	var raw = elem[0];
	if ( raw.nodeType === 9 ) {
		return {
			width: elem.width(),
			height: elem.height(),
			offset: { top: 0, left: 0 }
		};
	}
	if ( $.isWindow( raw ) ) {
		return {
			width: elem.width(),
			height: elem.height(),
			offset: { top: elem.scrollTop(), left: elem.scrollLeft() }
		};
	}
	if ( raw.preventDefault ) {
		return {
			width: 0,
			height: 0,
			offset: { top: raw.pageY, left: raw.pageX }
		};
	}
	return {
		width: elem.outerWidth(),
		height: elem.outerHeight(),
		offset: elem.offset()
	};
}

$.position = {
	scrollbarWidth: function() {
		if ( cachedScrollbarWidth !== undefined ) {
			return cachedScrollbarWidth;
		}
		var w1, w2,
			div = $( "<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>" ),
			innerDiv = div.children()[0];

		$( "body" ).append( div );
		w1 = innerDiv.offsetWidth;
		div.css( "overflow", "scroll" );

		w2 = innerDiv.offsetWidth;

		if ( w1 === w2 ) {
			w2 = div[0].clientWidth;
		}

		div.remove();

		return (cachedScrollbarWidth = w1 - w2);
	},
	getScrollInfo: function( within ) {
		var overflowX = within.isWindow || within.isDocument ? "" :
				within.element.css( "overflow-x" ),
			overflowY = within.isWindow || within.isDocument ? "" :
				within.element.css( "overflow-y" ),
			hasOverflowX = overflowX === "scroll" ||
				( overflowX === "auto" && within.width < within.element[0].scrollWidth ),
			hasOverflowY = overflowY === "scroll" ||
				( overflowY === "auto" && within.height < within.element[0].scrollHeight );
		return {
			width: hasOverflowY ? $.position.scrollbarWidth() : 0,
			height: hasOverflowX ? $.position.scrollbarWidth() : 0
		};
	},
	getWithinInfo: function( element ) {
		var withinElement = $( element || window ),
			isWindow = $.isWindow( withinElement[0] ),
			isDocument = !!withinElement[ 0 ] && withinElement[ 0 ].nodeType === 9;
		return {
			element: withinElement,
			isWindow: isWindow,
			isDocument: isDocument,
			offset: withinElement.offset() || { left: 0, top: 0 },
			scrollLeft: withinElement.scrollLeft(),
			scrollTop: withinElement.scrollTop(),

			// support: jQuery 1.6.x
			// jQuery 1.6 doesn't support .outerWidth/Height() on documents or windows
			width: isWindow || isDocument ? withinElement.width() : withinElement.outerWidth(),
			height: isWindow || isDocument ? withinElement.height() : withinElement.outerHeight()
		};
	}
};

$.fn.position = function( options ) {
	if ( !options || !options.of ) {
		return _position.apply( this, arguments );
	}

	// make a copy, we don't want to modify arguments
	options = $.extend( {}, options );

	var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions,
		target = $( options.of ),
		within = $.position.getWithinInfo( options.within ),
		scrollInfo = $.position.getScrollInfo( within ),
		collision = ( options.collision || "flip" ).split( " " ),
		offsets = {};

	dimensions = getDimensions( target );
	if ( target[0].preventDefault ) {
		// force left top to allow flipping
		options.at = "left top";
	}
	targetWidth = dimensions.width;
	targetHeight = dimensions.height;
	targetOffset = dimensions.offset;
	// clone to reuse original targetOffset later
	basePosition = $.extend( {}, targetOffset );

	// force my and at to have valid horizontal and vertical positions
	// if a value is missing or invalid, it will be converted to center
	$.each( [ "my", "at" ], function() {
		var pos = ( options[ this ] || "" ).split( " " ),
			horizontalOffset,
			verticalOffset;

		if ( pos.length === 1) {
			pos = rhorizontal.test( pos[ 0 ] ) ?
				pos.concat( [ "center" ] ) :
				rvertical.test( pos[ 0 ] ) ?
					[ "center" ].concat( pos ) :
					[ "center", "center" ];
		}
		pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center";
		pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center";

		// calculate offsets
		horizontalOffset = roffset.exec( pos[ 0 ] );
		verticalOffset = roffset.exec( pos[ 1 ] );
		offsets[ this ] = [
			horizontalOffset ? horizontalOffset[ 0 ] : 0,
			verticalOffset ? verticalOffset[ 0 ] : 0
		];

		// reduce to just the positions without the offsets
		options[ this ] = [
			rposition.exec( pos[ 0 ] )[ 0 ],
			rposition.exec( pos[ 1 ] )[ 0 ]
		];
	});

	// normalize collision option
	if ( collision.length === 1 ) {
		collision[ 1 ] = collision[ 0 ];
	}

	if ( options.at[ 0 ] === "right" ) {
		basePosition.left += targetWidth;
	} else if ( options.at[ 0 ] === "center" ) {
		basePosition.left += targetWidth / 2;
	}

	if ( options.at[ 1 ] === "bottom" ) {
		basePosition.top += targetHeight;
	} else if ( options.at[ 1 ] === "center" ) {
		basePosition.top += targetHeight / 2;
	}

	atOffset = getOffsets( offsets.at, targetWidth, targetHeight );
	basePosition.left += atOffset[ 0 ];
	basePosition.top += atOffset[ 1 ];

	return this.each(function() {
		var collisionPosition, using,
			elem = $( this ),
			elemWidth = elem.outerWidth(),
			elemHeight = elem.outerHeight(),
			marginLeft = parseCss( this, "marginLeft" ),
			marginTop = parseCss( this, "marginTop" ),
			collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) + scrollInfo.width,
			collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) + scrollInfo.height,
			position = $.extend( {}, basePosition ),
			myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() );

		if ( options.my[ 0 ] === "right" ) {
			position.left -= elemWidth;
		} else if ( options.my[ 0 ] === "center" ) {
			position.left -= elemWidth / 2;
		}

		if ( options.my[ 1 ] === "bottom" ) {
			position.top -= elemHeight;
		} else if ( options.my[ 1 ] === "center" ) {
			position.top -= elemHeight / 2;
		}

		position.left += myOffset[ 0 ];
		position.top += myOffset[ 1 ];

		// if the browser doesn't support fractions, then round for consistent results
		if ( !supportsOffsetFractions ) {
			position.left = round( position.left );
			position.top = round( position.top );
		}

		collisionPosition = {
			marginLeft: marginLeft,
			marginTop: marginTop
		};

		$.each( [ "left", "top" ], function( i, dir ) {
			if ( $.ui.position[ collision[ i ] ] ) {
				$.ui.position[ collision[ i ] ][ dir ]( position, {
					targetWidth: targetWidth,
					targetHeight: targetHeight,
					elemWidth: elemWidth,
					elemHeight: elemHeight,
					collisionPosition: collisionPosition,
					collisionWidth: collisionWidth,
					collisionHeight: collisionHeight,
					offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ],
					my: options.my,
					at: options.at,
					within: within,
					elem: elem
				});
			}
		});

		if ( options.using ) {
			// adds feedback as second argument to using callback, if present
			using = function( props ) {
				var left = targetOffset.left - position.left,
					right = left + targetWidth - elemWidth,
					top = targetOffset.top - position.top,
					bottom = top + targetHeight - elemHeight,
					feedback = {
						target: {
							element: target,
							left: targetOffset.left,
							top: targetOffset.top,
							width: targetWidth,
							height: targetHeight
						},
						element: {
							element: elem,
							left: position.left,
							top: position.top,
							width: elemWidth,
							height: elemHeight
						},
						horizontal: right < 0 ? "left" : left > 0 ? "right" : "center",
						vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle"
					};
				if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) {
					feedback.horizontal = "center";
				}
				if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) {
					feedback.vertical = "middle";
				}
				if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) {
					feedback.important = "horizontal";
				} else {
					feedback.important = "vertical";
				}
				options.using.call( this, props, feedback );
			};
		}

		elem.offset( $.extend( position, { using: using } ) );
	});
};

$.ui.position = {
	fit: {
		left: function( position, data ) {
			var within = data.within,
				withinOffset = within.isWindow ? within.scrollLeft : within.offset.left,
				outerWidth = within.width,
				collisionPosLeft = position.left - data.collisionPosition.marginLeft,
				overLeft = withinOffset - collisionPosLeft,
				overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,
				newOverRight;

			// element is wider than within
			if ( data.collisionWidth > outerWidth ) {
				// element is initially over the left side of within
				if ( overLeft > 0 && overRight <= 0 ) {
					newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset;
					position.left += overLeft - newOverRight;
				// element is initially over right side of within
				} else if ( overRight > 0 && overLeft <= 0 ) {
					position.left = withinOffset;
				// element is initially over both left and right sides of within
				} else {
					if ( overLeft > overRight ) {
						position.left = withinOffset + outerWidth - data.collisionWidth;
					} else {
						position.left = withinOffset;
					}
				}
			// too far left -> align with left edge
			} else if ( overLeft > 0 ) {
				position.left += overLeft;
			// too far right -> align with right edge
			} else if ( overRight > 0 ) {
				position.left -= overRight;
			// adjust based on position and margin
			} else {
				position.left = max( position.left - collisionPosLeft, position.left );
			}
		},
		top: function( position, data ) {
			var within = data.within,
				withinOffset = within.isWindow ? within.scrollTop : within.offset.top,
				outerHeight = data.within.height,
				collisionPosTop = position.top - data.collisionPosition.marginTop,
				overTop = withinOffset - collisionPosTop,
				overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
				newOverBottom;

			// element is taller than within
			if ( data.collisionHeight > outerHeight ) {
				// element is initially over the top of within
				if ( overTop > 0 && overBottom <= 0 ) {
					newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset;
					position.top += overTop - newOverBottom;
				// element is initially over bottom of within
				} else if ( overBottom > 0 && overTop <= 0 ) {
					position.top = withinOffset;
				// element is initially over both top and bottom of within
				} else {
					if ( overTop > overBottom ) {
						position.top = withinOffset + outerHeight - data.collisionHeight;
					} else {
						position.top = withinOffset;
					}
				}
			// too far up -> align with top
			} else if ( overTop > 0 ) {
				position.top += overTop;
			// too far down -> align with bottom edge
			} else if ( overBottom > 0 ) {
				position.top -= overBottom;
			// adjust based on position and margin
			} else {
				position.top = max( position.top - collisionPosTop, position.top );
			}
		}
	},
	flip: {
		left: function( position, data ) {
			var within = data.within,
				withinOffset = within.offset.left + within.scrollLeft,
				outerWidth = within.width,
				offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,
				collisionPosLeft = position.left - data.collisionPosition.marginLeft,
				overLeft = collisionPosLeft - offsetLeft,
				overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,
				myOffset = data.my[ 0 ] === "left" ?
					-data.elemWidth :
					data.my[ 0 ] === "right" ?
						data.elemWidth :
						0,
				atOffset = data.at[ 0 ] === "left" ?
					data.targetWidth :
					data.at[ 0 ] === "right" ?
						-data.targetWidth :
						0,
				offset = -2 * data.offset[ 0 ],
				newOverRight,
				newOverLeft;

			if ( overLeft < 0 ) {
				newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset;
				if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) {
					position.left += myOffset + atOffset + offset;
				}
			} else if ( overRight > 0 ) {
				newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft;
				if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) {
					position.left += myOffset + atOffset + offset;
				}
			}
		},
		top: function( position, data ) {
			var within = data.within,
				withinOffset = within.offset.top + within.scrollTop,
				outerHeight = within.height,
				offsetTop = within.isWindow ? within.scrollTop : within.offset.top,
				collisionPosTop = position.top - data.collisionPosition.marginTop,
				overTop = collisionPosTop - offsetTop,
				overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop,
				top = data.my[ 1 ] === "top",
				myOffset = top ?
					-data.elemHeight :
					data.my[ 1 ] === "bottom" ?
						data.elemHeight :
						0,
				atOffset = data.at[ 1 ] === "top" ?
					data.targetHeight :
					data.at[ 1 ] === "bottom" ?
						-data.targetHeight :
						0,
				offset = -2 * data.offset[ 1 ],
				newOverTop,
				newOverBottom;
			if ( overTop < 0 ) {
				newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset;
				if ( ( position.top + myOffset + atOffset + offset) > overTop && ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) ) {
					position.top += myOffset + atOffset + offset;
				}
			} else if ( overBottom > 0 ) {
				newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop;
				if ( ( position.top + myOffset + atOffset + offset) > overBottom && ( newOverTop > 0 || abs( newOverTop ) < overBottom ) ) {
					position.top += myOffset + atOffset + offset;
				}
			}
		}
	},
	flipfit: {
		left: function() {
			$.ui.position.flip.left.apply( this, arguments );
			$.ui.position.fit.left.apply( this, arguments );
		},
		top: function() {
			$.ui.position.flip.top.apply( this, arguments );
			$.ui.position.fit.top.apply( this, arguments );
		}
	}
};

// fraction support test
(function() {
	var testElement, testElementParent, testElementStyle, offsetLeft, i,
		body = document.getElementsByTagName( "body" )[ 0 ],
		div = document.createElement( "div" );

	//Create a "fake body" for testing based on method used in jQuery.support
	testElement = document.createElement( body ? "div" : "body" );
	testElementStyle = {
		visibility: "hidden",
		width: 0,
		height: 0,
		border: 0,
		margin: 0,
		background: "none"
	};
	if ( body ) {
		$.extend( testElementStyle, {
			position: "absolute",
			left: "-1000px",
			top: "-1000px"
		});
	}
	for ( i in testElementStyle ) {
		testElement.style[ i ] = testElementStyle[ i ];
	}
	testElement.appendChild( div );
	testElementParent = body || document.documentElement;
	testElementParent.insertBefore( testElement, testElementParent.firstChild );

	div.style.cssText = "position: absolute; left: 10.7432222px;";

	offsetLeft = $( div ).offset().left;
	supportsOffsetFractions = offsetLeft > 10 && offsetLeft < 11;

	testElement.innerHTML = "";
	testElementParent.removeChild( testElement );
})();

})();

return $.ui.position;

}));

/*!
 * jQuery UI Menu 1.11.2
 * http://jqueryui.com
 *
 * Copyright 2014 jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/menu/
 */
(function( factory ) {
	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define('jquery_ui/menu',[
			"jquery",
			"./core",
			"./widget",
			"./position"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
}(function( $ ) {

return $.widget( "ui.menu", {
	version: "1.11.2",
	defaultElement: "<ul>",
	delay: 300,
	options: {
		icons: {
			submenu: "bk-ui-icon-carat-1-e"
		},
		items: "> *",
		menus: "ul",
		position: {
			my: "left-1 top",
			at: "right top"
		},
		role: "menu",

		// callbacks
		blur: null,
		focus: null,
		select: null
	},

	_create: function() {
		this.activeMenu = this.element;

		// Flag used to prevent firing of the click handler
		// as the event bubbles up through nested menus
		this.mouseHandled = false;
		this.element
			.uniqueId()
			.addClass( "bk-ui-menu bk-ui-widget bk-ui-widget-content" )
			.toggleClass( "bk-ui-menu-icons", !!this.element.find( ".bk-ui-icon" ).length )
			.attr({
				role: this.options.role,
				tabIndex: 0
			});

		if ( this.options.disabled ) {
			this.element
				.addClass( "bk-ui-state-disabled" )
				.attr( "aria-disabled", "true" );
		}

		this._on({
			// Prevent focus from sticking to links inside menu after clicking
			// them (focus should always stay on UL during navigation).
			"mousedown .bk-ui-menu-item": function( event ) {
				event.preventDefault();
			},
			"click .bk-ui-menu-item": function( event ) {
				var target = $( event.target );
				if ( !this.mouseHandled && target.not( ".bk-ui-state-disabled" ).length ) {
					this.select( event );

					// Only set the mouseHandled flag if the event will bubble, see #9469.
					if ( !event.isPropagationStopped() ) {
						this.mouseHandled = true;
					}

					// Open submenu on click
					if ( target.has( ".bk-ui-menu" ).length ) {
						this.expand( event );
					} else if ( !this.element.is( ":focus" ) && $( this.document[ 0 ].activeElement ).closest( ".bk-ui-menu" ).length ) {

						// Redirect focus to the menu
						this.element.trigger( "focus", [ true ] );

						// If the active item is on the top level, let it stay active.
						// Otherwise, blur the active item since it is no longer visible.
						if ( this.active && this.active.parents( ".bk-ui-menu" ).length === 1 ) {
							clearTimeout( this.timer );
						}
					}
				}
			},
			"mouseenter .bk-ui-menu-item": function( event ) {
				// Ignore mouse events while typeahead is active, see #10458.
				// Prevents focusing the wrong item when typeahead causes a scroll while the mouse
				// is over an item in the menu
				if ( this.previousFilter ) {
					return;
				}
				var target = $( event.currentTarget );
				// Remove bk-ui-state-active class from siblings of the newly focused menu item
				// to avoid a jump caused by adjacent elements both having a class with a border
				target.siblings( ".bk-ui-state-active" ).removeClass( "bk-ui-state-active" );
				this.focus( event, target );
			},
			mouseleave: "collapseAll",
			"mouseleave .bk-ui-menu": "collapseAll",
			focus: function( event, keepActiveItem ) {
				// If there's already an active item, keep it active
				// If not, activate the first item
				var item = this.active || this.element.find( this.options.items ).eq( 0 );

				if ( !keepActiveItem ) {
					this.focus( event, item );
				}
			},
			blur: function( event ) {
				this._delay(function() {
					if ( !$.contains( this.element[0], this.document[0].activeElement ) ) {
						this.collapseAll( event );
					}
				});
			},
			keydown: "_keydown"
		});

		this.refresh();

		// Clicks outside of a menu collapse any open menus
		this._on( this.document, {
			click: function( event ) {
				if ( this._closeOnDocumentClick( event ) ) {
					this.collapseAll( event );
				}

				// Reset the mouseHandled flag
				this.mouseHandled = false;
			}
		});
	},

	_destroy: function() {
		// Destroy (sub)menus
		this.element
			.removeAttr( "aria-activedescendant" )
			.find( ".bk-ui-menu" ).addBack()
				.removeClass( "bk-ui-menu bk-ui-widget bk-ui-widget-content bk-ui-menu-icons bk-ui-front" )
				.removeAttr( "role" )
				.removeAttr( "tabIndex" )
				.removeAttr( "aria-labelledby" )
				.removeAttr( "aria-expanded" )
				.removeAttr( "aria-hidden" )
				.removeAttr( "aria-disabled" )
				.removeUniqueId()
				.show();

		// Destroy menu items
		this.element.find( ".bk-ui-menu-item" )
			.removeClass( "bk-ui-menu-item" )
			.removeAttr( "role" )
			.removeAttr( "aria-disabled" )
			.removeUniqueId()
			.removeClass( "bk-ui-state-hover" )
			.removeAttr( "tabIndex" )
			.removeAttr( "role" )
			.removeAttr( "aria-haspopup" )
			.children().each( function() {
				var elem = $( this );
				if ( elem.data( "bk-ui-menu-submenu-carat" ) ) {
					elem.remove();
				}
			});

		// Destroy menu dividers
		this.element.find( ".bk-ui-menu-divider" ).removeClass( "bk-ui-menu-divider bk-ui-widget-content" );
	},

	_keydown: function( event ) {
		var match, prev, character, skip,
			preventDefault = true;

		switch ( event.keyCode ) {
		case $.ui.keyCode.PAGE_UP:
			this.previousPage( event );
			break;
		case $.ui.keyCode.PAGE_DOWN:
			this.nextPage( event );
			break;
		case $.ui.keyCode.HOME:
			this._move( "first", "first", event );
			break;
		case $.ui.keyCode.END:
			this._move( "last", "last", event );
			break;
		case $.ui.keyCode.UP:
			this.previous( event );
			break;
		case $.ui.keyCode.DOWN:
			this.next( event );
			break;
		case $.ui.keyCode.LEFT:
			this.collapse( event );
			break;
		case $.ui.keyCode.RIGHT:
			if ( this.active && !this.active.is( ".bk-ui-state-disabled" ) ) {
				this.expand( event );
			}
			break;
		case $.ui.keyCode.ENTER:
		case $.ui.keyCode.SPACE:
			this._activate( event );
			break;
		case $.ui.keyCode.ESCAPE:
			this.collapse( event );
			break;
		default:
			preventDefault = false;
			prev = this.previousFilter || "";
			character = String.fromCharCode( event.keyCode );
			skip = false;

			clearTimeout( this.filterTimer );

			if ( character === prev ) {
				skip = true;
			} else {
				character = prev + character;
			}

			match = this._filterMenuItems( character );
			match = skip && match.index( this.active.next() ) !== -1 ?
				this.active.nextAll( ".bk-ui-menu-item" ) :
				match;

			// If no matches on the current filter, reset to the last character pressed
			// to move down the menu to the first item that starts with that character
			if ( !match.length ) {
				character = String.fromCharCode( event.keyCode );
				match = this._filterMenuItems( character );
			}

			if ( match.length ) {
				this.focus( event, match );
				this.previousFilter = character;
				this.filterTimer = this._delay(function() {
					delete this.previousFilter;
				}, 1000 );
			} else {
				delete this.previousFilter;
			}
		}

		if ( preventDefault ) {
			event.preventDefault();
		}
	},

	_activate: function( event ) {
		if ( !this.active.is( ".bk-ui-state-disabled" ) ) {
			if ( this.active.is( "[aria-haspopup='true']" ) ) {
				this.expand( event );
			} else {
				this.select( event );
			}
		}
	},

	refresh: function() {
		var menus, items,
			that = this,
			icon = this.options.icons.submenu,
			submenus = this.element.find( this.options.menus );

		this.element.toggleClass( "bk-ui-menu-icons", !!this.element.find( ".bk-ui-icon" ).length );

		// Initialize nested menus
		submenus.filter( ":not(.bk-ui-menu)" )
			.addClass( "bk-ui-menu bk-ui-widget bk-ui-widget-content bk-ui-front" )
			.hide()
			.attr({
				role: this.options.role,
				"aria-hidden": "true",
				"aria-expanded": "false"
			})
			.each(function() {
				var menu = $( this ),
					item = menu.parent(),
					submenuCarat = $( "<span>" )
						.addClass( "bk-ui-menu-icon bk-ui-icon " + icon )
						.data( "bk-ui-menu-submenu-carat", true );

				item
					.attr( "aria-haspopup", "true" )
					.prepend( submenuCarat );
				menu.attr( "aria-labelledby", item.attr( "id" ) );
			});

		menus = submenus.add( this.element );
		items = menus.find( this.options.items );

		// Initialize menu-items containing spaces and/or dashes only as dividers
		items.not( ".bk-ui-menu-item" ).each(function() {
			var item = $( this );
			if ( that._isDivider( item ) ) {
				item.addClass( "bk-ui-widget-content bk-ui-menu-divider" );
			}
		});

		// Don't refresh list items that are already adapted
		items.not( ".bk-ui-menu-item, .bk-ui-menu-divider" )
			.addClass( "bk-ui-menu-item" )
			.uniqueId()
			.attr({
				tabIndex: -1,
				role: this._itemRole()
			});

		// Add aria-disabled attribute to any disabled menu item
		items.filter( ".bk-ui-state-disabled" ).attr( "aria-disabled", "true" );

		// If the active item has been removed, blur the menu
		if ( this.active && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) {
			this.blur();
		}
	},

	_itemRole: function() {
		return {
			menu: "menuitem",
			listbox: "option"
		}[ this.options.role ];
	},

	_setOption: function( key, value ) {
		if ( key === "icons" ) {
			this.element.find( ".bk-ui-menu-icon" )
				.removeClass( this.options.icons.submenu )
				.addClass( value.submenu );
		}
		if ( key === "disabled" ) {
			this.element
				.toggleClass( "bk-ui-state-disabled", !!value )
				.attr( "aria-disabled", value );
		}
		this._super( key, value );
	},

	focus: function( event, item ) {
		var nested, focused;
		this.blur( event, event && event.type === "focus" );

		this._scrollIntoView( item );

		this.active = item.first();
		focused = this.active.addClass( "bk-ui-state-focus" ).removeClass( "bk-ui-state-active" );
		// Only update aria-activedescendant if there's a role
		// otherwise we assume focus is managed elsewhere
		if ( this.options.role ) {
			this.element.attr( "aria-activedescendant", focused.attr( "id" ) );
		}

		// Highlight active parent menu item, if any
		this.active
			.parent()
			.closest( ".bk-ui-menu-item" )
			.addClass( "bk-ui-state-active" );

		if ( event && event.type === "keydown" ) {
			this._close();
		} else {
			this.timer = this._delay(function() {
				this._close();
			}, this.delay );
		}

		nested = item.children( ".bk-ui-menu" );
		if ( nested.length && event && ( /^mouse/.test( event.type ) ) ) {
			this._startOpening(nested);
		}
		this.activeMenu = item.parent();

		this._trigger( "focus", event, { item: item } );
	},

	_scrollIntoView: function( item ) {
		var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight;
		if ( this._hasScroll() ) {
			borderTop = parseFloat( $.css( this.activeMenu[0], "borderTopWidth" ) ) || 0;
			paddingTop = parseFloat( $.css( this.activeMenu[0], "paddingTop" ) ) || 0;
			offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop;
			scroll = this.activeMenu.scrollTop();
			elementHeight = this.activeMenu.height();
			itemHeight = item.outerHeight();

			if ( offset < 0 ) {
				this.activeMenu.scrollTop( scroll + offset );
			} else if ( offset + itemHeight > elementHeight ) {
				this.activeMenu.scrollTop( scroll + offset - elementHeight + itemHeight );
			}
		}
	},

	blur: function( event, fromFocus ) {
		if ( !fromFocus ) {
			clearTimeout( this.timer );
		}

		if ( !this.active ) {
			return;
		}

		this.active.removeClass( "bk-ui-state-focus" );
		this.active = null;

		this._trigger( "blur", event, { item: this.active } );
	},

	_startOpening: function( submenu ) {
		clearTimeout( this.timer );

		// Don't open if already open fixes a Firefox bug that caused a .5 pixel
		// shift in the submenu position when mousing over the carat icon
		if ( submenu.attr( "aria-hidden" ) !== "true" ) {
			return;
		}

		this.timer = this._delay(function() {
			this._close();
			this._open( submenu );
		}, this.delay );
	},

	_open: function( submenu ) {
		var position = $.extend({
			of: this.active
		}, this.options.position );

		clearTimeout( this.timer );
		this.element.find( ".bk-ui-menu" ).not( submenu.parents( ".bk-ui-menu" ) )
			.hide()
			.attr( "aria-hidden", "true" );

		submenu
			.show()
			.removeAttr( "aria-hidden" )
			.attr( "aria-expanded", "true" )
			.position( position );
	},

	collapseAll: function( event, all ) {
		clearTimeout( this.timer );
		this.timer = this._delay(function() {
			// If we were passed an event, look for the submenu that contains the event
			var currentMenu = all ? this.element :
				$( event && event.target ).closest( this.element.find( ".bk-ui-menu" ) );

			// If we found no valid submenu ancestor, use the main menu to close all sub menus anyway
			if ( !currentMenu.length ) {
				currentMenu = this.element;
			}

			this._close( currentMenu );

			this.blur( event );
			this.activeMenu = currentMenu;
		}, this.delay );
	},

	// With no arguments, closes the currently active menu - if nothing is active
	// it closes all menus.  If passed an argument, it will search for menus BELOW
	_close: function( startMenu ) {
		if ( !startMenu ) {
			startMenu = this.active ? this.active.parent() : this.element;
		}

		startMenu
			.find( ".bk-ui-menu" )
				.hide()
				.attr( "aria-hidden", "true" )
				.attr( "aria-expanded", "false" )
			.end()
			.find( ".bk-ui-state-active" ).not( ".bk-ui-state-focus" )
				.removeClass( "bk-ui-state-active" );
	},

	_closeOnDocumentClick: function( event ) {
		return !$( event.target ).closest( ".bk-ui-menu" ).length;
	},

	_isDivider: function( item ) {

		// Match hyphen, em dash, en dash
		return !/[^\-\u2014\u2013\s]/.test( item.text() );
	},

	collapse: function( event ) {
		var newItem = this.active &&
			this.active.parent().closest( ".bk-ui-menu-item", this.element );
		if ( newItem && newItem.length ) {
			this._close();
			this.focus( event, newItem );
		}
	},

	expand: function( event ) {
		var newItem = this.active &&
			this.active
				.children( ".bk-ui-menu " )
				.find( this.options.items )
				.first();

		if ( newItem && newItem.length ) {
			this._open( newItem.parent() );

			// Delay so Firefox will not hide activedescendant change in expanding submenu from AT
			this._delay(function() {
				this.focus( event, newItem );
			});
		}
	},

	next: function( event ) {
		this._move( "next", "first", event );
	},

	previous: function( event ) {
		this._move( "prev", "last", event );
	},

	isFirstItem: function() {
		return this.active && !this.active.prevAll( ".bk-ui-menu-item" ).length;
	},

	isLastItem: function() {
		return this.active && !this.active.nextAll( ".bk-ui-menu-item" ).length;
	},

	_move: function( direction, filter, event ) {
		var next;
		if ( this.active ) {
			if ( direction === "first" || direction === "last" ) {
				next = this.active
					[ direction === "first" ? "prevAll" : "nextAll" ]( ".bk-ui-menu-item" )
					.eq( -1 );
			} else {
				next = this.active
					[ direction + "All" ]( ".bk-ui-menu-item" )
					.eq( 0 );
			}
		}
		if ( !next || !next.length || !this.active ) {
			next = this.activeMenu.find( this.options.items )[ filter ]();
		}

		this.focus( event, next );
	},

	nextPage: function( event ) {
		var item, base, height;

		if ( !this.active ) {
			this.next( event );
			return;
		}
		if ( this.isLastItem() ) {
			return;
		}
		if ( this._hasScroll() ) {
			base = this.active.offset().top;
			height = this.element.height();
			this.active.nextAll( ".bk-ui-menu-item" ).each(function() {
				item = $( this );
				return item.offset().top - base - height < 0;
			});

			this.focus( event, item );
		} else {
			this.focus( event, this.activeMenu.find( this.options.items )
				[ !this.active ? "first" : "last" ]() );
		}
	},

	previousPage: function( event ) {
		var item, base, height;
		if ( !this.active ) {
			this.next( event );
			return;
		}
		if ( this.isFirstItem() ) {
			return;
		}
		if ( this._hasScroll() ) {
			base = this.active.offset().top;
			height = this.element.height();
			this.active.prevAll( ".bk-ui-menu-item" ).each(function() {
				item = $( this );
				return item.offset().top - base + height > 0;
			});

			this.focus( event, item );
		} else {
			this.focus( event, this.activeMenu.find( this.options.items ).first() );
		}
	},

	_hasScroll: function() {
		return this.element.outerHeight() < this.element.prop( "scrollHeight" );
	},

	select: function( event ) {
		// TODO: It should never be possible to not have an active item at this
		// point, but the tests don't trigger mouseenter before click.
		this.active = this.active || $( event.target ).closest( ".bk-ui-menu-item" );
		var ui = { item: this.active };
		if ( !this.active.has( ".bk-ui-menu" ).length ) {
			this.collapseAll( event, true );
		}
		this._trigger( "select", event, ui );
	},

	_filterMenuItems: function(character) {
		var escapedCharacter = character.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" ),
			regex = new RegExp( "^" + escapedCharacter, "i" );

		return this.activeMenu
			.find( this.options.items )

			// Only match on items, not dividers or other content (#10571)
			.filter( ".bk-ui-menu-item" )
			.filter(function() {
				return regex.test( $.trim( $( this ).text() ) );
			});
	}
});

}));

/*!
 * jQuery UI Autocomplete 1.11.2
 * http://jqueryui.com
 *
 * Copyright 2014 jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/autocomplete/
 */
(function( factory ) {
	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define('jquery_ui/autocomplete',[
			"jquery",
			"./core",
			"./widget",
			"./position",
			"./menu"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
}(function( $ ) {

$.widget( "ui.autocomplete", {
	version: "1.11.2",
	defaultElement: "<input>",
	options: {
		appendTo: null,
		autoFocus: false,
		delay: 300,
		minLength: 1,
		position: {
			my: "left top",
			at: "left bottom",
			collision: "none"
		},
		source: null,

		// callbacks
		change: null,
		close: null,
		focus: null,
		open: null,
		response: null,
		search: null,
		select: null
	},

	requestIndex: 0,
	pending: 0,

	_create: function() {
		// Some browsers only repeat keydown events, not keypress events,
		// so we use the suppressKeyPress flag to determine if we've already
		// handled the keydown event. #7269
		// Unfortunately the code for & in keypress is the same as the up arrow,
		// so we use the suppressKeyPressRepeat flag to avoid handling keypress
		// events when we know the keydown event was used to modify the
		// search term. #7799
		var suppressKeyPress, suppressKeyPressRepeat, suppressInput,
			nodeName = this.element[ 0 ].nodeName.toLowerCase(),
			isTextarea = nodeName === "textarea",
			isInput = nodeName === "input";

		this.isMultiLine =
			// Textareas are always multi-line
			isTextarea ? true :
			// Inputs are always single-line, even if inside a contentEditable element
			// IE also treats inputs as contentEditable
			isInput ? false :
			// All other element types are determined by whether or not they're contentEditable
			this.element.prop( "isContentEditable" );

		this.valueMethod = this.element[ isTextarea || isInput ? "val" : "text" ];
		this.isNewMenu = true;

		this.element
			.addClass( "bk-ui-autocomplete-input" )
			.attr( "autocomplete", "off" );

		this._on( this.element, {
			keydown: function( event ) {
				if ( this.element.prop( "readOnly" ) ) {
					suppressKeyPress = true;
					suppressInput = true;
					suppressKeyPressRepeat = true;
					return;
				}

				suppressKeyPress = false;
				suppressInput = false;
				suppressKeyPressRepeat = false;
				var keyCode = $.ui.keyCode;
				switch ( event.keyCode ) {
				case keyCode.PAGE_UP:
					suppressKeyPress = true;
					this._move( "previousPage", event );
					break;
				case keyCode.PAGE_DOWN:
					suppressKeyPress = true;
					this._move( "nextPage", event );
					break;
				case keyCode.UP:
					suppressKeyPress = true;
					this._keyEvent( "previous", event );
					break;
				case keyCode.DOWN:
					suppressKeyPress = true;
					this._keyEvent( "next", event );
					break;
				case keyCode.ENTER:
					// when menu is open and has focus
					if ( this.menu.active ) {
						// #6055 - Opera still allows the keypress to occur
						// which causes forms to submit
						suppressKeyPress = true;
						event.preventDefault();
						this.menu.select( event );
					}
					break;
				case keyCode.TAB:
					if ( this.menu.active ) {
						this.menu.select( event );
					}
					break;
				case keyCode.ESCAPE:
					if ( this.menu.element.is( ":visible" ) ) {
						if ( !this.isMultiLine ) {
							this._value( this.term );
						}
						this.close( event );
						// Different browsers have different default behavior for escape
						// Single press can mean undo or clear
						// Double press in IE means clear the whole form
						event.preventDefault();
					}
					break;
				default:
					suppressKeyPressRepeat = true;
					// search timeout should be triggered before the input value is changed
					this._searchTimeout( event );
					break;
				}
			},
			keypress: function( event ) {
				if ( suppressKeyPress ) {
					suppressKeyPress = false;
					if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
						event.preventDefault();
					}
					return;
				}
				if ( suppressKeyPressRepeat ) {
					return;
				}

				// replicate some key handlers to allow them to repeat in Firefox and Opera
				var keyCode = $.ui.keyCode;
				switch ( event.keyCode ) {
				case keyCode.PAGE_UP:
					this._move( "previousPage", event );
					break;
				case keyCode.PAGE_DOWN:
					this._move( "nextPage", event );
					break;
				case keyCode.UP:
					this._keyEvent( "previous", event );
					break;
				case keyCode.DOWN:
					this._keyEvent( "next", event );
					break;
				}
			},
			input: function( event ) {
				if ( suppressInput ) {
					suppressInput = false;
					event.preventDefault();
					return;
				}
				this._searchTimeout( event );
			},
			focus: function() {
				this.selectedItem = null;
				this.previous = this._value();
			},
			blur: function( event ) {
				if ( this.cancelBlur ) {
					delete this.cancelBlur;
					return;
				}

				clearTimeout( this.searching );
				this.close( event );
				this._change( event );
			}
		});

		this._initSource();
		this.menu = $( "<ul>" )
			.addClass( "bk-ui-autocomplete bk-ui-front" )
			.appendTo( this._appendTo() )
			.menu({
				// disable ARIA support, the live region takes care of that
				role: null
			})
			.hide()
			.menu( "instance" );

		this._on( this.menu.element, {
			mousedown: function( event ) {
				// prevent moving focus out of the text field
				event.preventDefault();

				// IE doesn't prevent moving focus even with event.preventDefault()
				// so we set a flag to know when we should ignore the blur event
				this.cancelBlur = true;
				this._delay(function() {
					delete this.cancelBlur;
				});

				// clicking on the scrollbar causes focus to shift to the body
				// but we can't detect a mouseup or a click immediately afterward
				// so we have to track the next mousedown and close the menu if
				// the user clicks somewhere outside of the autocomplete
				var menuElement = this.menu.element[ 0 ];
				if ( !$( event.target ).closest( ".bk-ui-menu-item" ).length ) {
					this._delay(function() {
						var that = this;
						this.document.one( "mousedown", function( event ) {
							if ( event.target !== that.element[ 0 ] &&
									event.target !== menuElement &&
									!$.contains( menuElement, event.target ) ) {
								that.close();
							}
						});
					});
				}
			},
			menufocus: function( event, ui ) {
				var label, item;
				// support: Firefox
				// Prevent accidental activation of menu items in Firefox (#7024 #9118)
				if ( this.isNewMenu ) {
					this.isNewMenu = false;
					if ( event.originalEvent && /^mouse/.test( event.originalEvent.type ) ) {
						this.menu.blur();

						this.document.one( "mousemove", function() {
							$( event.target ).trigger( event.originalEvent );
						});

						return;
					}
				}

				item = ui.item.data( "bk-ui-autocomplete-item" );
				if ( false !== this._trigger( "focus", event, { item: item } ) ) {
					// use value to match what will end up in the input, if it was a key event
					if ( event.originalEvent && /^key/.test( event.originalEvent.type ) ) {
						this._value( item.value );
					}
				}

				// Announce the value in the liveRegion
				label = ui.item.attr( "aria-label" ) || item.value;
				if ( label && $.trim( label ).length ) {
					this.liveRegion.children().hide();
					$( "<div>" ).text( label ).appendTo( this.liveRegion );
				}
			},
			menuselect: function( event, ui ) {
				var item = ui.item.data( "bk-ui-autocomplete-item" ),
					previous = this.previous;

				// only trigger when focus was lost (click on menu)
				if ( this.element[ 0 ] !== this.document[ 0 ].activeElement ) {
					this.element.focus();
					this.previous = previous;
					// #6109 - IE triggers two focus events and the second
					// is asynchronous, so we need to reset the previous
					// term synchronously and asynchronously :-(
					this._delay(function() {
						this.previous = previous;
						this.selectedItem = item;
					});
				}

				if ( false !== this._trigger( "select", event, { item: item } ) ) {
					this._value( item.value );
				}
				// reset the term after the select event
				// this allows custom select handling to work properly
				this.term = this._value();

				this.close( event );
				this.selectedItem = item;
			}
		});

		this.liveRegion = $( "<span>", {
				role: "status",
				"aria-live": "assertive",
				"aria-relevant": "additions"
			})
			.addClass( "bk-ui-helper-hidden-accessible" )
			.appendTo( this.document[ 0 ].body );

		// turning off autocomplete prevents the browser from remembering the
		// value when navigating through history, so we re-enable autocomplete
		// if the page is unloaded before the widget is destroyed. #7790
		this._on( this.window, {
			beforeunload: function() {
				this.element.removeAttr( "autocomplete" );
			}
		});
	},

	_destroy: function() {
		clearTimeout( this.searching );
		this.element
			.removeClass( "bk-ui-autocomplete-input" )
			.removeAttr( "autocomplete" );
		this.menu.element.remove();
		this.liveRegion.remove();
	},

	_setOption: function( key, value ) {
		this._super( key, value );
		if ( key === "source" ) {
			this._initSource();
		}
		if ( key === "appendTo" ) {
			this.menu.element.appendTo( this._appendTo() );
		}
		if ( key === "disabled" && value && this.xhr ) {
			this.xhr.abort();
		}
	},

	_appendTo: function() {
		var element = this.options.appendTo;

		if ( element ) {
			element = element.jquery || element.nodeType ?
				$( element ) :
				this.document.find( element ).eq( 0 );
		}

		if ( !element || !element[ 0 ] ) {
			element = this.element.closest( ".bk-ui-front" );
		}

		if ( !element.length ) {
			element = this.document[ 0 ].body;
		}

		return element;
	},

	_initSource: function() {
		var array, url,
			that = this;
		if ( $.isArray( this.options.source ) ) {
			array = this.options.source;
			this.source = function( request, response ) {
				response( $.ui.autocomplete.filter( array, request.term ) );
			};
		} else if ( typeof this.options.source === "string" ) {
			url = this.options.source;
			this.source = function( request, response ) {
				if ( that.xhr ) {
					that.xhr.abort();
				}
				that.xhr = $.ajax({
					url: url,
					data: request,
					dataType: "json",
					success: function( data ) {
						response( data );
					},
					error: function() {
						response([]);
					}
				});
			};
		} else {
			this.source = this.options.source;
		}
	},

	_searchTimeout: function( event ) {
		clearTimeout( this.searching );
		this.searching = this._delay(function() {

			// Search if the value has changed, or if the user retypes the same value (see #7434)
			var equalValues = this.term === this._value(),
				menuVisible = this.menu.element.is( ":visible" ),
				modifierKey = event.altKey || event.ctrlKey || event.metaKey || event.shiftKey;

			if ( !equalValues || ( equalValues && !menuVisible && !modifierKey ) ) {
				this.selectedItem = null;
				this.search( null, event );
			}
		}, this.options.delay );
	},

	search: function( value, event ) {
		value = value != null ? value : this._value();

		// always save the actual value, not the one passed as an argument
		this.term = this._value();

		if ( value.length < this.options.minLength ) {
			return this.close( event );
		}

		if ( this._trigger( "search", event ) === false ) {
			return;
		}

		return this._search( value );
	},

	_search: function( value ) {
		this.pending++;
		this.element.addClass( "bk-ui-autocomplete-loading" );
		this.cancelSearch = false;

		this.source( { term: value }, this._response() );
	},

	_response: function() {
		var index = ++this.requestIndex;

		return $.proxy(function( content ) {
			if ( index === this.requestIndex ) {
				this.__response( content );
			}

			this.pending--;
			if ( !this.pending ) {
				this.element.removeClass( "bk-ui-autocomplete-loading" );
			}
		}, this );
	},

	__response: function( content ) {
		if ( content ) {
			content = this._normalize( content );
		}
		this._trigger( "response", null, { content: content } );
		if ( !this.options.disabled && content && content.length && !this.cancelSearch ) {
			this._suggest( content );
			this._trigger( "open" );
		} else {
			// use ._close() instead of .close() so we don't cancel future searches
			this._close();
		}
	},

	close: function( event ) {
		this.cancelSearch = true;
		this._close( event );
	},

	_close: function( event ) {
		if ( this.menu.element.is( ":visible" ) ) {
			this.menu.element.hide();
			this.menu.blur();
			this.isNewMenu = true;
			this._trigger( "close", event );
		}
	},

	_change: function( event ) {
		if ( this.previous !== this._value() ) {
			this._trigger( "change", event, { item: this.selectedItem } );
		}
	},

	_normalize: function( items ) {
		// assume all items have the right format when the first item is complete
		if ( items.length && items[ 0 ].label && items[ 0 ].value ) {
			return items;
		}
		return $.map( items, function( item ) {
			if ( typeof item === "string" ) {
				return {
					label: item,
					value: item
				};
			}
			return $.extend( {}, item, {
				label: item.label || item.value,
				value: item.value || item.label
			});
		});
	},

	_suggest: function( items ) {
		var ul = this.menu.element.empty();
		this._renderMenu( ul, items );
		this.isNewMenu = true;
		this.menu.refresh();

		// size and position menu
		ul.show();
		this._resizeMenu();
		ul.position( $.extend({
			of: this.element
		}, this.options.position ) );

		if ( this.options.autoFocus ) {
			this.menu.next();
		}
	},

	_resizeMenu: function() {
		var ul = this.menu.element;
		ul.outerWidth( Math.max(
			// Firefox wraps long text (possibly a rounding bug)
			// so we add 1px to avoid the wrapping (#7513)
			ul.width( "" ).outerWidth() + 1,
			this.element.outerWidth()
		) );
	},

	_renderMenu: function( ul, items ) {
		var that = this;
		$.each( items, function( index, item ) {
			that._renderItemData( ul, item );
		});
	},

	_renderItemData: function( ul, item ) {
		return this._renderItem( ul, item ).data( "bk-ui-autocomplete-item", item );
	},

	_renderItem: function( ul, item ) {
		return $( "<li>" ).text( item.label ).appendTo( ul );
	},

	_move: function( direction, event ) {
		if ( !this.menu.element.is( ":visible" ) ) {
			this.search( null, event );
			return;
		}
		if ( this.menu.isFirstItem() && /^previous/.test( direction ) ||
				this.menu.isLastItem() && /^next/.test( direction ) ) {

			if ( !this.isMultiLine ) {
				this._value( this.term );
			}

			this.menu.blur();
			return;
		}
		this.menu[ direction ]( event );
	},

	widget: function() {
		return this.menu.element;
	},

	_value: function() {
		return this.valueMethod.apply( this.element, arguments );
	},

	_keyEvent: function( keyEvent, event ) {
		if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
			this._move( keyEvent, event );

			// prevents moving cursor to beginning/end of the text field in some browsers
			event.preventDefault();
		}
	}
});

$.extend( $.ui.autocomplete, {
	escapeRegex: function( value ) {
		return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
	},
	filter: function( array, term ) {
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), "i" );
		return $.grep( array, function( value ) {
			return matcher.test( value.label || value.value || value );
		});
	}
});

// live region extension, adding a `messages` option
// NOTE: This is an experimental API. We are still investigating
// a full solution for string manipulation and internationalization.
$.widget( "ui.autocomplete", $.ui.autocomplete, {
	options: {
		messages: {
			noResults: "No search results.",
			results: function( amount ) {
				return amount + ( amount > 1 ? " results are" : " result is" ) +
					" available, use up and down arrow keys to navigate.";
			}
		}
	},

	__response: function( content ) {
		var message;
		this._superApply( arguments );
		if ( this.options.disabled || this.cancelSearch ) {
			return;
		}
		if ( content && content.length ) {
			message = this.options.messages.results( content.length );
		} else {
			message = this.options.messages.noResults;
		}
		this.liveRegion.children().hide();
		$( "<div>" ).text( message ).appendTo( this.liveRegion );
	}
});

return $.ui.autocomplete;

}));

/*!
 * jQuery UI Button 1.11.2
 * http://jqueryui.com
 *
 * Copyright 2014 jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/button/
 */
(function( factory ) {
	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define('jquery_ui/button',[
			"jquery",
			"./core",
			"./widget"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
}(function( $ ) {

var lastActive,
	baseClasses = "bk-ui-button bk-ui-widget bk-ui-state-default bk-ui-corner-all",
	typeClasses = "bk-ui-button-icons-only bk-ui-button-icon-only bk-ui-button-text-icons bk-ui-button-text-icon-primary bk-ui-button-text-icon-secondary bk-ui-button-text-only",
	formResetHandler = function() {
		var form = $( this );
		setTimeout(function() {
			form.find( ":ui-button" ).button( "refresh" );
		}, 1 );
	},
	radioGroup = function( radio ) {
		var name = radio.name,
			form = radio.form,
			radios = $( [] );
		if ( name ) {
			name = name.replace( /'/g, "\\'" );
			if ( form ) {
				radios = $( form ).find( "[name='" + name + "'][type=radio]" );
			} else {
				radios = $( "[name='" + name + "'][type=radio]", radio.ownerDocument )
					.filter(function() {
						return !this.form;
					});
			}
		}
		return radios;
	};

$.widget( "ui.button", {
	version: "1.11.2",
	defaultElement: "<button>",
	options: {
		disabled: null,
		text: true,
		label: null,
		icons: {
			primary: null,
			secondary: null
		}
	},
	_create: function() {
		this.element.closest( "form" )
			.unbind( "reset" + this.eventNamespace )
			.bind( "reset" + this.eventNamespace, formResetHandler );

		if ( typeof this.options.disabled !== "boolean" ) {
			this.options.disabled = !!this.element.prop( "disabled" );
		} else {
			this.element.prop( "disabled", this.options.disabled );
		}

		this._determineButtonType();
		this.hasTitle = !!this.buttonElement.attr( "title" );

		var that = this,
			options = this.options,
			toggleButton = this.type === "checkbox" || this.type === "radio",
			activeClass = !toggleButton ? "bk-ui-state-active" : "";

		if ( options.label === null ) {
			options.label = (this.type === "input" ? this.buttonElement.val() : this.buttonElement.html());
		}

		this._hoverable( this.buttonElement );

		this.buttonElement
			.addClass( baseClasses )
			.attr( "role", "button" )
			.bind( "mouseenter" + this.eventNamespace, function() {
				if ( options.disabled ) {
					return;
				}
				if ( this === lastActive ) {
					$( this ).addClass( "bk-ui-state-active" );
				}
			})
			.bind( "mouseleave" + this.eventNamespace, function() {
				if ( options.disabled ) {
					return;
				}
				$( this ).removeClass( activeClass );
			})
			.bind( "click" + this.eventNamespace, function( event ) {
				if ( options.disabled ) {
					event.preventDefault();
					event.stopImmediatePropagation();
				}
			});

		// Can't use _focusable() because the element that receives focus
		// and the element that gets the bk-ui-state-focus class are different
		this._on({
			focus: function() {
				this.buttonElement.addClass( "bk-ui-state-focus" );
			},
			blur: function() {
				this.buttonElement.removeClass( "bk-ui-state-focus" );
			}
		});

		if ( toggleButton ) {
			this.element.bind( "change" + this.eventNamespace, function() {
				that.refresh();
			});
		}

		if ( this.type === "checkbox" ) {
			this.buttonElement.bind( "click" + this.eventNamespace, function() {
				if ( options.disabled ) {
					return false;
				}
			});
		} else if ( this.type === "radio" ) {
			this.buttonElement.bind( "click" + this.eventNamespace, function() {
				if ( options.disabled ) {
					return false;
				}
				$( this ).addClass( "bk-ui-state-active" );
				that.buttonElement.attr( "aria-pressed", "true" );

				var radio = that.element[ 0 ];
				radioGroup( radio )
					.not( radio )
					.map(function() {
						return $( this ).button( "widget" )[ 0 ];
					})
					.removeClass( "bk-ui-state-active" )
					.attr( "aria-pressed", "false" );
			});
		} else {
			this.buttonElement
				.bind( "mousedown" + this.eventNamespace, function() {
					if ( options.disabled ) {
						return false;
					}
					$( this ).addClass( "bk-ui-state-active" );
					lastActive = this;
					that.document.one( "mouseup", function() {
						lastActive = null;
					});
				})
				.bind( "mouseup" + this.eventNamespace, function() {
					if ( options.disabled ) {
						return false;
					}
					$( this ).removeClass( "bk-ui-state-active" );
				})
				.bind( "keydown" + this.eventNamespace, function(event) {
					if ( options.disabled ) {
						return false;
					}
					if ( event.keyCode === $.ui.keyCode.SPACE || event.keyCode === $.ui.keyCode.ENTER ) {
						$( this ).addClass( "bk-ui-state-active" );
					}
				})
				// see #8559, we bind to blur here in case the button element loses
				// focus between keydown and keyup, it would be left in an "active" state
				.bind( "keyup" + this.eventNamespace + " blur" + this.eventNamespace, function() {
					$( this ).removeClass( "bk-ui-state-active" );
				});

			if ( this.buttonElement.is("a") ) {
				this.buttonElement.keyup(function(event) {
					if ( event.keyCode === $.ui.keyCode.SPACE ) {
						// TODO pass through original event correctly (just as 2nd argument doesn't work)
						$( this ).click();
					}
				});
			}
		}

		this._setOption( "disabled", options.disabled );
		this._resetButton();
	},

	_determineButtonType: function() {
		var ancestor, labelSelector, checked;

		if ( this.element.is("[type=checkbox]") ) {
			this.type = "checkbox";
		} else if ( this.element.is("[type=radio]") ) {
			this.type = "radio";
		} else if ( this.element.is("input") ) {
			this.type = "input";
		} else {
			this.type = "button";
		}

		if ( this.type === "checkbox" || this.type === "radio" ) {
			// we don't search against the document in case the element
			// is disconnected from the DOM
			ancestor = this.element.parents().last();
			labelSelector = "label[for='" + this.element.attr("id") + "']";
			this.buttonElement = ancestor.find( labelSelector );
			if ( !this.buttonElement.length ) {
				ancestor = ancestor.length ? ancestor.siblings() : this.element.siblings();
				this.buttonElement = ancestor.filter( labelSelector );
				if ( !this.buttonElement.length ) {
					this.buttonElement = ancestor.find( labelSelector );
				}
			}
			this.element.addClass( "bk-ui-helper-hidden-accessible" );

			checked = this.element.is( ":checked" );
			if ( checked ) {
				this.buttonElement.addClass( "bk-ui-state-active" );
			}
			this.buttonElement.prop( "aria-pressed", checked );
		} else {
			this.buttonElement = this.element;
		}
	},

	widget: function() {
		return this.buttonElement;
	},

	_destroy: function() {
		this.element
			.removeClass( "bk-ui-helper-hidden-accessible" );
		this.buttonElement
			.removeClass( baseClasses + " bk-ui-state-active " + typeClasses )
			.removeAttr( "role" )
			.removeAttr( "aria-pressed" )
			.html( this.buttonElement.find(".bk-ui-button-text").html() );

		if ( !this.hasTitle ) {
			this.buttonElement.removeAttr( "title" );
		}
	},

	_setOption: function( key, value ) {
		this._super( key, value );
		if ( key === "disabled" ) {
			this.widget().toggleClass( "bk-ui-state-disabled", !!value );
			this.element.prop( "disabled", !!value );
			if ( value ) {
				if ( this.type === "checkbox" || this.type === "radio" ) {
					this.buttonElement.removeClass( "bk-ui-state-focus" );
				} else {
					this.buttonElement.removeClass( "bk-ui-state-focus bk-ui-state-active" );
				}
			}
			return;
		}
		this._resetButton();
	},

	refresh: function() {
		//See #8237 & #8828
		var isDisabled = this.element.is( "input, button" ) ? this.element.is( ":disabled" ) : this.element.hasClass( "bk-ui-button-disabled" );

		if ( isDisabled !== this.options.disabled ) {
			this._setOption( "disabled", isDisabled );
		}
		if ( this.type === "radio" ) {
			radioGroup( this.element[0] ).each(function() {
				if ( $( this ).is( ":checked" ) ) {
					$( this ).button( "widget" )
						.addClass( "bk-ui-state-active" )
						.attr( "aria-pressed", "true" );
				} else {
					$( this ).button( "widget" )
						.removeClass( "bk-ui-state-active" )
						.attr( "aria-pressed", "false" );
				}
			});
		} else if ( this.type === "checkbox" ) {
			if ( this.element.is( ":checked" ) ) {
				this.buttonElement
					.addClass( "bk-ui-state-active" )
					.attr( "aria-pressed", "true" );
			} else {
				this.buttonElement
					.removeClass( "bk-ui-state-active" )
					.attr( "aria-pressed", "false" );
			}
		}
	},

	_resetButton: function() {
		if ( this.type === "input" ) {
			if ( this.options.label ) {
				this.element.val( this.options.label );
			}
			return;
		}
		var buttonElement = this.buttonElement.removeClass( typeClasses ),
			buttonText = $( "<span></span>", this.document[0] )
				.addClass( "bk-ui-button-text" )
				.html( this.options.label )
				.appendTo( buttonElement.empty() )
				.text(),
			icons = this.options.icons,
			multipleIcons = icons.primary && icons.secondary,
			buttonClasses = [];

		if ( icons.primary || icons.secondary ) {
			if ( this.options.text ) {
				buttonClasses.push( "bk-ui-button-text-icon" + ( multipleIcons ? "s" : ( icons.primary ? "-primary" : "-secondary" ) ) );
			}

			if ( icons.primary ) {
				buttonElement.prepend( "<span class='bk-ui-button-icon-primary bk-ui-icon " + icons.primary + "'></span>" );
			}

			if ( icons.secondary ) {
				buttonElement.append( "<span class='bk-ui-button-icon-secondary bk-ui-icon " + icons.secondary + "'></span>" );
			}

			if ( !this.options.text ) {
				buttonClasses.push( multipleIcons ? "bk-ui-button-icons-only" : "bk-ui-button-icon-only" );

				if ( !this.hasTitle ) {
					buttonElement.attr( "title", $.trim( buttonText ) );
				}
			}
		} else {
			buttonClasses.push( "bk-ui-button-text-only" );
		}
		buttonElement.addClass( buttonClasses.join( " " ) );
	}
});

$.widget( "ui.buttonset", {
	version: "1.11.2",
	options: {
		items: "button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(bk-ui-button)"
	},

	_create: function() {
		this.element.addClass( "bk-ui-buttonset" );
	},

	_init: function() {
		this.refresh();
	},

	_setOption: function( key, value ) {
		if ( key === "disabled" ) {
			this.buttons.button( "option", key, value );
		}

		this._super( key, value );
	},

	refresh: function() {
		var rtl = this.element.css( "direction" ) === "rtl",
			allButtons = this.element.find( this.options.items ),
			existingButtons = allButtons.filter( ":ui-button" );

		// Initialize new buttons
		allButtons.not( ":ui-button" ).button();

		// Refresh existing buttons
		existingButtons.button( "refresh" );

		this.buttons = allButtons
			.map(function() {
				return $( this ).button( "widget" )[ 0 ];
			})
				.removeClass( "bk-ui-corner-all bk-ui-corner-left bk-ui-corner-right" )
				.filter( ":first" )
					.addClass( rtl ? "bk-ui-corner-right" : "bk-ui-corner-left" )
				.end()
				.filter( ":last" )
					.addClass( rtl ? "bk-ui-corner-left" : "bk-ui-corner-right" )
				.end()
			.end();
	},

	_destroy: function() {
		this.element.removeClass( "bk-ui-buttonset" );
		this.buttons
			.map(function() {
				return $( this ).button( "widget" )[ 0 ];
			})
				.removeClass( "bk-ui-corner-left bk-ui-corner-right" )
			.end()
			.button( "destroy" );
	}
});

return $.ui.button;

}));

/*!
 * jQuery UI Spinner 1.11.2
 * http://jqueryui.com
 *
 * Copyright 2014 jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/spinner/
 */
(function( factory ) {
	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define('jquery_ui/spinner',[
			"jquery",
			"./core",
			"./widget",
			"./button"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
}(function( $ ) {

function spinner_modifier( fn ) {
	return function() {
		var previous = this.element.val();
		fn.apply( this, arguments );
		this._refresh();
		if ( previous !== this.element.val() ) {
			this._trigger( "change" );
		}
	};
}

return $.widget( "ui.spinner", {
	version: "1.11.2",
	defaultElement: "<input>",
	widgetEventPrefix: "spin",
	options: {
		culture: null,
		icons: {
			down: "bk-ui-icon-triangle-1-s",
			up: "bk-ui-icon-triangle-1-n"
		},
		incremental: true,
		max: null,
		min: null,
		numberFormat: null,
		page: 10,
		step: 1,

		change: null,
		spin: null,
		start: null,
		stop: null
	},

	_create: function() {
		// handle string values that need to be parsed
		this._setOption( "max", this.options.max );
		this._setOption( "min", this.options.min );
		this._setOption( "step", this.options.step );

		// Only format if there is a value, prevents the field from being marked
		// as invalid in Firefox, see #9573.
		if ( this.value() !== "" ) {
			// Format the value, but don't constrain.
			this._value( this.element.val(), true );
		}

		this._draw();
		this._on( this._events );
		this._refresh();

		// turning off autocomplete prevents the browser from remembering the
		// value when navigating through history, so we re-enable autocomplete
		// if the page is unloaded before the widget is destroyed. #7790
		this._on( this.window, {
			beforeunload: function() {
				this.element.removeAttr( "autocomplete" );
			}
		});
	},

	_getCreateOptions: function() {
		var options = {},
			element = this.element;

		$.each( [ "min", "max", "step" ], function( i, option ) {
			var value = element.attr( option );
			if ( value !== undefined && value.length ) {
				options[ option ] = value;
			}
		});

		return options;
	},

	_events: {
		keydown: function( event ) {
			if ( this._start( event ) && this._keydown( event ) ) {
				event.preventDefault();
			}
		},
		keyup: "_stop",
		focus: function() {
			this.previous = this.element.val();
		},
		blur: function( event ) {
			if ( this.cancelBlur ) {
				delete this.cancelBlur;
				return;
			}

			this._stop();
			this._refresh();
			if ( this.previous !== this.element.val() ) {
				this._trigger( "change", event );
			}
		},
		mousewheel: function( event, delta ) {
			if ( !delta ) {
				return;
			}
			if ( !this.spinning && !this._start( event ) ) {
				return false;
			}

			this._spin( (delta > 0 ? 1 : -1) * this.options.step, event );
			clearTimeout( this.mousewheelTimer );
			this.mousewheelTimer = this._delay(function() {
				if ( this.spinning ) {
					this._stop( event );
				}
			}, 100 );
			event.preventDefault();
		},
		"mousedown .bk-ui-spinner-button": function( event ) {
			var previous;

			// We never want the buttons to have focus; whenever the user is
			// interacting with the spinner, the focus should be on the input.
			// If the input is focused then this.previous is properly set from
			// when the input first received focus. If the input is not focused
			// then we need to set this.previous based on the value before spinning.
			previous = this.element[0] === this.document[0].activeElement ?
				this.previous : this.element.val();
			function checkFocus() {
				var isActive = this.element[0] === this.document[0].activeElement;
				if ( !isActive ) {
					this.element.focus();
					this.previous = previous;
					// support: IE
					// IE sets focus asynchronously, so we need to check if focus
					// moved off of the input because the user clicked on the button.
					this._delay(function() {
						this.previous = previous;
					});
				}
			}

			// ensure focus is on (or stays on) the text field
			event.preventDefault();
			checkFocus.call( this );

			// support: IE
			// IE doesn't prevent moving focus even with event.preventDefault()
			// so we set a flag to know when we should ignore the blur event
			// and check (again) if focus moved off of the input.
			this.cancelBlur = true;
			this._delay(function() {
				delete this.cancelBlur;
				checkFocus.call( this );
			});

			if ( this._start( event ) === false ) {
				return;
			}

			this._repeat( null, $( event.currentTarget ).hasClass( "bk-ui-spinner-up" ) ? 1 : -1, event );
		},
		"mouseup .bk-ui-spinner-button": "_stop",
		"mouseenter .bk-ui-spinner-button": function( event ) {
			// button will add bk-ui-state-active if mouse was down while mouseleave and kept down
			if ( !$( event.currentTarget ).hasClass( "bk-ui-state-active" ) ) {
				return;
			}

			if ( this._start( event ) === false ) {
				return false;
			}
			this._repeat( null, $( event.currentTarget ).hasClass( "bk-ui-spinner-up" ) ? 1 : -1, event );
		},
		// TODO: do we really want to consider this a stop?
		// shouldn't we just stop the repeater and wait until mouseup before
		// we trigger the stop event?
		"mouseleave .bk-ui-spinner-button": "_stop"
	},

	_draw: function() {
		var uiSpinner = this.uiSpinner = this.element
			.addClass( "bk-ui-spinner-input" )
			.attr( "autocomplete", "off" )
			.wrap( this._uiSpinnerHtml() )
			.parent()
				// add buttons
				.append( this._buttonHtml() );

		this.element.attr( "role", "spinbutton" );

		// button bindings
		this.buttons = uiSpinner.find( ".bk-ui-spinner-button" )
			.attr( "tabIndex", -1 )
			.button()
			.removeClass( "bk-ui-corner-all" );

		// IE 6 doesn't understand height: 50% for the buttons
		// unless the wrapper has an explicit height
		if ( this.buttons.height() > Math.ceil( uiSpinner.height() * 0.5 ) &&
				uiSpinner.height() > 0 ) {
			uiSpinner.height( uiSpinner.height() );
		}

		// disable spinner if element was already disabled
		if ( this.options.disabled ) {
			this.disable();
		}
	},

	_keydown: function( event ) {
		var options = this.options,
			keyCode = $.ui.keyCode;

		switch ( event.keyCode ) {
		case keyCode.UP:
			this._repeat( null, 1, event );
			return true;
		case keyCode.DOWN:
			this._repeat( null, -1, event );
			return true;
		case keyCode.PAGE_UP:
			this._repeat( null, options.page, event );
			return true;
		case keyCode.PAGE_DOWN:
			this._repeat( null, -options.page, event );
			return true;
		}

		return false;
	},

	_uiSpinnerHtml: function() {
		return "<span class='bk-ui-spinner bk-ui-widget bk-ui-widget-content bk-ui-corner-all'></span>";
	},

	_buttonHtml: function() {
		return "" +
			"<a class='bk-ui-spinner-button bk-ui-spinner-up bk-ui-corner-tr'>" +
				"<span class='bk-ui-icon " + this.options.icons.up + "'>&#9650;</span>" +
			"</a>" +
			"<a class='bk-ui-spinner-button bk-ui-spinner-down bk-ui-corner-br'>" +
				"<span class='bk-ui-icon " + this.options.icons.down + "'>&#9660;</span>" +
			"</a>";
	},

	_start: function( event ) {
		if ( !this.spinning && this._trigger( "start", event ) === false ) {
			return false;
		}

		if ( !this.counter ) {
			this.counter = 1;
		}
		this.spinning = true;
		return true;
	},

	_repeat: function( i, steps, event ) {
		i = i || 500;

		clearTimeout( this.timer );
		this.timer = this._delay(function() {
			this._repeat( 40, steps, event );
		}, i );

		this._spin( steps * this.options.step, event );
	},

	_spin: function( step, event ) {
		var value = this.value() || 0;

		if ( !this.counter ) {
			this.counter = 1;
		}

		value = this._adjustValue( value + step * this._increment( this.counter ) );

		if ( !this.spinning || this._trigger( "spin", event, { value: value } ) !== false) {
			this._value( value );
			this.counter++;
		}
	},

	_increment: function( i ) {
		var incremental = this.options.incremental;

		if ( incremental ) {
			return $.isFunction( incremental ) ?
				incremental( i ) :
				Math.floor( i * i * i / 50000 - i * i / 500 + 17 * i / 200 + 1 );
		}

		return 1;
	},

	_precision: function() {
		var precision = this._precisionOf( this.options.step );
		if ( this.options.min !== null ) {
			precision = Math.max( precision, this._precisionOf( this.options.min ) );
		}
		return precision;
	},

	_precisionOf: function( num ) {
		var str = num.toString(),
			decimal = str.indexOf( "." );
		return decimal === -1 ? 0 : str.length - decimal - 1;
	},

	_adjustValue: function( value ) {
		var base, aboveMin,
			options = this.options;

		// make sure we're at a valid step
		// - find out where we are relative to the base (min or 0)
		base = options.min !== null ? options.min : 0;
		aboveMin = value - base;
		// - round to the nearest step
		aboveMin = Math.round(aboveMin / options.step) * options.step;
		// - rounding is based on 0, so adjust back to our base
		value = base + aboveMin;

		// fix precision from bad JS floating point math
		value = parseFloat( value.toFixed( this._precision() ) );

		// clamp the value
		if ( options.max !== null && value > options.max) {
			return options.max;
		}
		if ( options.min !== null && value < options.min ) {
			return options.min;
		}

		return value;
	},

	_stop: function( event ) {
		if ( !this.spinning ) {
			return;
		}

		clearTimeout( this.timer );
		clearTimeout( this.mousewheelTimer );
		this.counter = 0;
		this.spinning = false;
		this._trigger( "stop", event );
	},

	_setOption: function( key, value ) {
		if ( key === "culture" || key === "numberFormat" ) {
			var prevValue = this._parse( this.element.val() );
			this.options[ key ] = value;
			this.element.val( this._format( prevValue ) );
			return;
		}

		if ( key === "max" || key === "min" || key === "step" ) {
			if ( typeof value === "string" ) {
				value = this._parse( value );
			}
		}
		if ( key === "icons" ) {
			this.buttons.first().find( ".bk-ui-icon" )
				.removeClass( this.options.icons.up )
				.addClass( value.up );
			this.buttons.last().find( ".bk-ui-icon" )
				.removeClass( this.options.icons.down )
				.addClass( value.down );
		}

		this._super( key, value );

		if ( key === "disabled" ) {
			this.widget().toggleClass( "bk-ui-state-disabled", !!value );
			this.element.prop( "disabled", !!value );
			this.buttons.button( value ? "disable" : "enable" );
		}
	},

	_setOptions: spinner_modifier(function( options ) {
		this._super( options );
	}),

	_parse: function( val ) {
		if ( typeof val === "string" && val !== "" ) {
			val = window.Globalize && this.options.numberFormat ?
				Globalize.parseFloat( val, 10, this.options.culture ) : +val;
		}
		return val === "" || isNaN( val ) ? null : val;
	},

	_format: function( value ) {
		if ( value === "" ) {
			return "";
		}
		return window.Globalize && this.options.numberFormat ?
			Globalize.format( value, this.options.numberFormat, this.options.culture ) :
			value;
	},

	_refresh: function() {
		this.element.attr({
			"aria-valuemin": this.options.min,
			"aria-valuemax": this.options.max,
			// TODO: what should we do with values that can't be parsed?
			"aria-valuenow": this._parse( this.element.val() )
		});
	},

	isValid: function() {
		var value = this.value();

		// null is invalid
		if ( value === null ) {
			return false;
		}

		// if value gets adjusted, it's invalid
		return value === this._adjustValue( value );
	},

	// update the value without triggering change
	_value: function( value, allowAny ) {
		var parsed;
		if ( value !== "" ) {
			parsed = this._parse( value );
			if ( parsed !== null ) {
				if ( !allowAny ) {
					parsed = this._adjustValue( parsed );
				}
				value = this._format( parsed );
			}
		}
		this.element.val( value );
		this._refresh();
	},

	_destroy: function() {
		this.element
			.removeClass( "bk-ui-spinner-input" )
			.prop( "disabled", false )
			.removeAttr( "autocomplete" )
			.removeAttr( "role" )
			.removeAttr( "aria-valuemin" )
			.removeAttr( "aria-valuemax" )
			.removeAttr( "aria-valuenow" );
		this.uiSpinner.replaceWith( this.element );
	},

	stepUp: spinner_modifier(function( steps ) {
		this._stepUp( steps );
	}),
	_stepUp: function( steps ) {
		if ( this._start() ) {
			this._spin( (steps || 1) * this.options.step );
			this._stop();
		}
	},

	stepDown: spinner_modifier(function( steps ) {
		this._stepDown( steps );
	}),
	_stepDown: function( steps ) {
		if ( this._start() ) {
			this._spin( (steps || 1) * -this.options.step );
			this._stop();
		}
	},

	pageUp: spinner_modifier(function( pages ) {
		this._stepUp( (pages || 1) * this.options.page );
	}),

	pageDown: spinner_modifier(function( pages ) {
		this._stepDown( (pages || 1) * this.options.page );
	}),

	value: function( newVal ) {
		if ( !arguments.length ) {
			return this._parse( this.element.val() );
		}
		spinner_modifier( this._value ).call( this, newVal );
	},

	widget: function() {
		return this.uiSpinner;
	}
});

}));

(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('widget/cell_editors',["underscore", "jquery", "common/has_properties", "common/collection", "common/continuum_view", "jquery_ui/autocomplete", "jquery_ui/spinner"], function(_, $, HasProperties, Collection, ContinuumView) {
    var CellEditor, CellEditorCollection, CellEditorView, CheckboxEditor, CheckboxEditorView, CheckboxEditors, DateEditor, DateEditorView, DateEditors, IntEditor, IntEditorView, IntEditors, NumberEditor, NumberEditorView, NumberEditors, PercentEditor, PercentEditorView, PercentEditors, SelectEditor, SelectEditorView, SelectEditors, StringEditor, StringEditorView, StringEditors, TextEditor, TextEditorView, TextEditors, TimeEditor, TimeEditorView, TimeEditors, _ref, _ref1, _ref10, _ref11, _ref12, _ref13, _ref14, _ref15, _ref16, _ref17, _ref18, _ref19, _ref2, _ref20, _ref21, _ref22, _ref23, _ref24, _ref25, _ref26, _ref27, _ref28, _ref29, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8, _ref9;
    CellEditor = (function(_super) {
      __extends(CellEditor, _super);

      function CellEditor() {
        _ref = CellEditor.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      CellEditor.prototype.editorDefaults = {};

      CellEditor.prototype.defaults = function() {
        return _.extend({}, CellEditor.__super__.defaults.call(this), this.editorDefaults);
      };

      return CellEditor;

    })(HasProperties);
    CellEditorCollection = (function(_super) {
      __extends(CellEditorCollection, _super);

      function CellEditorCollection() {
        _ref1 = CellEditorCollection.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      return CellEditorCollection;

    })(Collection);
    CellEditorView = (function(_super) {
      __extends(CellEditorView, _super);

      function CellEditorView() {
        _ref2 = CellEditorView.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      CellEditorView.prototype.tagName = "div";

      CellEditorView.prototype.className = "bk-cell-editor";

      CellEditorView.prototype.input = null;

      CellEditorView.prototype.emptyValue = null;

      CellEditorView.prototype.defaultValue = null;

      CellEditorView.prototype.initialize = function(args) {
        CellEditorView.__super__.initialize.call(this, {});
        this.args = args;
        this.model = this.args.column.editor;
        return this.render();
      };

      CellEditorView.prototype.render = function() {
        this.$el.appendTo(this.args.container);
        this.$input = $(this.input);
        this.$el.append(this.$input);
        this.renderEditor();
        return this.disableNavigation();
      };

      CellEditorView.prototype.renderEditor = function() {};

      CellEditorView.prototype.disableNavigation = function() {
        var _this = this;
        return this.$input.keydown(function(event) {
          var stop;
          stop = function() {
            return event.stopImmediatePropagation();
          };
          switch (event.keyCode) {
            case $.ui.keyCode.LEFT:
              return stop();
            case $.ui.keyCode.RIGHT:
              return stop();
            case $.ui.keyCode.UP:
              return stop();
            case $.ui.keyCode.DOWN:
              return stop();
            case $.ui.keyCode.PAGE_UP:
              return stop();
            case $.ui.keyCode.PAGE_DOWN:
              return stop();
          }
        });
      };

      CellEditorView.prototype.destroy = function() {
        return this.remove();
      };

      CellEditorView.prototype.focus = function() {
        return this.$input.focus();
      };

      CellEditorView.prototype.show = function() {};

      CellEditorView.prototype.hide = function() {};

      CellEditorView.prototype.position = function() {};

      CellEditorView.prototype.getValue = function() {
        return this.$input.val();
      };

      CellEditorView.prototype.setValue = function(val) {
        return this.$input.val(val);
      };

      CellEditorView.prototype.serializeValue = function() {
        return this.getValue();
      };

      CellEditorView.prototype.isValueChanged = function() {
        return !(this.getValue() === "" && (this.defaultValue == null)) && (this.getValue() !== this.defaultValue);
      };

      CellEditorView.prototype.applyValue = function(item, state) {
        return this.args.grid.getData().setField(item.index, this.args.column.field, state);
      };

      CellEditorView.prototype.loadValue = function(item) {
        var value;
        value = item[this.args.column.field];
        this.defaultValue = value != null ? value : this.emptyValue;
        return this.setValue(this.defaultValue);
      };

      CellEditorView.prototype.validateValue = function(value) {
        var result;
        if (this.args.column.validator) {
          result = this.args.column.validator(value);
          if (!result.valid) {
            return result;
          }
        }
        return {
          valid: true,
          msg: null
        };
      };

      CellEditorView.prototype.validate = function() {
        return this.validateValue(this.getValue());
      };

      return CellEditorView;

    })(ContinuumView);
    StringEditorView = (function(_super) {
      __extends(StringEditorView, _super);

      function StringEditorView() {
        _ref3 = StringEditorView.__super__.constructor.apply(this, arguments);
        return _ref3;
      }

      StringEditorView.prototype.emptyValue = "";

      StringEditorView.prototype.input = '<input type="text" />';

      StringEditorView.prototype.renderEditor = function() {
        var completions;
        completions = this.model.get("completions");
        if (!_.isEmpty(completions)) {
          this.$input.autocomplete({
            source: completions
          });
          this.$input.autocomplete("widget").addClass("bk-cell-editor-completion");
        }
        return this.$input.focus().select();
      };

      StringEditorView.prototype.loadValue = function(item) {
        StringEditorView.__super__.loadValue.call(this, item);
        this.$input[0].defaultValue = this.defaultValue;
        return this.$input.select();
      };

      return StringEditorView;

    })(CellEditorView);
    StringEditor = (function(_super) {
      __extends(StringEditor, _super);

      function StringEditor() {
        _ref4 = StringEditor.__super__.constructor.apply(this, arguments);
        return _ref4;
      }

      StringEditor.prototype.type = 'StringEditor';

      StringEditor.prototype.default_view = StringEditorView;

      StringEditor.prototype.editorDefaults = {
        completions: []
      };

      return StringEditor;

    })(CellEditor);
    StringEditors = (function(_super) {
      __extends(StringEditors, _super);

      function StringEditors() {
        _ref5 = StringEditors.__super__.constructor.apply(this, arguments);
        return _ref5;
      }

      StringEditors.prototype.model = StringEditor;

      return StringEditors;

    })(CellEditorCollection);
    TextEditorView = (function(_super) {
      __extends(TextEditorView, _super);

      function TextEditorView() {
        _ref6 = TextEditorView.__super__.constructor.apply(this, arguments);
        return _ref6;
      }

      return TextEditorView;

    })(CellEditorView);
    TextEditor = (function(_super) {
      __extends(TextEditor, _super);

      function TextEditor() {
        _ref7 = TextEditor.__super__.constructor.apply(this, arguments);
        return _ref7;
      }

      TextEditor.prototype.type = 'TextEditor';

      TextEditor.prototype.default_view = TextEditorView;

      return TextEditor;

    })(CellEditor);
    TextEditors = (function(_super) {
      __extends(TextEditors, _super);

      function TextEditors() {
        _ref8 = TextEditors.__super__.constructor.apply(this, arguments);
        return _ref8;
      }

      TextEditors.prototype.model = TextEditor;

      return TextEditors;

    })(CellEditorCollection);
    SelectEditorView = (function(_super) {
      __extends(SelectEditorView, _super);

      function SelectEditorView() {
        _ref9 = SelectEditorView.__super__.constructor.apply(this, arguments);
        return _ref9;
      }

      SelectEditorView.prototype.input = '<select />';

      SelectEditorView.prototype.renderEditor = function() {
        var option, _i, _len, _ref10;
        _ref10 = this.model.get("options");
        for (_i = 0, _len = _ref10.length; _i < _len; _i++) {
          option = _ref10[_i];
          this.$input.append($('<option>').attr({
            value: option
          }).text(option));
        }
        return this.focus();
      };

      SelectEditorView.prototype.loadValue = function(item) {
        SelectEditorView.__super__.loadValue.call(this, item);
        return this.$input.select();
      };

      return SelectEditorView;

    })(CellEditorView);
    SelectEditor = (function(_super) {
      __extends(SelectEditor, _super);

      function SelectEditor() {
        _ref10 = SelectEditor.__super__.constructor.apply(this, arguments);
        return _ref10;
      }

      SelectEditor.prototype.type = 'SelectEditor';

      SelectEditor.prototype.default_view = SelectEditorView;

      SelectEditor.prototype.editorDefaults = {
        options: []
      };

      return SelectEditor;

    })(CellEditor);
    SelectEditors = (function(_super) {
      __extends(SelectEditors, _super);

      function SelectEditors() {
        _ref11 = SelectEditors.__super__.constructor.apply(this, arguments);
        return _ref11;
      }

      SelectEditors.prototype.model = SelectEditor;

      return SelectEditors;

    })(CellEditorCollection);
    PercentEditorView = (function(_super) {
      __extends(PercentEditorView, _super);

      function PercentEditorView() {
        _ref12 = PercentEditorView.__super__.constructor.apply(this, arguments);
        return _ref12;
      }

      return PercentEditorView;

    })(CellEditorView);
    PercentEditor = (function(_super) {
      __extends(PercentEditor, _super);

      function PercentEditor() {
        _ref13 = PercentEditor.__super__.constructor.apply(this, arguments);
        return _ref13;
      }

      PercentEditor.prototype.type = 'PercentEditor';

      PercentEditor.prototype.default_view = PercentEditorView;

      return PercentEditor;

    })(CellEditor);
    PercentEditors = (function(_super) {
      __extends(PercentEditors, _super);

      function PercentEditors() {
        _ref14 = PercentEditors.__super__.constructor.apply(this, arguments);
        return _ref14;
      }

      PercentEditors.prototype.model = PercentEditor;

      return PercentEditors;

    })(CellEditorCollection);
    CheckboxEditorView = (function(_super) {
      __extends(CheckboxEditorView, _super);

      function CheckboxEditorView() {
        _ref15 = CheckboxEditorView.__super__.constructor.apply(this, arguments);
        return _ref15;
      }

      CheckboxEditorView.prototype.input = '<input type="checkbox" value="true" />';

      CheckboxEditorView.prototype.renderEditor = function() {
        return this.focus();
      };

      CheckboxEditorView.prototype.loadValue = function(item) {
        this.defaultValue = !!item[this.args.column.field];
        return this.$input.prop('checked', this.defaultValue);
      };

      CheckboxEditorView.prototype.serializeValue = function() {
        return this.$input.prop('checked');
      };

      return CheckboxEditorView;

    })(CellEditorView);
    CheckboxEditor = (function(_super) {
      __extends(CheckboxEditor, _super);

      function CheckboxEditor() {
        _ref16 = CheckboxEditor.__super__.constructor.apply(this, arguments);
        return _ref16;
      }

      CheckboxEditor.prototype.type = 'CheckboxEditor';

      CheckboxEditor.prototype.default_view = CheckboxEditorView;

      return CheckboxEditor;

    })(CellEditor);
    CheckboxEditors = (function(_super) {
      __extends(CheckboxEditors, _super);

      function CheckboxEditors() {
        _ref17 = CheckboxEditors.__super__.constructor.apply(this, arguments);
        return _ref17;
      }

      CheckboxEditors.prototype.model = CheckboxEditor;

      return CheckboxEditors;

    })(CellEditorCollection);
    IntEditorView = (function(_super) {
      __extends(IntEditorView, _super);

      function IntEditorView() {
        _ref18 = IntEditorView.__super__.constructor.apply(this, arguments);
        return _ref18;
      }

      IntEditorView.prototype.input = '<input type="text" />';

      IntEditorView.prototype.renderEditor = function() {
        this.$input.spinner({
          step: this.model.get("step")
        });
        return this.$input.focus().select();
      };

      IntEditorView.prototype.remove = function() {
        this.$input.spinner("destroy");
        return IntEditorView.__super__.remove.call(this);
      };

      IntEditorView.prototype.serializeValue = function() {
        return parseInt(this.getValue(), 10) || 0;
      };

      IntEditorView.prototype.loadValue = function(item) {
        IntEditorView.__super__.loadValue.call(this, item);
        this.$input[0].defaultValue = this.defaultValue;
        return this.$input.select();
      };

      IntEditorView.prototype.validateValue = function(value) {
        if (isNaN(value)) {
          return {
            valid: false,
            msg: "Please enter a valid integer"
          };
        } else {
          return IntEditorView.__super__.validateValue.call(this, value);
        }
      };

      return IntEditorView;

    })(CellEditorView);
    IntEditor = (function(_super) {
      __extends(IntEditor, _super);

      function IntEditor() {
        _ref19 = IntEditor.__super__.constructor.apply(this, arguments);
        return _ref19;
      }

      IntEditor.prototype.type = 'IntEditor';

      IntEditor.prototype.default_view = IntEditorView;

      IntEditor.prototype.editorDefaults = {
        step: 1
      };

      return IntEditor;

    })(CellEditor);
    IntEditors = (function(_super) {
      __extends(IntEditors, _super);

      function IntEditors() {
        _ref20 = IntEditors.__super__.constructor.apply(this, arguments);
        return _ref20;
      }

      IntEditors.prototype.model = IntEditor;

      return IntEditors;

    })(CellEditorCollection);
    NumberEditorView = (function(_super) {
      __extends(NumberEditorView, _super);

      function NumberEditorView() {
        _ref21 = NumberEditorView.__super__.constructor.apply(this, arguments);
        return _ref21;
      }

      NumberEditorView.prototype.input = '<input type="text" />';

      NumberEditorView.prototype.renderEditor = function() {
        this.$input.spinner({
          step: this.model.get("step")
        });
        return this.$input.focus().select();
      };

      NumberEditorView.prototype.remove = function() {
        this.$input.spinner("destroy");
        return NumberEditorView.__super__.remove.call(this);
      };

      NumberEditorView.prototype.serializeValue = function() {
        return parseFloat(this.getValue()) || 0.0;
      };

      NumberEditorView.prototype.loadValue = function(item) {
        NumberEditorView.__super__.loadValue.call(this, item);
        this.$input[0].defaultValue = this.defaultValue;
        return this.$input.select();
      };

      NumberEditorView.prototype.validateValue = function(value) {
        if (isNaN(value)) {
          return {
            valid: false,
            msg: "Please enter a valid number"
          };
        } else {
          return NumberEditorView.__super__.validateValue.call(this, value);
        }
      };

      return NumberEditorView;

    })(CellEditorView);
    NumberEditor = (function(_super) {
      __extends(NumberEditor, _super);

      function NumberEditor() {
        _ref22 = NumberEditor.__super__.constructor.apply(this, arguments);
        return _ref22;
      }

      NumberEditor.prototype.type = 'NumberEditor';

      NumberEditor.prototype.default_view = NumberEditorView;

      NumberEditor.prototype.editorDefaults = {
        step: 0.01
      };

      return NumberEditor;

    })(CellEditor);
    NumberEditors = (function(_super) {
      __extends(NumberEditors, _super);

      function NumberEditors() {
        _ref23 = NumberEditors.__super__.constructor.apply(this, arguments);
        return _ref23;
      }

      NumberEditors.prototype.model = NumberEditor;

      return NumberEditors;

    })(CellEditorCollection);
    TimeEditorView = (function(_super) {
      __extends(TimeEditorView, _super);

      function TimeEditorView() {
        _ref24 = TimeEditorView.__super__.constructor.apply(this, arguments);
        return _ref24;
      }

      return TimeEditorView;

    })(CellEditorView);
    TimeEditor = (function(_super) {
      __extends(TimeEditor, _super);

      function TimeEditor() {
        _ref25 = TimeEditor.__super__.constructor.apply(this, arguments);
        return _ref25;
      }

      TimeEditor.prototype.type = 'TimeEditor';

      TimeEditor.prototype.default_view = TimeEditorView;

      return TimeEditor;

    })(CellEditor);
    TimeEditors = (function(_super) {
      __extends(TimeEditors, _super);

      function TimeEditors() {
        _ref26 = TimeEditors.__super__.constructor.apply(this, arguments);
        return _ref26;
      }

      TimeEditors.prototype.model = TimeEditor;

      return TimeEditors;

    })(CellEditorCollection);
    DateEditorView = (function(_super) {
      __extends(DateEditorView, _super);

      function DateEditorView() {
        _ref27 = DateEditorView.__super__.constructor.apply(this, arguments);
        return _ref27;
      }

      DateEditorView.prototype.emptyValue = new Date();

      DateEditorView.prototype.input = '<input type="text" />';

      DateEditorView.prototype.renderEditor = function() {
        var _this = this;
        this.calendarOpen = false;
        this.$input.datepicker({
          showOn: "button",
          buttonImageOnly: true,
          beforeShow: function() {
            return _this.calendarOpen = true;
          },
          onClose: function() {
            return _this.calendarOpen = false;
          }
        });
        this.$input.siblings(".bk-ui-datepicker-trigger").css({
          "vertical-align": "middle"
        });
        this.$input.width(this.$input.width() - (14 + 2 * 4 + 4));
        return this.$input.focus().select();
      };

      DateEditorView.prototype.destroy = function() {
        $.datepicker.dpDiv.stop(true, true);
        this.$input.datepicker("hide");
        this.$input.datepicker("destroy");
        return DateEditorView.__super__.destroy.call(this);
      };

      DateEditorView.prototype.show = function() {
        if (this.calendarOpen) {
          $.datepicker.dpDiv.stop(true, true).show();
        }
        return DateEditorView.__super__.show.call(this);
      };

      DateEditorView.prototype.hide = function() {
        if (this.calendarOpen) {
          $.datepicker.dpDiv.stop(true, true).hide();
        }
        return DateEditorView.__super__.hide.call(this);
      };

      DateEditorView.prototype.position = function(position) {
        if (this.calendarOpen) {
          $.datepicker.dpDiv.css({
            top: position.top + 30,
            left: position.left
          });
        }
        return DateEditorView.__super__.position.call(this);
      };

      DateEditorView.prototype.getValue = function() {
        return this.$input.datepicker("getDate").getTime();
      };

      DateEditorView.prototype.setValue = function(val) {
        return this.$input.datepicker("setDate", new Date(val));
      };

      return DateEditorView;

    })(CellEditorView);
    DateEditor = (function(_super) {
      __extends(DateEditor, _super);

      function DateEditor() {
        _ref28 = DateEditor.__super__.constructor.apply(this, arguments);
        return _ref28;
      }

      DateEditor.prototype.type = 'DateEditor';

      DateEditor.prototype.default_view = DateEditorView;

      return DateEditor;

    })(CellEditor);
    DateEditors = (function(_super) {
      __extends(DateEditors, _super);

      function DateEditors() {
        _ref29 = DateEditors.__super__.constructor.apply(this, arguments);
        return _ref29;
      }

      DateEditors.prototype.model = DateEditor;

      return DateEditors;

    })(CellEditorCollection);
    return {
      String: {
        Model: StringEditor,
        Collection: new StringEditors(),
        View: StringEditorView
      },
      Text: {
        Model: TextEditor,
        Collection: new TextEditors(),
        View: TextEditorView
      },
      Select: {
        Model: SelectEditor,
        Collection: new SelectEditors(),
        View: SelectEditorView
      },
      Percent: {
        Model: PercentEditor,
        Collection: new PercentEditors(),
        View: PercentEditorView
      },
      Checkbox: {
        Model: CheckboxEditor,
        Collection: new CheckboxEditors(),
        View: CheckboxEditorView
      },
      Int: {
        Model: IntEditor,
        Collection: new IntEditors(),
        View: IntEditorView
      },
      Number: {
        Model: NumberEditor,
        Collection: new NumberEditors(),
        View: NumberEditorView
      },
      Time: {
        Model: TimeEditor,
        Collection: new TimeEditors(),
        View: TimeEditorView
      },
      Date: {
        Model: DateEditor,
        Collection: new DateEditors(),
        View: DateEditorView
      }
    };
  });

}).call(this);

/*
//@ sourceMappingURL=cell_editors.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('widget/table_column',["underscore", "common/has_properties", "common/collection"], function(_, HasProperties, Collection) {
    var TableColumn, TableColumns, _ref, _ref1;
    TableColumn = (function(_super) {
      __extends(TableColumn, _super);

      function TableColumn() {
        _ref = TableColumn.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      TableColumn.prototype.type = 'TableColumn';

      TableColumn.prototype.default_view = null;

      TableColumn.prototype.defaults = function() {
        return _.extend({}, TableColumn.__super__.defaults.call(this), {
          field: null,
          title: null,
          width: 300,
          formatter: null,
          editor: null,
          sortable: true,
          default_sort: "ascending"
        });
      };

      TableColumn.prototype.toColumn = function() {
        return {
          id: _.uniqueId(),
          field: this.get("field"),
          name: this.get("title"),
          width: this.get("width"),
          formatter: this.get("formatter"),
          editor: this.get("editor"),
          sortable: this.get("sortable"),
          defaultSortAsc: this.get("default_sort") === "ascending"
        };
      };

      return TableColumn;

    })(HasProperties);
    TableColumns = (function(_super) {
      __extends(TableColumns, _super);

      function TableColumns() {
        _ref1 = TableColumns.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      TableColumns.prototype.model = TableColumn;

      return TableColumns;

    })(Collection);
    return {
      Model: TableColumn,
      Collection: new TableColumns()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=table_column.js.map
*/;
(function() {
  define('util/dom_util',["underscore", "jquery"], function(_, $) {
    var waitForElement;
    waitForElement = function(el, fn) {
      var handler, interval,
        _this = this;
      handler = function() {
        if ($.contains(document.documentElement, el)) {
          clearInterval(interval);
          return fn();
        }
      };
      return interval = setInterval(handler, 50);
    };
    return {
      waitForElement: waitForElement
    };
  });

}).call(this);

/*
//@ sourceMappingURL=dom_util.js.map
*/;
/***
 * Contains core SlickGrid classes.
 * @module Core
 * @namespace Slick
 */

define('slick_grid/slick.core',["jquery"], function($) {

  // register namespace
  var Slick = {
    Event: Event,
    EventData: EventData,
    EventHandler: EventHandler,
    Range: Range,
    NonDataRow: NonDataItem,
    Group: Group,
    GroupTotals: GroupTotals,
    EditorLock: EditorLock,

      /***
       * A global singleton editor lock.
       * @class GlobalEditorLock
       * @static
       * @constructor
       */
    GlobalEditorLock: new EditorLock()
  };

  /***
   * An event object for passing data to event handlers and letting them control propagation.
   * <p>This is pretty much identical to how W3C and jQuery implement events.</p>
   * @class EventData
   * @constructor
   */
  function EventData() {
    var isPropagationStopped = false;
    var isImmediatePropagationStopped = false;

    /***
     * Stops event from propagating up the DOM tree.
     * @method stopPropagation
     */
    this.stopPropagation = function () {
      isPropagationStopped = true;
    };

    /***
     * Returns whether stopPropagation was called on this event object.
     * @method isPropagationStopped
     * @return {Boolean}
     */
    this.isPropagationStopped = function () {
      return isPropagationStopped;
    };

    /***
     * Prevents the rest of the handlers from being executed.
     * @method stopImmediatePropagation
     */
    this.stopImmediatePropagation = function () {
      isImmediatePropagationStopped = true;
    };

    /***
     * Returns whether stopImmediatePropagation was called on this event object.\
     * @method isImmediatePropagationStopped
     * @return {Boolean}
     */
    this.isImmediatePropagationStopped = function () {
      return isImmediatePropagationStopped;
    }
  }

  /***
   * A simple publisher-subscriber implementation.
   * @class Event
   * @constructor
   */
  function Event() {
    var handlers = [];

    /***
     * Adds an event handler to be called when the event is fired.
     * <p>Event handler will receive two arguments - an <code>EventData</code> and the <code>data</code>
     * object the event was fired with.<p>
     * @method subscribe
     * @param fn {Function} Event handler.
     */
    this.subscribe = function (fn) {
      handlers.push(fn);
    };

    /***
     * Removes an event handler added with <code>subscribe(fn)</code>.
     * @method unsubscribe
     * @param fn {Function} Event handler to be removed.
     */
    this.unsubscribe = function (fn) {
      for (var i = handlers.length - 1; i >= 0; i--) {
        if (handlers[i] === fn) {
          handlers.splice(i, 1);
        }
      }
    };

    /***
     * Fires an event notifying all subscribers.
     * @method notify
     * @param args {Object} Additional data object to be passed to all handlers.
     * @param e {EventData}
     *      Optional.
     *      An <code>EventData</code> object to be passed to all handlers.
     *      For DOM events, an existing W3C/jQuery event object can be passed in.
     * @param scope {Object}
     *      Optional.
     *      The scope ("this") within which the handler will be executed.
     *      If not specified, the scope will be set to the <code>Event</code> instance.
     */
    this.notify = function (args, e, scope) {
      e = e || new EventData();
      scope = scope || this;

      var returnValue;
      for (var i = 0; i < handlers.length && !(e.isPropagationStopped() || e.isImmediatePropagationStopped()); i++) {
        returnValue = handlers[i].call(scope, e, args);
      }

      return returnValue;
    };
  }

  function EventHandler() {
    var handlers = [];

    this.subscribe = function (event, handler) {
      handlers.push({
        event: event,
        handler: handler
      });
      event.subscribe(handler);

      return this;  // allow chaining
    };

    this.unsubscribe = function (event, handler) {
      var i = handlers.length;
      while (i--) {
        if (handlers[i].event === event &&
            handlers[i].handler === handler) {
          handlers.splice(i, 1);
          event.unsubscribe(handler);
          return;
        }
      }

      return this;  // allow chaining
    };

    this.unsubscribeAll = function () {
      var i = handlers.length;
      while (i--) {
        handlers[i].event.unsubscribe(handlers[i].handler);
      }
      handlers = [];

      return this;  // allow chaining
    }
  }

  /***
   * A structure containing a range of cells.
   * @class Range
   * @constructor
   * @param fromRow {Integer} Starting row.
   * @param fromCell {Integer} Starting cell.
   * @param toRow {Integer} Optional. Ending row. Defaults to <code>fromRow</code>.
   * @param toCell {Integer} Optional. Ending cell. Defaults to <code>fromCell</code>.
   */
  function Range(fromRow, fromCell, toRow, toCell) {
    if (toRow === undefined && toCell === undefined) {
      toRow = fromRow;
      toCell = fromCell;
    }

    /***
     * @property fromRow
     * @type {Integer}
     */
    this.fromRow = Math.min(fromRow, toRow);

    /***
     * @property fromCell
     * @type {Integer}
     */
    this.fromCell = Math.min(fromCell, toCell);

    /***
     * @property toRow
     * @type {Integer}
     */
    this.toRow = Math.max(fromRow, toRow);

    /***
     * @property toCell
     * @type {Integer}
     */
    this.toCell = Math.max(fromCell, toCell);

    /***
     * Returns whether a range represents a single row.
     * @method isSingleRow
     * @return {Boolean}
     */
    this.isSingleRow = function () {
      return this.fromRow == this.toRow;
    };

    /***
     * Returns whether a range represents a single cell.
     * @method isSingleCell
     * @return {Boolean}
     */
    this.isSingleCell = function () {
      return this.fromRow == this.toRow && this.fromCell == this.toCell;
    };

    /***
     * Returns whether a range contains a given cell.
     * @method contains
     * @param row {Integer}
     * @param cell {Integer}
     * @return {Boolean}
     */
    this.contains = function (row, cell) {
      return row >= this.fromRow && row <= this.toRow &&
          cell >= this.fromCell && cell <= this.toCell;
    };

    /***
     * Returns a readable representation of a range.
     * @method toString
     * @return {String}
     */
    this.toString = function () {
      if (this.isSingleCell()) {
        return "(" + this.fromRow + ":" + this.fromCell + ")";
      }
      else {
        return "(" + this.fromRow + ":" + this.fromCell + " - " + this.toRow + ":" + this.toCell + ")";
      }
    }
  }


  /***
   * A base class that all special / non-data rows (like Group and GroupTotals) derive from.
   * @class NonDataItem
   * @constructor
   */
  function NonDataItem() {
    this.__nonDataRow = true;
  }


  /***
   * Information about a group of rows.
   * @class Group
   * @extends Slick.NonDataItem
   * @constructor
   */
  function Group() {
    this.__group = true;

    /**
     * Grouping level, starting with 0.
     * @property level
     * @type {Number}
     */
    this.level = 0;

    /***
     * Number of rows in the group.
     * @property count
     * @type {Integer}
     */
    this.count = 0;

    /***
     * Grouping value.
     * @property value
     * @type {Object}
     */
    this.value = null;

    /***
     * Formatted display value of the group.
     * @property title
     * @type {String}
     */
    this.title = null;

    /***
     * Whether a group is collapsed.
     * @property collapsed
     * @type {Boolean}
     */
    this.collapsed = false;

    /***
     * GroupTotals, if any.
     * @property totals
     * @type {GroupTotals}
     */
    this.totals = null;

    /**
     * Rows that are part of the group.
     * @property rows
     * @type {Array}
     */
    this.rows = [];

    /**
     * Sub-groups that are part of the group.
     * @property groups
     * @type {Array}
     */
    this.groups = null;

    /**
     * A unique key used to identify the group.  This key can be used in calls to DataView
     * collapseGroup() or expandGroup().
     * @property groupingKey
     * @type {Object}
     */
    this.groupingKey = null;
  }

  Group.prototype = new NonDataItem();

  /***
   * Compares two Group instances.
   * @method equals
   * @return {Boolean}
   * @param group {Group} Group instance to compare to.
   */
  Group.prototype.equals = function (group) {
    return this.value === group.value &&
        this.count === group.count &&
        this.collapsed === group.collapsed &&
        this.title === group.title;
  };

  /***
   * Information about group totals.
   * An instance of GroupTotals will be created for each totals row and passed to the aggregators
   * so that they can store arbitrary data in it.  That data can later be accessed by group totals
   * formatters during the display.
   * @class GroupTotals
   * @extends Slick.NonDataItem
   * @constructor
   */
  function GroupTotals() {
    this.__groupTotals = true;

    /***
     * Parent Group.
     * @param group
     * @type {Group}
     */
    this.group = null;

    /***
     * Whether the totals have been fully initialized / calculated.
     * Will be set to false for lazy-calculated group totals.
     * @param initialized
     * @type {Boolean}
     */
    this.initialized = false;
  }

  GroupTotals.prototype = new NonDataItem();

  /***
   * A locking helper to track the active edit controller and ensure that only a single controller
   * can be active at a time.  This prevents a whole class of state and validation synchronization
   * issues.  An edit controller (such as SlickGrid) can query if an active edit is in progress
   * and attempt a commit or cancel before proceeding.
   * @class EditorLock
   * @constructor
   */
  function EditorLock() {
    var activeEditController = null;

    /***
     * Returns true if a specified edit controller is active (has the edit lock).
     * If the parameter is not specified, returns true if any edit controller is active.
     * @method isActive
     * @param editController {EditController}
     * @return {Boolean}
     */
    this.isActive = function (editController) {
      return (editController ? activeEditController === editController : activeEditController !== null);
    };

    /***
     * Sets the specified edit controller as the active edit controller (acquire edit lock).
     * If another edit controller is already active, and exception will be thrown.
     * @method activate
     * @param editController {EditController} edit controller acquiring the lock
     */
    this.activate = function (editController) {
      if (editController === activeEditController) { // already activated?
        return;
      }
      if (activeEditController !== null) {
        throw "SlickGrid.EditorLock.activate: an editController is still active, can't activate another editController";
      }
      if (!editController.commitCurrentEdit) {
        throw "SlickGrid.EditorLock.activate: editController must implement .commitCurrentEdit()";
      }
      if (!editController.cancelCurrentEdit) {
        throw "SlickGrid.EditorLock.activate: editController must implement .cancelCurrentEdit()";
      }
      activeEditController = editController;
    };

    /***
     * Unsets the specified edit controller as the active edit controller (release edit lock).
     * If the specified edit controller is not the active one, an exception will be thrown.
     * @method deactivate
     * @param editController {EditController} edit controller releasing the lock
     */
    this.deactivate = function (editController) {
      if (activeEditController !== editController) {
        throw "SlickGrid.EditorLock.deactivate: specified editController is not the currently active one";
      }
      activeEditController = null;
    };

    /***
     * Attempts to commit the current edit by calling "commitCurrentEdit" method on the active edit
     * controller and returns whether the commit attempt was successful (commit may fail due to validation
     * errors, etc.).  Edit controller's "commitCurrentEdit" must return true if the commit has succeeded
     * and false otherwise.  If no edit controller is active, returns true.
     * @method commitCurrentEdit
     * @return {Boolean}
     */
    this.commitCurrentEdit = function () {
      return (activeEditController ? activeEditController.commitCurrentEdit() : true);
    };

    /***
     * Attempts to cancel the current edit by calling "cancelCurrentEdit" method on the active edit
     * controller and returns whether the edit was successfully cancelled.  If no edit controller is
     * active, returns true.
     * @method cancelCurrentEdit
     * @return {Boolean}
     */
    this.cancelCurrentEdit = function cancelCurrentEdit() {
      return (activeEditController ? activeEditController.cancelCurrentEdit() : true);
    };
  }

  return Slick;
});

(function(root) {
define("jquery_event_drag", ["jquery"], function() {
  return (function() {
/*! 
 * jquery.event.drag - v 2.2
 * Copyright (c) 2010 Three Dub Media - http://threedubmedia.com
 * Open Source MIT License - http://threedubmedia.com/code/license
 */
// Created: 2008-06-04 
// Updated: 2012-05-21
// REQUIRES: jquery 1.7.x

;(function( $ ){

// add the jquery instance method
$.fn.drag = function( str, arg, opts ){
	// figure out the event type
	var type = typeof str == "string" ? str : "",
	// figure out the event handler...
	fn = $.isFunction( str ) ? str : $.isFunction( arg ) ? arg : null;
	// fix the event type
	if ( type.indexOf("drag") !== 0 ) 
		type = "drag"+ type;
	// were options passed
	opts = ( str == fn ? arg : opts ) || {};
	// trigger or bind event handler
	return fn ? this.bind( type, opts, fn ) : this.trigger( type );
};

// local refs (increase compression)
var $event = $.event, 
$special = $event.special,
// configure the drag special event 
drag = $special.drag = {
	
	// these are the default settings
	defaults: {
		which: 1, // mouse button pressed to start drag sequence
		distance: 0, // distance dragged before dragstart
		not: ':input', // selector to suppress dragging on target elements
		handle: null, // selector to match handle target elements
		relative: false, // true to use "position", false to use "offset"
		drop: true, // false to suppress drop events, true or selector to allow
		click: false // false to suppress click events after dragend (no proxy)
	},
	
	// the key name for stored drag data
	datakey: "dragdata",
	
	// prevent bubbling for better performance
	noBubble: true,
	
	// count bound related events
	add: function( obj ){ 
		// read the interaction data
		var data = $.data( this, drag.datakey ),
		// read any passed options 
		opts = obj.data || {};
		// count another realted event
		data.related += 1;
		// extend data options bound with this event
		// don't iterate "opts" in case it is a node 
		$.each( drag.defaults, function( key, def ){
			if ( opts[ key ] !== undefined )
				data[ key ] = opts[ key ];
		});
	},
	
	// forget unbound related events
	remove: function(){
		$.data( this, drag.datakey ).related -= 1;
	},
	
	// configure interaction, capture settings
	setup: function(){
		// check for related events
		if ( $.data( this, drag.datakey ) ) 
			return;
		// initialize the drag data with copied defaults
		var data = $.extend({ related:0 }, drag.defaults );
		// store the interaction data
		$.data( this, drag.datakey, data );
		// bind the mousedown event, which starts drag interactions
		$event.add( this, "touchstart mousedown", drag.init, data );
		// prevent image dragging in IE...
		if ( this.attachEvent ) 
			this.attachEvent("ondragstart", drag.dontstart ); 
	},
	
	// destroy configured interaction
	teardown: function(){
		var data = $.data( this, drag.datakey ) || {};
		// check for related events
		if ( data.related ) 
			return;
		// remove the stored data
		$.removeData( this, drag.datakey );
		// remove the mousedown event
		$event.remove( this, "touchstart mousedown", drag.init );
		// enable text selection
		drag.textselect( true ); 
		// un-prevent image dragging in IE...
		if ( this.detachEvent ) 
			this.detachEvent("ondragstart", drag.dontstart ); 
	},
		
	// initialize the interaction
	init: function( event ){ 
		// sorry, only one touch at a time
		if ( drag.touched ) 
			return;
		// the drag/drop interaction data
		var dd = event.data, results;
		// check the which directive
		if ( event.which != 0 && dd.which > 0 && event.which != dd.which ) 
			return; 
		// check for suppressed selector
		if ( $( event.target ).is( dd.not ) ) 
			return;
		// check for handle selector
		if ( dd.handle && !$( event.target ).closest( dd.handle, event.currentTarget ).length ) 
			return;

		drag.touched = event.type == 'touchstart' ? this : null;
		dd.propagates = 1;
		dd.mousedown = this;
		dd.interactions = [ drag.interaction( this, dd ) ];
		dd.target = event.target;
		dd.pageX = event.pageX;
		dd.pageY = event.pageY;
		dd.dragging = null;
		// handle draginit event... 
		results = drag.hijack( event, "draginit", dd );
		// early cancel
		if ( !dd.propagates )
			return;
		// flatten the result set
		results = drag.flatten( results );
		// insert new interaction elements
		if ( results && results.length ){
			dd.interactions = [];
			$.each( results, function(){
				dd.interactions.push( drag.interaction( this, dd ) );
			});
		}
		// remember how many interactions are propagating
		dd.propagates = dd.interactions.length;
		// locate and init the drop targets
		if ( dd.drop !== false && $special.drop ) 
			$special.drop.handler( event, dd );
		// disable text selection
		drag.textselect( false ); 
		// bind additional events...
		if ( drag.touched )
			$event.add( drag.touched, "touchmove touchend", drag.handler, dd );
		else 
			$event.add( document, "mousemove mouseup", drag.handler, dd );
		// helps prevent text selection or scrolling
		if ( !drag.touched || dd.live )
			return false;
	},	
	
	// returns an interaction object
	interaction: function( elem, dd ){
		var offset = $( elem )[ dd.relative ? "position" : "offset" ]() || { top:0, left:0 };
		return {
			drag: elem, 
			callback: new drag.callback(), 
			droppable: [],
			offset: offset
		};
	},
	
	// handle drag-releatd DOM events
	handler: function( event ){ 
		// read the data before hijacking anything
		var dd = event.data;	
		// handle various events
		switch ( event.type ){
			// mousemove, check distance, start dragging
			case !dd.dragging && 'touchmove': 
				event.preventDefault();
			case !dd.dragging && 'mousemove':
				//  drag tolerance, x≤ + y≤ = distance≤
				if ( Math.pow(  event.pageX-dd.pageX, 2 ) + Math.pow(  event.pageY-dd.pageY, 2 ) < Math.pow( dd.distance, 2 ) ) 
					break; // distance tolerance not reached
				event.target = dd.target; // force target from "mousedown" event (fix distance issue)
				drag.hijack( event, "dragstart", dd ); // trigger "dragstart"
				if ( dd.propagates ) // "dragstart" not rejected
					dd.dragging = true; // activate interaction
			// mousemove, dragging
			case 'touchmove':
				event.preventDefault();
			case 'mousemove':
				if ( dd.dragging ){
					// trigger "drag"		
					drag.hijack( event, "drag", dd );
					if ( dd.propagates ){
						// manage drop events
						if ( dd.drop !== false && $special.drop )
							$special.drop.handler( event, dd ); // "dropstart", "dropend"							
						break; // "drag" not rejected, stop		
					}
					event.type = "mouseup"; // helps "drop" handler behave
				}
			// mouseup, stop dragging
			case 'touchend': 
			case 'mouseup': 
			default:
				if ( drag.touched )
					$event.remove( drag.touched, "touchmove touchend", drag.handler ); // remove touch events
				else 
					$event.remove( document, "mousemove mouseup", drag.handler ); // remove page events	
				if ( dd.dragging ){
					if ( dd.drop !== false && $special.drop )
						$special.drop.handler( event, dd ); // "drop"
					drag.hijack( event, "dragend", dd ); // trigger "dragend"	
				}
				drag.textselect( true ); // enable text selection
				// if suppressing click events...
				if ( dd.click === false && dd.dragging )
					$.data( dd.mousedown, "suppress.click", new Date().getTime() + 5 );
				dd.dragging = drag.touched = false; // deactivate element	
				break;
		}
	},
		
	// re-use event object for custom events
	hijack: function( event, type, dd, x, elem ){
		// not configured
		if ( !dd ) 
			return;
		// remember the original event and type
		var orig = { event:event.originalEvent, type:event.type },
		// is the event drag related or drog related?
		mode = type.indexOf("drop") ? "drag" : "drop",
		// iteration vars
		result, i = x || 0, ia, $elems, callback,
		len = !isNaN( x ) ? x : dd.interactions.length;
		// modify the event type
		event.type = type;
		// remove the original event
		event.originalEvent = null;
		// initialize the results
		dd.results = [];
		// handle each interacted element
		do if ( ia = dd.interactions[ i ] ){
			// validate the interaction
			if ( type !== "dragend" && ia.cancelled )
				continue;
			// set the dragdrop properties on the event object
			callback = drag.properties( event, dd, ia );
			// prepare for more results
			ia.results = [];
			// handle each element
			$( elem || ia[ mode ] || dd.droppable ).each(function( p, subject ){
				// identify drag or drop targets individually
				callback.target = subject;
				// force propagtion of the custom event
				event.isPropagationStopped = function(){ return false; };
				// handle the event	
				result = subject ? $event.dispatch.call( subject, event, callback ) : null;
				// stop the drag interaction for this element
				if ( result === false ){
					if ( mode == "drag" ){
						ia.cancelled = true;
						dd.propagates -= 1;
					}
					if ( type == "drop" ){
						ia[ mode ][p] = null;
					}
				}
				// assign any dropinit elements
				else if ( type == "dropinit" )
					ia.droppable.push( drag.element( result ) || subject );
				// accept a returned proxy element 
				if ( type == "dragstart" )
					ia.proxy = $( drag.element( result ) || ia.drag )[0];
				// remember this result	
				ia.results.push( result );
				// forget the event result, for recycling
				delete event.result;
				// break on cancelled handler
				if ( type !== "dropinit" )
					return result;
			});	
			// flatten the results	
			dd.results[ i ] = drag.flatten( ia.results );	
			// accept a set of valid drop targets
			if ( type == "dropinit" )
				ia.droppable = drag.flatten( ia.droppable );
			// locate drop targets
			if ( type == "dragstart" && !ia.cancelled )
				callback.update(); 
		}
		while ( ++i < len )
		// restore the original event & type
		event.type = orig.type;
		event.originalEvent = orig.event;
		// return all handler results
		return drag.flatten( dd.results );
	},
		
	// extend the callback object with drag/drop properties...
	properties: function( event, dd, ia ){		
		var obj = ia.callback;
		// elements
		obj.drag = ia.drag;
		obj.proxy = ia.proxy || ia.drag;
		// starting mouse position
		obj.startX = dd.pageX;
		obj.startY = dd.pageY;
		// current distance dragged
		obj.deltaX = event.pageX - dd.pageX;
		obj.deltaY = event.pageY - dd.pageY;
		// original element position
		obj.originalX = ia.offset.left;
		obj.originalY = ia.offset.top;
		// adjusted element position
		obj.offsetX = obj.originalX + obj.deltaX; 
		obj.offsetY = obj.originalY + obj.deltaY;
		// assign the drop targets information
		obj.drop = drag.flatten( ( ia.drop || [] ).slice() );
		obj.available = drag.flatten( ( ia.droppable || [] ).slice() );
		return obj;	
	},
	
	// determine is the argument is an element or jquery instance
	element: function( arg ){
		if ( arg && ( arg.jquery || arg.nodeType == 1 ) )
			return arg;
	},
	
	// flatten nested jquery objects and arrays into a single dimension array
	flatten: function( arr ){
		return $.map( arr, function( member ){
			return member && member.jquery ? $.makeArray( member ) : 
				member && member.length ? drag.flatten( member ) : member;
		});
	},
	
	// toggles text selection attributes ON (true) or OFF (false)
	textselect: function( bool ){ 
		$( document )[ bool ? "unbind" : "bind" ]("selectstart", drag.dontstart )
			.css("MozUserSelect", bool ? "" : "none" );
		// .attr("unselectable", bool ? "off" : "on" )
		document.unselectable = bool ? "off" : "on"; 
	},
	
	// suppress "selectstart" and "ondragstart" events
	dontstart: function(){ 
		return false; 
	},
	
	// a callback instance contructor
	callback: function(){}
	
};

// callback methods
drag.callback.prototype = {
	update: function(){
		if ( $special.drop && this.available.length )
			$.each( this.available, function( i ){
				$special.drop.locate( this, i );
			});
	}
};

// patch $.event.$dispatch to allow suppressing clicks
var $dispatch = $event.dispatch;
$event.dispatch = function( event ){
	if ( $.data( this, "suppress."+ event.type ) - new Date().getTime() > 0 ){
		$.removeData( this, "suppress."+ event.type );
		return;
	}
	return $dispatch.apply( this, arguments );
};

// event fix hooks for touch events...
var touchHooks = 
$event.fixHooks.touchstart = 
$event.fixHooks.touchmove = 
$event.fixHooks.touchend =
$event.fixHooks.touchcancel = {
	props: "clientX clientY pageX pageY screenX screenY".split( " " ),
	filter: function( event, orig ) {
		if ( orig ){
			var touched = ( orig.touches && orig.touches[0] )
				|| ( orig.changedTouches && orig.changedTouches[0] )
				|| null; 
			// iOS webkit: touchstart, touchmove, touchend
			if ( touched ) 
				$.each( touchHooks.props, function( i, prop ){
					event[ prop ] = touched[ prop ];
				});
		}
		return event;
	}
};

// share the same special event configuration with related events...
$special.draginit = $special.dragstart = $special.dragend = drag;

})( jQuery );
return $.fn.drag;
  }).apply(root, arguments);
});
}(this));

(function(root) {
define("jquery_event_drop", ["jquery"], function() {
  return (function() {
/*! 
 * jquery.event.drop - v 2.2
 * Copyright (c) 2010 Three Dub Media - http://threedubmedia.com
 * Open Source MIT License - http://threedubmedia.com/code/license
 */
// Created: 2008-06-04 
// Updated: 2012-05-21
// REQUIRES: jquery 1.7.x, event.drag 2.2

;(function($){ // secure $ jQuery alias

// Events: drop, dropstart, dropend

// add the jquery instance method
$.fn.drop = function( str, arg, opts ){
	// figure out the event type
	var type = typeof str == "string" ? str : "",
	// figure out the event handler...
	fn = $.isFunction( str ) ? str : $.isFunction( arg ) ? arg : null;
	// fix the event type
	if ( type.indexOf("drop") !== 0 ) 
		type = "drop"+ type;
	// were options passed
	opts = ( str == fn ? arg : opts ) || {};
	// trigger or bind event handler
	return fn ? this.bind( type, opts, fn ) : this.trigger( type );
};

// DROP MANAGEMENT UTILITY
// returns filtered drop target elements, caches their positions
$.drop = function( opts ){ 
	opts = opts || {};
	// safely set new options...
	drop.multi = opts.multi === true ? Infinity : 
		opts.multi === false ? 1 : !isNaN( opts.multi ) ? opts.multi : drop.multi;
	drop.delay = opts.delay || drop.delay;
	drop.tolerance = $.isFunction( opts.tolerance ) ? opts.tolerance : 
		opts.tolerance === null ? null : drop.tolerance;
	drop.mode = opts.mode || drop.mode || 'intersect';
};

// local refs (increase compression)
var $event = $.event, 
$special = $event.special,
// configure the drop special event
drop = $.event.special.drop = {

	// these are the default settings
	multi: 1, // allow multiple drop winners per dragged element
	delay: 20, // async timeout delay
	mode: 'overlap', // drop tolerance mode
		
	// internal cache
	targets: [], 
	
	// the key name for stored drop data
	datakey: "dropdata",
		
	// prevent bubbling for better performance
	noBubble: true,
	
	// count bound related events
	add: function( obj ){ 
		// read the interaction data
		var data = $.data( this, drop.datakey );
		// count another realted event
		data.related += 1;
	},
	
	// forget unbound related events
	remove: function(){
		$.data( this, drop.datakey ).related -= 1;
	},
	
	// configure the interactions
	setup: function(){
		// check for related events
		if ( $.data( this, drop.datakey ) ) 
			return;
		// initialize the drop element data
		var data = { 
			related: 0,
			active: [],
			anyactive: 0,
			winner: 0,
			location: {}
		};
		// store the drop data on the element
		$.data( this, drop.datakey, data );
		// store the drop target in internal cache
		drop.targets.push( this );
	},
	
	// destroy the configure interaction	
	teardown: function(){ 
		var data = $.data( this, drop.datakey ) || {};
		// check for related events
		if ( data.related ) 
			return;
		// remove the stored data
		$.removeData( this, drop.datakey );
		// reference the targeted element
		var element = this;
		// remove from the internal cache
		drop.targets = $.grep( drop.targets, function( target ){ 
			return ( target !== element ); 
		});
	},
	
	// shared event handler
	handler: function( event, dd ){ 
		// local vars
		var results, $targets;
		// make sure the right data is available
		if ( !dd ) 
			return;
		// handle various events
		switch ( event.type ){
			// draginit, from $.event.special.drag
			case 'mousedown': // DROPINIT >>
			case 'touchstart': // DROPINIT >>
				// collect and assign the drop targets
				$targets =  $( drop.targets );
				if ( typeof dd.drop == "string" )
					$targets = $targets.filter( dd.drop );
				// reset drop data winner properties
				$targets.each(function(){
					var data = $.data( this, drop.datakey );
					data.active = [];
					data.anyactive = 0;
					data.winner = 0;
				});
				// set available target elements
				dd.droppable = $targets;
				// activate drop targets for the initial element being dragged
				$special.drag.hijack( event, "dropinit", dd ); 
				break;
			// drag, from $.event.special.drag
			case 'mousemove': // TOLERATE >>
			case 'touchmove': // TOLERATE >>
				drop.event = event; // store the mousemove event
				if ( !drop.timer )
					// monitor drop targets
					drop.tolerate( dd ); 
				break;
			// dragend, from $.event.special.drag
			case 'mouseup': // DROP >> DROPEND >>
			case 'touchend': // DROP >> DROPEND >>
				drop.timer = clearTimeout( drop.timer ); // delete timer	
				if ( dd.propagates ){
					$special.drag.hijack( event, "drop", dd ); 
					$special.drag.hijack( event, "dropend", dd ); 
				}
				break;
				
		}
	},
		
	// returns the location positions of an element
	locate: function( elem, index ){ 
		var data = $.data( elem, drop.datakey ),
		$elem = $( elem ), 
		posi = $elem.offset() || {}, 
		height = $elem.outerHeight(), 
		width = $elem.outerWidth(),
		location = { 
			elem: elem, 
			width: width, 
			height: height,
			top: posi.top, 
			left: posi.left, 
			right: posi.left + width, 
			bottom: posi.top + height
		};
		// drag elements might not have dropdata
		if ( data ){
			data.location = location;
			data.index = index;
			data.elem = elem;
		}
		return location;
	},
	
	// test the location positions of an element against another OR an X,Y coord
	contains: function( target, test ){ // target { location } contains test [x,y] or { location }
		return ( ( test[0] || test.left ) >= target.left && ( test[0] || test.right ) <= target.right
			&& ( test[1] || test.top ) >= target.top && ( test[1] || test.bottom ) <= target.bottom ); 
	},
	
	// stored tolerance modes
	modes: { // fn scope: "$.event.special.drop" object 
		// target with mouse wins, else target with most overlap wins
		'intersect': function( event, proxy, target ){
			return this.contains( target, [ event.pageX, event.pageY ] ) ? // check cursor
				1e9 : this.modes.overlap.apply( this, arguments ); // check overlap
		},
		// target with most overlap wins	
		'overlap': function( event, proxy, target ){
			// calculate the area of overlap...
			return Math.max( 0, Math.min( target.bottom, proxy.bottom ) - Math.max( target.top, proxy.top ) )
				* Math.max( 0, Math.min( target.right, proxy.right ) - Math.max( target.left, proxy.left ) );
		},
		// proxy is completely contained within target bounds	
		'fit': function( event, proxy, target ){
			return this.contains( target, proxy ) ? 1 : 0;
		},
		// center of the proxy is contained within target bounds	
		'middle': function( event, proxy, target ){
			return this.contains( target, [ proxy.left + proxy.width * .5, proxy.top + proxy.height * .5 ] ) ? 1 : 0;
		}
	},	
	
	// sort drop target cache by by winner (dsc), then index (asc)
	sort: function( a, b ){
		return ( b.winner - a.winner ) || ( a.index - b.index );
	},
		
	// async, recursive tolerance execution
	tolerate: function( dd ){		
		// declare local refs
		var i, drp, drg, data, arr, len, elem,
		// interaction iteration variables
		x = 0, ia, end = dd.interactions.length,
		// determine the mouse coords
		xy = [ drop.event.pageX, drop.event.pageY ],
		// custom or stored tolerance fn
		tolerance = drop.tolerance || drop.modes[ drop.mode ];
		// go through each passed interaction...
		do if ( ia = dd.interactions[x] ){
			// check valid interaction
			if ( !ia )
				return; 
			// initialize or clear the drop data
			ia.drop = [];
			// holds the drop elements
			arr = []; 
			len = ia.droppable.length;
			// determine the proxy location, if needed
			if ( tolerance )
				drg = drop.locate( ia.proxy ); 
			// reset the loop
			i = 0;
			// loop each stored drop target
			do if ( elem = ia.droppable[i] ){ 
				data = $.data( elem, drop.datakey );
				drp = data.location;
				if ( !drp ) continue;
				// find a winner: tolerance function is defined, call it
				data.winner = tolerance ? tolerance.call( drop, drop.event, drg, drp ) 
					// mouse position is always the fallback
					: drop.contains( drp, xy ) ? 1 : 0; 
				arr.push( data );	
			} while ( ++i < len ); // loop 
			// sort the drop targets
			arr.sort( drop.sort );			
			// reset the loop
			i = 0;
			// loop through all of the targets again
			do if ( data = arr[ i ] ){
				// winners...
				if ( data.winner && ia.drop.length < drop.multi ){
					// new winner... dropstart
					if ( !data.active[x] && !data.anyactive ){
						// check to make sure that this is not prevented
						if ( $special.drag.hijack( drop.event, "dropstart", dd, x, data.elem )[0] !== false ){ 	
							data.active[x] = 1;
							data.anyactive += 1;
						}
						// if false, it is not a winner
						else
							data.winner = 0;
					}
					// if it is still a winner
					if ( data.winner )
						ia.drop.push( data.elem );
				}
				// losers... 
				else if ( data.active[x] && data.anyactive == 1 ){
					// former winner... dropend
					$special.drag.hijack( drop.event, "dropend", dd, x, data.elem ); 
					data.active[x] = 0;
					data.anyactive -= 1;
				}
			} while ( ++i < len ); // loop 		
		} while ( ++x < end ) // loop
		// check if the mouse is still moving or is idle
		if ( drop.last && xy[0] == drop.last.pageX && xy[1] == drop.last.pageY ) 
			delete drop.timer; // idle, don't recurse
		else  // recurse
			drop.timer = setTimeout(function(){ 
				drop.tolerate( dd ); 
			}, drop.delay );
		// remember event, to compare idleness
		drop.last = drop.event; 
	}
	
};

// share the same special event configuration with related events...
$special.dropinit = $special.dropstart = $special.dropend = drop;

})(jQuery); // confine scope	;
return $.fn.drop;
  }).apply(root, arguments);
});
}(this));

/**
 * @license
 * (c) 2009-2013 Michael Leibman
 * michael{dot}leibman{at}gmail{dot}com
 * http://github.com/mleibman/slickgrid
 *
 * Distributed under MIT license.
 * All rights reserved.
 *
 * SlickGrid v2.2
 *
 * NOTES:
 *     Cell/row DOM manipulations are done directly bypassing jQuery's DOM manipulation methods.
 *     This increases the speed dramatically, but can only be done safely because there are no event handlers
 *     or data associated with any cell/row DOM nodes.  Cell editors must make sure they implement .destroy()
 *     and do proper cleanup.
 */

define('slick_grid/slick.grid',["jquery", "./slick.core", "jquery_event_drag", "jquery_event_drop"], function($, Slick, $1, $2) {

  // shared across all grids on the page
  var scrollbarDimensions;
  var maxSupportedCssHeight;  // browser's breaking point

  //////////////////////////////////////////////////////////////////////////////////////////////
  // SlickGrid class implementation (available as Slick.Grid)

  /**
   * Creates a new instance of the grid.
   * @class SlickGrid
   * @constructor
   * @param {Node}              container   Container node to create the grid in.
   * @param {Array,Object}      data        An array of objects for databinding.
   * @param {Array}             columns     An array of column definitions.
   * @param {Object}            options     Grid options.
   **/
  function SlickGrid(container, data, columns, options) {
    // settings
    var defaults = {
      explicitInitialization: false,
      rowHeight: 25,
      defaultColumnWidth: 80,
      enableAddRow: false,
      leaveSpaceForNewRows: false,
      editable: false,
      autoEdit: true,
      enableCellNavigation: true,
      enableColumnReorder: true,
      asyncEditorLoading: false,
      asyncEditorLoadDelay: 100,
      forceFitColumns: false,
      enableAsyncPostRender: false,
      asyncPostRenderDelay: 50,
      autoHeight: false,
      editorLock: Slick.GlobalEditorLock,
      showHeaderRow: false,
      headerRowHeight: 25,
      showTopPanel: false,
      topPanelHeight: 25,
      formatterFactory: null,
      editorFactory: null,
      cellFlashingCssClass: "flashing",
      selectedCellCssClass: "selected",
      multiSelect: true,
      enableTextSelectionOnCells: false,
      dataItemColumnValueExtractor: null,
      fullWidthRows: false,
      multiColumnSort: false,
      defaultFormatter: defaultFormatter,
      forceSyncScrolling: false,
      addNewRowCssClass: "new-row"
    };

    var columnDefaults = {
      name: "",
      resizable: true,
      sortable: false,
      minWidth: 30,
      rerenderOnResize: false,
      headerCssClass: null,
      defaultSortAsc: true,
      focusable: true,
      selectable: true
    };

    // scroller
    var th;   // virtual height
    var h;    // real scrollable height
    var ph;   // page height
    var n;    // number of pages
    var cj;   // "jumpiness" coefficient

    var page = 0;       // current page
    var offset = 0;     // current page offset
    var vScrollDir = 1;

    // private
    var initialized = false;
    var $container;
    var uid = "slickgrid_" + Math.round(1000000 * Math.random());
    var self = this;
    var $focusSink, $focusSink2;
    var $headerScroller;
    var $headers;
    var $headerRow, $headerRowScroller, $headerRowSpacer;
    var $topPanelScroller;
    var $topPanel;
    var $viewport;
    var $canvas;
    var $style;
    var $boundAncestors;
    var stylesheet, columnCssRulesL, columnCssRulesR;
    var viewportH, viewportW;
    var canvasWidth;
    var viewportHasHScroll, viewportHasVScroll;
    var headerColumnWidthDiff = 0, headerColumnHeightDiff = 0, // border+padding
        cellWidthDiff = 0, cellHeightDiff = 0;
    var absoluteColumnMinWidth;

    var tabbingDirection = 1;
    var activePosX;
    var activeRow, activeCell;
    var activeCellNode = null;
    var currentEditor = null;
    var serializedEditorValue;
    var editController;

    var rowsCache = {};
    var renderedRows = 0;
    var numVisibleRows;
    var prevScrollTop = 0;
    var scrollTop = 0;
    var lastRenderedScrollTop = 0;
    var lastRenderedScrollLeft = 0;
    var prevScrollLeft = 0;
    var scrollLeft = 0;

    var selectionModel;
    var selectedRows = [];

    var plugins = [];
    var cellCssClasses = {};

    var columnsById = {};
    var sortColumns = [];
    var columnPosLeft = [];
    var columnPosRight = [];


    // async call handles
    var h_editorLoader = null;
    var h_render = null;
    var h_postrender = null;
    var postProcessedRows = {};
    var postProcessToRow = null;
    var postProcessFromRow = null;

    // perf counters
    var counter_rows_rendered = 0;
    var counter_rows_removed = 0;

    // These two variables work around a bug with inertial scrolling in Webkit/Blink on Mac.
    // See http://crbug.com/312427.
    var rowNodeFromLastMouseWheelEvent;  // this node must not be deleted while inertial scrolling
    var zombieRowNodeFromLastMouseWheelEvent;  // node that was hidden instead of getting deleted


    //////////////////////////////////////////////////////////////////////////////////////////////
    // Initialization

    function init() {
      $container = $(container);
      if ($container.length < 1) {
        throw new Error("SlickGrid requires a valid container, " + container + " does not exist in the DOM.");
      }

      // calculate these only once and share between grid instances
      maxSupportedCssHeight = maxSupportedCssHeight || getMaxSupportedCssHeight();
      scrollbarDimensions = scrollbarDimensions || measureScrollbar();

      options = $.extend({}, defaults, options);
      validateAndEnforceOptions();
      columnDefaults.width = options.defaultColumnWidth;

      columnsById = {};
      for (var i = 0; i < columns.length; i++) {
        var m = columns[i] = $.extend({}, columnDefaults, columns[i]);
        columnsById[m.id] = i;
        if (m.minWidth && m.width < m.minWidth) {
          m.width = m.minWidth;
        }
        if (m.maxWidth && m.width > m.maxWidth) {
          m.width = m.maxWidth;
        }
      }

      // validate loaded JavaScript modules against requested options
      if (options.enableColumnReorder && !$.fn.sortable) {
        throw new Error("SlickGrid's 'enableColumnReorder = true' option requires jquery-ui.sortable module to be loaded");
      }

      editController = {
        "commitCurrentEdit": commitCurrentEdit,
        "cancelCurrentEdit": cancelCurrentEdit
      };

      $container
          .empty()
          .css("overflow", "hidden")
          .css("outline", 0)
          .addClass(uid)
          .addClass("bk-ui-widget");

      // set up a positioning container if needed
      if (!/relative|absolute|fixed/.test($container.css("position"))) {
        $container.css("position", "relative");
      }

      $focusSink = $("<div tabIndex='0' hideFocus style='position:fixed;width:0;height:0;top:0;left:0;outline:0;'></div>").appendTo($container);

      $headerScroller = $("<div class='bk-slick-header bk-ui-state-default' style='overflow:hidden;position:relative;' />").appendTo($container);
      $headers = $("<div class='bk-slick-header-columns' style='left:-1000px' />").appendTo($headerScroller);
      $headers.width(getHeadersWidth());

      $headerRowScroller = $("<div class='bk-slick-headerrow bk-ui-state-default' style='overflow:hidden;position:relative;' />").appendTo($container);
      $headerRow = $("<div class='bk-slick-headerrow-columns' />").appendTo($headerRowScroller);
      $headerRowSpacer = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>")
          .css("width", getCanvasWidth() + scrollbarDimensions.width + "px")
          .appendTo($headerRowScroller);

      $topPanelScroller = $("<div class='bk-slick-top-panel-scroller bk-ui-state-default' style='overflow:hidden;position:relative;' />").appendTo($container);
      $topPanel = $("<div class='bk-slick-top-panel' style='width:10000px' />").appendTo($topPanelScroller);

      if (!options.showTopPanel) {
        $topPanelScroller.hide();
      }

      if (!options.showHeaderRow) {
        $headerRowScroller.hide();
      }

      $viewport = $("<div class='bk-slick-viewport' style='width:100%;overflow:auto;outline:0;position:relative;;'>").appendTo($container);
      $viewport.css("overflow-y", options.autoHeight ? "hidden" : "auto");

      $canvas = $("<div class='grid-canvas' />").appendTo($viewport);

      $focusSink2 = $focusSink.clone().appendTo($container);

      if (!options.explicitInitialization) {
        finishInitialization();
      }
    }

    function finishInitialization() {
      if (!initialized) {
        initialized = true;

        viewportW = parseFloat($.css($container[0], "width", true));

        // header columns and cells may have different padding/border skewing width calculations (box-sizing, hello?)
        // calculate the diff so we can set consistent sizes
        measureCellPaddingAndBorder();

        // for usability reasons, all text selection in SlickGrid is disabled
        // with the exception of input and textarea elements (selection must
        // be enabled there so that editors work as expected); note that
        // selection in grid cells (grid body) is already unavailable in
        // all browsers except IE
        disableSelection($headers); // disable all text selection in header (including input and textarea)

        if (!options.enableTextSelectionOnCells) {
          // disable text selection in grid cells except in input and textarea elements
          // (this is IE-specific, because selectstart event will only fire in IE)
          $viewport.bind("selectstart.ui", function (event) {
            return $(event.target).is("input,textarea");
          });
        }

        updateColumnCaches();
        createColumnHeaders();
        setupColumnSort();
        createCssRules();
        resizeCanvas();
        bindAncestorScrollEvents();

        $container
            .bind("resize.bk-slickgrid", resizeCanvas);
        $viewport
            //.bind("click", handleClick)
            .bind("scroll", handleScroll);
        $headerScroller
            .bind("contextmenu", handleHeaderContextMenu)
            .bind("click", handleHeaderClick)
            .delegate(".bk-slick-header-column", "mouseenter", handleHeaderMouseEnter)
            .delegate(".bk-slick-header-column", "mouseleave", handleHeaderMouseLeave);
        $headerRowScroller
            .bind("scroll", handleHeaderRowScroll);
        $focusSink.add($focusSink2)
            .bind("keydown", handleKeyDown);
        $canvas
            .bind("keydown", handleKeyDown)
            .bind("click", handleClick)
            .bind("dblclick", handleDblClick)
            .bind("contextmenu", handleContextMenu)
            .bind("draginit", handleDragInit)
            .bind("dragstart", {distance: 3}, handleDragStart)
            .bind("drag", handleDrag)
            .bind("dragend", handleDragEnd)
            .delegate(".bk-slick-cell", "mouseenter", handleMouseEnter)
            .delegate(".bk-slick-cell", "mouseleave", handleMouseLeave);

        // Work around http://crbug.com/312427.
        if (navigator.userAgent.toLowerCase().match(/webkit/) &&
            navigator.userAgent.toLowerCase().match(/macintosh/)) {
          $canvas.bind("mousewheel", handleMouseWheel);
        }
      }
    }

    function registerPlugin(plugin) {
      plugins.unshift(plugin);
      plugin.init(self);
    }

    function unregisterPlugin(plugin) {
      for (var i = plugins.length; i >= 0; i--) {
        if (plugins[i] === plugin) {
          if (plugins[i].destroy) {
            plugins[i].destroy();
          }
          plugins.splice(i, 1);
          break;
        }
      }
    }

    function setSelectionModel(model) {
      if (selectionModel) {
        selectionModel.onSelectedRangesChanged.unsubscribe(handleSelectedRangesChanged);
        if (selectionModel.destroy) {
          selectionModel.destroy();
        }
      }

      selectionModel = model;
      if (selectionModel) {
        selectionModel.init(self);
        selectionModel.onSelectedRangesChanged.subscribe(handleSelectedRangesChanged);
      }
    }

    function getSelectionModel() {
      return selectionModel;
    }

    function getCanvasNode() {
      return $canvas[0];
    }

    function measureScrollbar() {
      var $c = $("<div style='position:absolute; top:-10000px; left:-10000px; width:100px; height:100px; overflow:scroll;'></div>").appendTo("body");
      var dim = {
        width: $c.width() - $c[0].clientWidth,
        height: $c.height() - $c[0].clientHeight
      };
      $c.remove();
      return dim;
    }

    function getHeadersWidth() {
      var headersWidth = 0;
      for (var i = 0, ii = columns.length; i < ii; i++) {
        var width = columns[i].width;
        headersWidth += width;
      }
      headersWidth += scrollbarDimensions.width;
      return Math.max(headersWidth, viewportW) + 1000;
    }

    function getCanvasWidth() {
      var availableWidth = viewportHasVScroll ? viewportW - scrollbarDimensions.width : viewportW;
      var rowWidth = 0;
      var i = columns.length;
      while (i--) {
        rowWidth += columns[i].width;
      }
      return options.fullWidthRows ? Math.max(rowWidth, availableWidth) : rowWidth;
    }

    function updateCanvasWidth(forceColumnWidthsUpdate) {
      var oldCanvasWidth = canvasWidth;
      canvasWidth = getCanvasWidth();

      if (canvasWidth != oldCanvasWidth) {
        $canvas.width(canvasWidth);
        $headerRow.width(canvasWidth);
        $headers.width(getHeadersWidth());
        viewportHasHScroll = (canvasWidth > viewportW - scrollbarDimensions.width);
      }

      $headerRowSpacer.width(canvasWidth + (viewportHasVScroll ? scrollbarDimensions.width : 0));

      if (canvasWidth != oldCanvasWidth || forceColumnWidthsUpdate) {
        applyColumnWidths();
      }
    }

    function disableSelection($target) {
      if ($target && $target.jquery) {
        $target
            .attr("unselectable", "on")
            .css("MozUserSelect", "none")
            .bind("selectstart.ui", function () {
              return false;
            }); // from jquery:ui.core.js 1.7.2
      }
    }

    function getMaxSupportedCssHeight() {
      var supportedHeight = 1000000;
      // FF reports the height back but still renders blank after ~6M px
      var testUpTo = navigator.userAgent.toLowerCase().match(/firefox/) ? 6000000 : 1000000000;
      var div = $("<div style='display:none' />").appendTo(document.body);

      while (true) {
        var test = supportedHeight * 2;
        div.css("height", test);
        if (test > testUpTo || div.height() !== test) {
          break;
        } else {
          supportedHeight = test;
        }
      }

      div.remove();
      return supportedHeight;
    }

    // TODO:  this is static.  need to handle page mutation.
    function bindAncestorScrollEvents() {
      var elem = $canvas[0];
      while ((elem = elem.parentNode) != document.body && elem != null) {
        // bind to scroll containers only
        if (elem == $viewport[0] || elem.scrollWidth != elem.clientWidth || elem.scrollHeight != elem.clientHeight) {
          var $elem = $(elem);
          if (!$boundAncestors) {
            $boundAncestors = $elem;
          } else {
            $boundAncestors = $boundAncestors.add($elem);
          }
          $elem.bind("scroll." + uid, handleActiveCellPositionChange);
        }
      }
    }

    function unbindAncestorScrollEvents() {
      if (!$boundAncestors) {
        return;
      }
      $boundAncestors.unbind("scroll." + uid);
      $boundAncestors = null;
    }

    function updateColumnHeader(columnId, title, toolTip) {
      if (!initialized) { return; }
      var idx = getColumnIndex(columnId);
      if (idx == null) {
        return;
      }

      var columnDef = columns[idx];
      var $header = $headers.children().eq(idx);
      if ($header) {
        if (title !== undefined) {
          columns[idx].name = title;
        }
        if (toolTip !== undefined) {
          columns[idx].toolTip = toolTip;
        }

        trigger(self.onBeforeHeaderCellDestroy, {
          "node": $header[0],
          "column": columnDef
        });

        $header
            .attr("title", toolTip || "")
            .children().eq(0).html(title);

        trigger(self.onHeaderCellRendered, {
          "node": $header[0],
          "column": columnDef
        });
      }
    }

    function getHeaderRow() {
      return $headerRow[0];
    }

    function getHeaderRowColumn(columnId) {
      var idx = getColumnIndex(columnId);
      var $header = $headerRow.children().eq(idx);
      return $header && $header[0];
    }

    function createColumnHeaders() {
      function onMouseEnter() {
        $(this).addClass("bk-ui-state-hover");
      }

      function onMouseLeave() {
        $(this).removeClass("bk-ui-state-hover");
      }

      $headers.find(".bk-slick-header-column")
        .each(function() {
          var columnDef = $(this).data("column");
          if (columnDef) {
            trigger(self.onBeforeHeaderCellDestroy, {
              "node": this,
              "column": columnDef
            });
          }
        });
      $headers.empty();
      $headers.width(getHeadersWidth());

      $headerRow.find(".bk-slick-headerrow-column")
        .each(function() {
          var columnDef = $(this).data("column");
          if (columnDef) {
            trigger(self.onBeforeHeaderRowCellDestroy, {
              "node": this,
              "column": columnDef
            });
          }
        });
      $headerRow.empty();

      for (var i = 0; i < columns.length; i++) {
        var m = columns[i];

        var header = $("<div class='bk-ui-state-default bk-slick-header-column' />")
            .html("<span class='bk-slick-column-name'>" + m.name + "</span>")
            .width(m.width - headerColumnWidthDiff)
            .attr("id", "" + uid + m.id)
            .attr("title", m.toolTip || "")
            .data("column", m)
            .addClass(m.headerCssClass || "")
            .appendTo($headers);

        if (options.enableColumnReorder || m.sortable) {
          header
            .on('mouseenter', onMouseEnter)
            .on('mouseleave', onMouseLeave);
        }

        if (m.sortable) {
          header.addClass("bk-slick-header-sortable");
          header.append("<span class='bk-slick-sort-indicator' />");
        }

        trigger(self.onHeaderCellRendered, {
          "node": header[0],
          "column": m
        });

        if (options.showHeaderRow) {
          var headerRowCell = $("<div class='bk-ui-state-default bk-slick-headerrow-column l" + i + " r" + i + "'></div>")
              .data("column", m)
              .appendTo($headerRow);

          trigger(self.onHeaderRowCellRendered, {
            "node": headerRowCell[0],
            "column": m
          });
        }
      }

      setSortColumns(sortColumns);
      setupColumnResize();
      if (options.enableColumnReorder) {
        setupColumnReorder();
      }
    }

    function setupColumnSort() {
      $headers.click(function (e) {
        // temporary workaround for a bug in jQuery 1.7.1 (http://bugs.jquery.com/ticket/11328)
        e.metaKey = e.metaKey || e.ctrlKey;

        if ($(e.target).hasClass("bk-slick-resizable-handle")) {
          return;
        }

        var $col = $(e.target).closest(".bk-slick-header-column");
        if (!$col.length) {
          return;
        }

        var column = $col.data("column");
        if (column.sortable) {
          if (!getEditorLock().commitCurrentEdit()) {
            return;
          }

          var sortOpts = null;
          var i = 0;
          for (; i < sortColumns.length; i++) {
            if (sortColumns[i].columnId == column.id) {
              sortOpts = sortColumns[i];
              sortOpts.sortAsc = !sortOpts.sortAsc;
              break;
            }
          }

          if (e.metaKey && options.multiColumnSort) {
            if (sortOpts) {
              sortColumns.splice(i, 1);
            }
          }
          else {
            if ((!e.shiftKey && !e.metaKey) || !options.multiColumnSort) {
              sortColumns = [];
            }

            if (!sortOpts) {
              sortOpts = { columnId: column.id, sortAsc: column.defaultSortAsc };
              sortColumns.push(sortOpts);
            } else if (sortColumns.length == 0) {
              sortColumns.push(sortOpts);
            }
          }

          setSortColumns(sortColumns);

          if (!options.multiColumnSort) {
            trigger(self.onSort, {
              multiColumnSort: false,
              sortCol: column,
              sortAsc: sortOpts.sortAsc}, e);
          } else {
            trigger(self.onSort, {
              multiColumnSort: true,
              sortCols: $.map(sortColumns, function(col) {
                return {sortCol: columns[getColumnIndex(col.columnId)], sortAsc: col.sortAsc };
              })}, e);
          }
        }
      });
    }

    function setupColumnReorder() {
      $headers.filter(":ui-sortable").sortable("destroy");
      $headers.sortable({
        containment: "parent",
        distance: 3,
        axis: "x",
        cursor: "default",
        tolerance: "intersection",
        helper: "clone",
        placeholder: "bk-slick-sortable-placeholder bk-ui-state-default bk-slick-header-column",
        start: function (e, ui) {
          ui.placeholder.width(ui.helper.outerWidth() - headerColumnWidthDiff);
          $(ui.helper).addClass("bk-slick-header-column-active");
        },
        beforeStop: function (e, ui) {
          $(ui.helper).removeClass("bk-slick-header-column-active");
        },
        stop: function (e) {
          if (!getEditorLock().commitCurrentEdit()) {
            $(this).sortable("cancel");
            return;
          }

          var reorderedIds = $headers.sortable("toArray");
          var reorderedColumns = [];
          for (var i = 0; i < reorderedIds.length; i++) {
            reorderedColumns.push(columns[getColumnIndex(reorderedIds[i].replace(uid, ""))]);
          }
          setColumns(reorderedColumns);

          trigger(self.onColumnsReordered, {});
          e.stopPropagation();
          setupColumnResize();
        }
      });
    }

    function setupColumnResize() {
      var $col, j, c, pageX, columnElements, minPageX, maxPageX, firstResizable, lastResizable;
      columnElements = $headers.children();
      columnElements.find(".bk-slick-resizable-handle").remove();
      columnElements.each(function (i, e) {
        if (columns[i].resizable) {
          if (firstResizable === undefined) {
            firstResizable = i;
          }
          lastResizable = i;
        }
      });
      if (firstResizable === undefined) {
        return;
      }
      columnElements.each(function (i, e) {
        if (i < firstResizable || (options.forceFitColumns && i >= lastResizable)) {
          return;
        }
        $col = $(e);
        $("<div class='bk-slick-resizable-handle' />")
            .appendTo(e)
            .bind("dragstart", function (e, dd) {
              if (!getEditorLock().commitCurrentEdit()) {
                return false;
              }
              pageX = e.pageX;
              $(this).parent().addClass("bk-slick-header-column-active");
              var shrinkLeewayOnRight = null, stretchLeewayOnRight = null;
              // lock each column's width option to current width
              columnElements.each(function (i, e) {
                columns[i].previousWidth = $(e).outerWidth();
              });
              if (options.forceFitColumns) {
                shrinkLeewayOnRight = 0;
                stretchLeewayOnRight = 0;
                // colums on right affect maxPageX/minPageX
                for (j = i + 1; j < columnElements.length; j++) {
                  c = columns[j];
                  if (c.resizable) {
                    if (stretchLeewayOnRight !== null) {
                      if (c.maxWidth) {
                        stretchLeewayOnRight += c.maxWidth - c.previousWidth;
                      } else {
                        stretchLeewayOnRight = null;
                      }
                    }
                    shrinkLeewayOnRight += c.previousWidth - Math.max(c.minWidth || 0, absoluteColumnMinWidth);
                  }
                }
              }
              var shrinkLeewayOnLeft = 0, stretchLeewayOnLeft = 0;
              for (j = 0; j <= i; j++) {
                // columns on left only affect minPageX
                c = columns[j];
                if (c.resizable) {
                  if (stretchLeewayOnLeft !== null) {
                    if (c.maxWidth) {
                      stretchLeewayOnLeft += c.maxWidth - c.previousWidth;
                    } else {
                      stretchLeewayOnLeft = null;
                    }
                  }
                  shrinkLeewayOnLeft += c.previousWidth - Math.max(c.minWidth || 0, absoluteColumnMinWidth);
                }
              }
              if (shrinkLeewayOnRight === null) {
                shrinkLeewayOnRight = 100000;
              }
              if (shrinkLeewayOnLeft === null) {
                shrinkLeewayOnLeft = 100000;
              }
              if (stretchLeewayOnRight === null) {
                stretchLeewayOnRight = 100000;
              }
              if (stretchLeewayOnLeft === null) {
                stretchLeewayOnLeft = 100000;
              }
              maxPageX = pageX + Math.min(shrinkLeewayOnRight, stretchLeewayOnLeft);
              minPageX = pageX - Math.min(shrinkLeewayOnLeft, stretchLeewayOnRight);
            })
            .bind("drag", function (e, dd) {
              var actualMinWidth, d = Math.min(maxPageX, Math.max(minPageX, e.pageX)) - pageX, x;
              if (d < 0) { // shrink column
                x = d;
                for (j = i; j >= 0; j--) {
                  c = columns[j];
                  if (c.resizable) {
                    actualMinWidth = Math.max(c.minWidth || 0, absoluteColumnMinWidth);
                    if (x && c.previousWidth + x < actualMinWidth) {
                      x += c.previousWidth - actualMinWidth;
                      c.width = actualMinWidth;
                    } else {
                      c.width = c.previousWidth + x;
                      x = 0;
                    }
                  }
                }

                if (options.forceFitColumns) {
                  x = -d;
                  for (j = i + 1; j < columnElements.length; j++) {
                    c = columns[j];
                    if (c.resizable) {
                      if (x && c.maxWidth && (c.maxWidth - c.previousWidth < x)) {
                        x -= c.maxWidth - c.previousWidth;
                        c.width = c.maxWidth;
                      } else {
                        c.width = c.previousWidth + x;
                        x = 0;
                      }
                    }
                  }
                }
              } else { // stretch column
                x = d;
                for (j = i; j >= 0; j--) {
                  c = columns[j];
                  if (c.resizable) {
                    if (x && c.maxWidth && (c.maxWidth - c.previousWidth < x)) {
                      x -= c.maxWidth - c.previousWidth;
                      c.width = c.maxWidth;
                    } else {
                      c.width = c.previousWidth + x;
                      x = 0;
                    }
                  }
                }

                if (options.forceFitColumns) {
                  x = -d;
                  for (j = i + 1; j < columnElements.length; j++) {
                    c = columns[j];
                    if (c.resizable) {
                      actualMinWidth = Math.max(c.minWidth || 0, absoluteColumnMinWidth);
                      if (x && c.previousWidth + x < actualMinWidth) {
                        x += c.previousWidth - actualMinWidth;
                        c.width = actualMinWidth;
                      } else {
                        c.width = c.previousWidth + x;
                        x = 0;
                      }
                    }
                  }
                }
              }
              applyColumnHeaderWidths();
              if (options.syncColumnCellResize) {
                applyColumnWidths();
              }
            })
            .bind("dragend", function (e, dd) {
              var newWidth;
              $(this).parent().removeClass("bk-slick-header-column-active");
              for (j = 0; j < columnElements.length; j++) {
                c = columns[j];
                newWidth = $(columnElements[j]).outerWidth();

                if (c.previousWidth !== newWidth && c.rerenderOnResize) {
                  invalidateAllRows();
                }
              }
              updateCanvasWidth(true);
              render();
              trigger(self.onColumnsResized, {});
            });
      });
    }

    function getVBoxDelta($el) {
      var p = ["borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom"];
      var delta = 0;
      $.each(p, function (n, val) {
        delta += parseFloat($el.css(val)) || 0;
      });
      return delta;
    }

    function measureCellPaddingAndBorder() {
      var el;
      var h = ["borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight"];
      var v = ["borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom"];

      el = $("<div class='bk-ui-state-default bk-slick-header-column' style='visibility:hidden'>-</div>").appendTo($headers);
      headerColumnWidthDiff = headerColumnHeightDiff = 0;
      if (el.css("box-sizing") != "border-box" && el.css("-moz-box-sizing") != "border-box" && el.css("-webkit-box-sizing") != "border-box") {
        $.each(h, function (n, val) {
          headerColumnWidthDiff += parseFloat(el.css(val)) || 0;
        });
        $.each(v, function (n, val) {
          headerColumnHeightDiff += parseFloat(el.css(val)) || 0;
        });
      }
      el.remove();

      var r = $("<div class='bk-slick-row' />").appendTo($canvas);
      el = $("<div class='bk-slick-cell' id='' style='visibility:hidden'>-</div>").appendTo(r);
      cellWidthDiff = cellHeightDiff = 0;
      if (el.css("box-sizing") != "border-box" && el.css("-moz-box-sizing") != "border-box" && el.css("-webkit-box-sizing") != "border-box") {
        $.each(h, function (n, val) {
          cellWidthDiff += parseFloat(el.css(val)) || 0;
        });
        $.each(v, function (n, val) {
          cellHeightDiff += parseFloat(el.css(val)) || 0;
        });
      }
      r.remove();

      absoluteColumnMinWidth = Math.max(headerColumnWidthDiff, cellWidthDiff);
    }

    function createCssRules() {
      $style = $("<style type='text/css' rel='stylesheet' />").appendTo($("head"));
      var rowHeight = (options.rowHeight - cellHeightDiff);
      var rules = [
        "." + uid + " .bk-slick-header-column { left: 1000px; }",
        "." + uid + " .bk-slick-top-panel { height:" + options.topPanelHeight + "px; }",
        "." + uid + " .bk-slick-headerrow-columns { height:" + options.headerRowHeight + "px; }",
        "." + uid + " .bk-slick-cell { height:" + rowHeight + "px; }",
        "." + uid + " .bk-slick-row { height:" + options.rowHeight + "px; }"
      ];

      for (var i = 0; i < columns.length; i++) {
        rules.push("." + uid + " .l" + i + " { }");
        rules.push("." + uid + " .r" + i + " { }");
      }

      if ($style[0].styleSheet) { // IE
        $style[0].styleSheet.cssText = rules.join(" ");
      } else {
        $style[0].appendChild(document.createTextNode(rules.join(" ")));
      }
    }

    function getColumnCssRules(idx) {
      if (!stylesheet) {
        var sheets = document.styleSheets;
        for (var i = 0; i < sheets.length; i++) {
          if ((sheets[i].ownerNode || sheets[i].owningElement) == $style[0]) {
            stylesheet = sheets[i];
            break;
          }
        }

        if (!stylesheet) {
          throw new Error("Cannot find stylesheet.");
        }

        // find and cache column CSS rules
        columnCssRulesL = [];
        columnCssRulesR = [];
        var cssRules = (stylesheet.cssRules || stylesheet.rules);
        var matches, columnIdx;
        for (var i = 0; i < cssRules.length; i++) {
          var selector = cssRules[i].selectorText;
          if (matches = /\.l\d+/.exec(selector)) {
            columnIdx = parseInt(matches[0].substr(2, matches[0].length - 2), 10);
            columnCssRulesL[columnIdx] = cssRules[i];
          } else if (matches = /\.r\d+/.exec(selector)) {
            columnIdx = parseInt(matches[0].substr(2, matches[0].length - 2), 10);
            columnCssRulesR[columnIdx] = cssRules[i];
          }
        }
      }

      return {
        "left": columnCssRulesL[idx],
        "right": columnCssRulesR[idx]
      };
    }

    function removeCssRules() {
      $style.remove();
      stylesheet = null;
    }

    function destroy() {
      getEditorLock().cancelCurrentEdit();

      trigger(self.onBeforeDestroy, {});

      var i = plugins.length;
      while(i--) {
        unregisterPlugin(plugins[i]);
      }

      if (options.enableColumnReorder) {
          $headers.filter(":ui-sortable").sortable("destroy");
      }

      unbindAncestorScrollEvents();
      $container.unbind(".bk-slickgrid");
      removeCssRules();

      $canvas.unbind("draginit dragstart dragend drag");
      $container.empty().removeClass(uid);
    }


    //////////////////////////////////////////////////////////////////////////////////////////////
    // General

    function trigger(evt, args, e) {
      e = e || new Slick.EventData();
      args = args || {};
      args.grid = self;
      return evt.notify(args, e, self);
    }

    function getEditorLock() {
      return options.editorLock;
    }

    function getEditController() {
      return editController;
    }

    function getColumnIndex(id) {
      return columnsById[id];
    }

    function autosizeColumns() {
      var i, c,
          widths = [],
          shrinkLeeway = 0,
          total = 0,
          prevTotal,
          availWidth = viewportHasVScroll ? viewportW - scrollbarDimensions.width : viewportW;

      for (i = 0; i < columns.length; i++) {
        c = columns[i];
        widths.push(c.width);
        total += c.width;
        if (c.resizable) {
          shrinkLeeway += c.width - Math.max(c.minWidth, absoluteColumnMinWidth);
        }
      }

      // shrink
      prevTotal = total;
      while (total > availWidth && shrinkLeeway) {
        var shrinkProportion = (total - availWidth) / shrinkLeeway;
        for (i = 0; i < columns.length && total > availWidth; i++) {
          c = columns[i];
          var width = widths[i];
          if (!c.resizable || width <= c.minWidth || width <= absoluteColumnMinWidth) {
            continue;
          }
          var absMinWidth = Math.max(c.minWidth, absoluteColumnMinWidth);
          var shrinkSize = Math.floor(shrinkProportion * (width - absMinWidth)) || 1;
          shrinkSize = Math.min(shrinkSize, width - absMinWidth);
          total -= shrinkSize;
          shrinkLeeway -= shrinkSize;
          widths[i] -= shrinkSize;
        }
        if (prevTotal <= total) {  // avoid infinite loop
          break;
        }
        prevTotal = total;
      }

      // grow
      prevTotal = total;
      while (total < availWidth) {
        var growProportion = availWidth / total;
        for (i = 0; i < columns.length && total < availWidth; i++) {
          c = columns[i];
          var currentWidth = widths[i];
          var growSize;

          if (!c.resizable || c.maxWidth <= currentWidth) {
            growSize = 0;
          } else {
            growSize = Math.min(Math.floor(growProportion * currentWidth) - currentWidth, (c.maxWidth - currentWidth) || 1000000) || 1;
          }
          total += growSize;
          widths[i] += growSize;
        }
        if (prevTotal >= total) {  // avoid infinite loop
          break;
        }
        prevTotal = total;
      }

      var reRender = false;
      for (i = 0; i < columns.length; i++) {
        if (columns[i].rerenderOnResize && columns[i].width != widths[i]) {
          reRender = true;
        }
        columns[i].width = widths[i];
      }

      applyColumnHeaderWidths();
      updateCanvasWidth(true);
      if (reRender) {
        invalidateAllRows();
        render();
      }
    }

    function applyColumnHeaderWidths() {
      if (!initialized) { return; }
      var h;
      for (var i = 0, headers = $headers.children(), ii = headers.length; i < ii; i++) {
        h = $(headers[i]);
        if (h.width() !== columns[i].width - headerColumnWidthDiff) {
          h.width(columns[i].width - headerColumnWidthDiff);
        }
      }

      updateColumnCaches();
    }

    function applyColumnWidths() {
      var x = 0, w, rule;
      for (var i = 0; i < columns.length; i++) {
        w = columns[i].width;

        rule = getColumnCssRules(i);
        rule.left.style.left = x + "px";
        rule.right.style.right = (canvasWidth - x - w) + "px";

        x += columns[i].width;
      }
    }

    function setSortColumn(columnId, ascending) {
      setSortColumns([{ columnId: columnId, sortAsc: ascending}]);
    }

    function setSortColumns(cols) {
      sortColumns = cols;

      var headerColumnEls = $headers.children();
      headerColumnEls
          .removeClass("bk-slick-header-column-sorted")
          .find(".bk-slick-sort-indicator")
              .removeClass("bk-slick-sort-indicator-asc bk-slick-sort-indicator-desc");

      $.each(sortColumns, function(i, col) {
        if (col.sortAsc == null) {
          col.sortAsc = true;
        }
        var columnIndex = getColumnIndex(col.columnId);
        if (columnIndex != null) {
          headerColumnEls.eq(columnIndex)
              .addClass("bk-slick-header-column-sorted")
              .find(".bk-slick-sort-indicator")
                  .addClass(col.sortAsc ? "bk-slick-sort-indicator-asc" : "bk-slick-sort-indicator-desc");
        }
      });
    }

    function getSortColumns() {
      return sortColumns;
    }

    function handleSelectedRangesChanged(e, ranges) {
      selectedRows = [];
      var hash = {};
      for (var i = 0; i < ranges.length; i++) {
        for (var j = ranges[i].fromRow; j <= ranges[i].toRow; j++) {
          if (!hash[j]) {  // prevent duplicates
            selectedRows.push(j);
            hash[j] = {};
          }
          for (var k = ranges[i].fromCell; k <= ranges[i].toCell; k++) {
            if (canCellBeSelected(j, k)) {
              hash[j][columns[k].id] = options.selectedCellCssClass;
            }
          }
        }
      }

      setCellCssStyles(options.selectedCellCssClass, hash);

      trigger(self.onSelectedRowsChanged, {rows: getSelectedRows()}, e);
    }

    function getColumns() {
      return columns;
    }

    function updateColumnCaches() {
      // Pre-calculate cell boundaries.
      columnPosLeft = [];
      columnPosRight = [];
      var x = 0;
      for (var i = 0, ii = columns.length; i < ii; i++) {
        columnPosLeft[i] = x;
        columnPosRight[i] = x + columns[i].width;
        x += columns[i].width;
      }
    }

    function setColumns(columnDefinitions) {
      columns = columnDefinitions;

      columnsById = {};
      for (var i = 0; i < columns.length; i++) {
        var m = columns[i] = $.extend({}, columnDefaults, columns[i]);
        columnsById[m.id] = i;
        if (m.minWidth && m.width < m.minWidth) {
          m.width = m.minWidth;
        }
        if (m.maxWidth && m.width > m.maxWidth) {
          m.width = m.maxWidth;
        }
      }

      updateColumnCaches();

      if (initialized) {
        invalidateAllRows();
        createColumnHeaders();
        removeCssRules();
        createCssRules();
        resizeCanvas();
        applyColumnWidths();
        handleScroll();
      }
    }

    function getOptions() {
      return options;
    }

    function setOptions(args) {
      if (!getEditorLock().commitCurrentEdit()) {
        return;
      }

      makeActiveCellNormal();

      if (options.enableAddRow !== args.enableAddRow) {
        invalidateRow(getDataLength());
      }

      options = $.extend(options, args);
      validateAndEnforceOptions();

      $viewport.css("overflow-y", options.autoHeight ? "hidden" : "auto");
      render();
    }

    function validateAndEnforceOptions() {
      if (options.autoHeight) {
        options.leaveSpaceForNewRows = false;
      }
    }

    function setData(newData, scrollToTop) {
      data = newData;
      invalidateAllRows();
      updateRowCount();
      if (scrollToTop) {
        scrollTo(0);
      }
    }

    function getData() {
      return data;
    }

    function getDataLength() {
      if (data.getLength) {
        return data.getLength();
      } else {
        return data.length;
      }
    }

    function getDataLengthIncludingAddNew() {
      return getDataLength() + (options.enableAddRow ? 1 : 0);
    }

    function getDataItem(i) {
      if (data.getItem) {
        return data.getItem(i);
      } else {
        return data[i];
      }
    }

    function getTopPanel() {
      return $topPanel[0];
    }

    function setTopPanelVisibility(visible) {
      if (options.showTopPanel != visible) {
        options.showTopPanel = visible;
        if (visible) {
          $topPanelScroller.slideDown("fast", resizeCanvas);
        } else {
          $topPanelScroller.slideUp("fast", resizeCanvas);
        }
      }
    }

    function setHeaderRowVisibility(visible) {
      if (options.showHeaderRow != visible) {
        options.showHeaderRow = visible;
        if (visible) {
          $headerRowScroller.slideDown("fast", resizeCanvas);
        } else {
          $headerRowScroller.slideUp("fast", resizeCanvas);
        }
      }
    }

    function getContainerNode() {
      return $container.get(0);
    }

    //////////////////////////////////////////////////////////////////////////////////////////////
    // Rendering / Scrolling

    function getRowTop(row) {
      return options.rowHeight * row - offset;
    }

    function getRowFromPosition(y) {
      return Math.floor((y + offset) / options.rowHeight);
    }

    function scrollTo(y) {
      y = Math.max(y, 0);
      y = Math.min(y, th - viewportH + (viewportHasHScroll ? scrollbarDimensions.height : 0));

      var oldOffset = offset;

      page = Math.min(n - 1, Math.floor(y / ph));
      offset = Math.round(page * cj);
      var newScrollTop = y - offset;

      if (offset != oldOffset) {
        var range = getVisibleRange(newScrollTop);
        cleanupRows(range);
        updateRowPositions();
      }

      if (prevScrollTop != newScrollTop) {
        vScrollDir = (prevScrollTop + oldOffset < newScrollTop + offset) ? 1 : -1;
        $viewport[0].scrollTop = (lastRenderedScrollTop = scrollTop = prevScrollTop = newScrollTop);

        trigger(self.onViewportChanged, {});
      }
    }

    function defaultFormatter(row, cell, value, columnDef, dataContext) {
      if (value == null) {
        return "";
      } else {
        return (value + "").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");
      }
    }

    function getFormatter(row, column) {
      var rowMetadata = data.getItemMetadata && data.getItemMetadata(row);

      // look up by id, then index
      var columnOverrides = rowMetadata &&
          rowMetadata.columns &&
          (rowMetadata.columns[column.id] || rowMetadata.columns[getColumnIndex(column.id)]);

      var formatter =
          (columnOverrides && columnOverrides.formatter) ||
          (rowMetadata && rowMetadata.formatter) ||
          column.formatter ||
          (options.formatterFactory && options.formatterFactory.getFormatter(column)) ||
          options.defaultFormatter;

      if (formatter.format !== undefined) {
        var model = formatter;
        function format(row, cell, value, columnDef, dataContext) {
          return model.format(row, cell, value, columnDef, dataContext);
        }
        formatter = format
      }

      return formatter;
    }

    function getEditor(row, cell) {
      var editor;
      var column = columns[cell];
      var rowMetadata = data.getItemMetadata && data.getItemMetadata(row);
      var columnMetadata = rowMetadata && rowMetadata.columns;

      if (columnMetadata && columnMetadata[column.id] && columnMetadata[column.id].editor !== undefined) {
        editor = columnMetadata[column.id].editor;
      } else if (columnMetadata && columnMetadata[cell] && columnMetadata[cell].editor !== undefined) {
        editor = columnMetadata[cell].editor;
      } else {
        editor = column.editor || (options.editorFactory && options.editorFactory.getEditor(column));
      }

      if (editor.default_view !== undefined) {
        editor = editor.default_view;
      }

      return editor;
    }

    function getDataItemValueForColumn(item, columnDef) {
      if (options.dataItemColumnValueExtractor) {
        return options.dataItemColumnValueExtractor(item, columnDef);
      }
      return item[columnDef.field];
    }

    function appendRowHtml(stringArray, row, range, dataLength) {
      var d = getDataItem(row);
      var dataLoading = row < dataLength && !d;
      var rowCss = "bk-slick-row" +
          (dataLoading ? " loading" : "") +
          (row === activeRow ? " active" : "") +
          (row % 2 == 1 ? " odd" : " even");

      if (!d) {
        rowCss += " " + options.addNewRowCssClass;
      }

      var metadata = data.getItemMetadata && data.getItemMetadata(row);

      if (metadata && metadata.cssClasses) {
        rowCss += " " + metadata.cssClasses;
      }

      stringArray.push("<div class='bk-ui-widget-content " + rowCss + "' style='top:" + getRowTop(row) + "px'>");

      var colspan, m;
      for (var i = 0, ii = columns.length; i < ii; i++) {
        m = columns[i];
        colspan = 1;
        if (metadata && metadata.columns) {
          var columnData = metadata.columns[m.id] || metadata.columns[i];
          colspan = (columnData && columnData.colspan) || 1;
          if (colspan === "*") {
            colspan = ii - i;
          }
        }

        // Do not render cells outside of the viewport.
        if (columnPosRight[Math.min(ii - 1, i + colspan - 1)] > range.leftPx) {
          if (columnPosLeft[i] > range.rightPx) {
            // All columns to the right are outside the range.
            break;
          }

          appendCellHtml(stringArray, row, i, colspan, d);
        }

        if (colspan > 1) {
          i += (colspan - 1);
        }
      }

      stringArray.push("</div>");
    }

    function appendCellHtml(stringArray, row, cell, colspan, item) {
      var m = columns[cell];
      var cellCss = "bk-slick-cell l" + cell + " r" + Math.min(columns.length - 1, cell + colspan - 1) +
          (m.cssClass ? " " + m.cssClass : "");
      if (row === activeRow && cell === activeCell) {
        cellCss += (" active");
      }

      // TODO:  merge them together in the setter
      for (var key in cellCssClasses) {
        if (cellCssClasses[key][row] && cellCssClasses[key][row][m.id]) {
          cellCss += (" " + cellCssClasses[key][row][m.id]);
        }
      }

      stringArray.push("<div class='" + cellCss + "'>");

      // if there is a corresponding row (if not, this is the Add New row or this data hasn't been loaded yet)
      if (item) {
        var value = getDataItemValueForColumn(item, m);
        stringArray.push(getFormatter(row, m)(row, cell, value, m, item));
      }

      stringArray.push("</div>");

      rowsCache[row].cellRenderQueue.push(cell);
      rowsCache[row].cellColSpans[cell] = colspan;
    }


    function cleanupRows(rangeToKeep) {
      for (var i in rowsCache) {
        if (((i = parseInt(i, 10)) !== activeRow) && (i < rangeToKeep.top || i > rangeToKeep.bottom)) {
          removeRowFromCache(i);
        }
      }
    }

    function invalidate() {
      updateRowCount();
      invalidateAllRows();
      render();
    }

    function invalidateAllRows() {
      if (currentEditor) {
        makeActiveCellNormal();
      }
      for (var row in rowsCache) {
        removeRowFromCache(row);
      }
    }

    function removeRowFromCache(row) {
      var cacheEntry = rowsCache[row];
      if (!cacheEntry) {
        return;
      }

      if (rowNodeFromLastMouseWheelEvent == cacheEntry.rowNode) {
        cacheEntry.rowNode.style.display = 'none';
        zombieRowNodeFromLastMouseWheelEvent = rowNodeFromLastMouseWheelEvent;
      } else {
        $canvas[0].removeChild(cacheEntry.rowNode);
      }

      delete rowsCache[row];
      delete postProcessedRows[row];
      renderedRows--;
      counter_rows_removed++;
    }

    function invalidateRows(rows) {
      var i, rl;
      if (!rows || !rows.length) {
        return;
      }
      vScrollDir = 0;
      for (i = 0, rl = rows.length; i < rl; i++) {
        if (currentEditor && activeRow === rows[i]) {
          makeActiveCellNormal();
        }
        if (rowsCache[rows[i]]) {
          removeRowFromCache(rows[i]);
        }
      }
    }

    function invalidateRow(row) {
      invalidateRows([row]);
    }

    function updateCell(row, cell) {
      var cellNode = getCellNode(row, cell);
      if (!cellNode) {
        return;
      }

      var m = columns[cell], d = getDataItem(row);
      if (currentEditor && activeRow === row && activeCell === cell) {
        currentEditor.loadValue(d);
      } else {
        cellNode.innerHTML = d ? getFormatter(row, m)(row, cell, getDataItemValueForColumn(d, m), m, d) : "";
        invalidatePostProcessingResults(row);
      }
    }

    function updateRow(row) {
      var cacheEntry = rowsCache[row];
      if (!cacheEntry) {
        return;
      }

      ensureCellNodesInRowsCache(row);

      var d = getDataItem(row);

      for (var columnIdx in cacheEntry.cellNodesByColumnIdx) {
        if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(columnIdx)) {
          continue;
        }

        columnIdx = columnIdx | 0;
        var m = columns[columnIdx],
            node = cacheEntry.cellNodesByColumnIdx[columnIdx];

        if (row === activeRow && columnIdx === activeCell && currentEditor) {
          currentEditor.loadValue(d);
        } else if (d) {
          node.innerHTML = getFormatter(row, m)(row, columnIdx, getDataItemValueForColumn(d, m), m, d);
        } else {
          node.innerHTML = "";
        }
      }

      invalidatePostProcessingResults(row);
    }

    function getViewportHeight() {
      return parseFloat($.css($container[0], "height", true)) -
          parseFloat($.css($container[0], "paddingTop", true)) -
          parseFloat($.css($container[0], "paddingBottom", true)) -
          parseFloat($.css($headerScroller[0], "height")) - getVBoxDelta($headerScroller) -
          (options.showTopPanel ? options.topPanelHeight + getVBoxDelta($topPanelScroller) : 0) -
          (options.showHeaderRow ? options.headerRowHeight + getVBoxDelta($headerRowScroller) : 0);
    }

    function resizeCanvas() {
      if (!initialized) { return; }
      if (options.autoHeight) {
        viewportH = options.rowHeight * getDataLengthIncludingAddNew();
      } else {
        viewportH = getViewportHeight();
      }

      numVisibleRows = Math.ceil(viewportH / options.rowHeight);
      viewportW = parseFloat($.css($container[0], "width", true));
      if (!options.autoHeight) {
        $viewport.height(viewportH);
      }

      if (options.forceFitColumns) {
        autosizeColumns();
      }

      updateRowCount();
      handleScroll();
      // Since the width has changed, force the render() to reevaluate virtually rendered cells.
      lastRenderedScrollLeft = -1;
      render();
    }

    function updateRowCount() {
      if (!initialized) { return; }

      var dataLengthIncludingAddNew = getDataLengthIncludingAddNew();
      var numberOfRows = dataLengthIncludingAddNew +
          (options.leaveSpaceForNewRows ? numVisibleRows - 1 : 0);

      var oldViewportHasVScroll = viewportHasVScroll;
      // with autoHeight, we do not need to accommodate the vertical scroll bar
      viewportHasVScroll = !options.autoHeight && (numberOfRows * options.rowHeight > viewportH);

      makeActiveCellNormal();

      // remove the rows that are now outside of the data range
      // this helps avoid redundant calls to .removeRow() when the size of the data decreased by thousands of rows
      var l = dataLengthIncludingAddNew - 1;
      for (var i in rowsCache) {
        if (i >= l) {
          removeRowFromCache(i);
        }
      }

      if (activeCellNode && activeRow > l) {
        resetActiveCell();
      }

      var oldH = h;
      th = Math.max(options.rowHeight * numberOfRows, viewportH - scrollbarDimensions.height);
      if (th < maxSupportedCssHeight) {
        // just one page
        h = ph = th;
        n = 1;
        cj = 0;
      } else {
        // break into pages
        h = maxSupportedCssHeight;
        ph = h / 100;
        n = Math.floor(th / ph);
        cj = (th - h) / (n - 1);
      }

      if (h !== oldH) {
        $canvas.css("height", h);
        scrollTop = $viewport[0].scrollTop;
      }

      var oldScrollTopInRange = (scrollTop + offset <= th - viewportH);

      if (th == 0 || scrollTop == 0) {
        page = offset = 0;
      } else if (oldScrollTopInRange) {
        // maintain virtual position
        scrollTo(scrollTop + offset);
      } else {
        // scroll to bottom
        scrollTo(th - viewportH);
      }

      if (h != oldH && options.autoHeight) {
        resizeCanvas();
      }

      if (options.forceFitColumns && oldViewportHasVScroll != viewportHasVScroll) {
        autosizeColumns();
      }
      updateCanvasWidth(false);
    }

    function getVisibleRange(viewportTop, viewportLeft) {
      if (viewportTop == null) {
        viewportTop = scrollTop;
      }
      if (viewportLeft == null) {
        viewportLeft = scrollLeft;
      }

      return {
        top: getRowFromPosition(viewportTop),
        bottom: getRowFromPosition(viewportTop + viewportH) + 1,
        leftPx: viewportLeft,
        rightPx: viewportLeft + viewportW
      };
    }

    function getRenderedRange(viewportTop, viewportLeft) {
      var range = getVisibleRange(viewportTop, viewportLeft);
      var buffer = Math.round(viewportH / options.rowHeight);
      var minBuffer = 3;

      if (vScrollDir == -1) {
        range.top -= buffer;
        range.bottom += minBuffer;
      } else if (vScrollDir == 1) {
        range.top -= minBuffer;
        range.bottom += buffer;
      } else {
        range.top -= minBuffer;
        range.bottom += minBuffer;
      }

      range.top = Math.max(0, range.top);
      range.bottom = Math.min(getDataLengthIncludingAddNew() - 1, range.bottom);

      range.leftPx -= viewportW;
      range.rightPx += viewportW;

      range.leftPx = Math.max(0, range.leftPx);
      range.rightPx = Math.min(canvasWidth, range.rightPx);

      return range;
    }

    function ensureCellNodesInRowsCache(row) {
      var cacheEntry = rowsCache[row];
      if (cacheEntry) {
        if (cacheEntry.cellRenderQueue.length) {
          var lastChild = cacheEntry.rowNode.lastChild;
          while (cacheEntry.cellRenderQueue.length) {
            var columnIdx = cacheEntry.cellRenderQueue.pop();
            cacheEntry.cellNodesByColumnIdx[columnIdx] = lastChild;
            lastChild = lastChild.previousSibling;
          }
        }
      }
    }

    function cleanUpCells(range, row) {
      var totalCellsRemoved = 0;
      var cacheEntry = rowsCache[row];

      // Remove cells outside the range.
      var cellsToRemove = [];
      for (var i in cacheEntry.cellNodesByColumnIdx) {
        // I really hate it when people mess with Array.prototype.
        if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(i)) {
          continue;
        }

        // This is a string, so it needs to be cast back to a number.
        i = i | 0;

        var colspan = cacheEntry.cellColSpans[i];
        if (columnPosLeft[i] > range.rightPx ||
          columnPosRight[Math.min(columns.length - 1, i + colspan - 1)] < range.leftPx) {
          if (!(row == activeRow && i == activeCell)) {
            cellsToRemove.push(i);
          }
        }
      }

      var cellToRemove;
      while ((cellToRemove = cellsToRemove.pop()) != null) {
        cacheEntry.rowNode.removeChild(cacheEntry.cellNodesByColumnIdx[cellToRemove]);
        delete cacheEntry.cellColSpans[cellToRemove];
        delete cacheEntry.cellNodesByColumnIdx[cellToRemove];
        if (postProcessedRows[row]) {
          delete postProcessedRows[row][cellToRemove];
        }
        totalCellsRemoved++;
      }
    }

    function cleanUpAndRenderCells(range) {
      var cacheEntry;
      var stringArray = [];
      var processedRows = [];
      var cellsAdded;
      var totalCellsAdded = 0;
      var colspan;

      for (var row = range.top, btm = range.bottom; row <= btm; row++) {
        cacheEntry = rowsCache[row];
        if (!cacheEntry) {
          continue;
        }

        // cellRenderQueue populated in renderRows() needs to be cleared first
        ensureCellNodesInRowsCache(row);

        cleanUpCells(range, row);

        // Render missing cells.
        cellsAdded = 0;

        var metadata = data.getItemMetadata && data.getItemMetadata(row);
        metadata = metadata && metadata.columns;

        var d = getDataItem(row);

        // TODO:  shorten this loop (index? heuristics? binary search?)
        for (var i = 0, ii = columns.length; i < ii; i++) {
          // Cells to the right are outside the range.
          if (columnPosLeft[i] > range.rightPx) {
            break;
          }

          // Already rendered.
          if ((colspan = cacheEntry.cellColSpans[i]) != null) {
            i += (colspan > 1 ? colspan - 1 : 0);
            continue;
          }

          colspan = 1;
          if (metadata) {
            var columnData = metadata[columns[i].id] || metadata[i];
            colspan = (columnData && columnData.colspan) || 1;
            if (colspan === "*") {
              colspan = ii - i;
            }
          }

          if (columnPosRight[Math.min(ii - 1, i + colspan - 1)] > range.leftPx) {
            appendCellHtml(stringArray, row, i, colspan, d);
            cellsAdded++;
          }

          i += (colspan > 1 ? colspan - 1 : 0);
        }

        if (cellsAdded) {
          totalCellsAdded += cellsAdded;
          processedRows.push(row);
        }
      }

      if (!stringArray.length) {
        return;
      }

      var x = document.createElement("div");
      x.innerHTML = stringArray.join("");

      var processedRow;
      var node;
      while ((processedRow = processedRows.pop()) != null) {
        cacheEntry = rowsCache[processedRow];
        var columnIdx;
        while ((columnIdx = cacheEntry.cellRenderQueue.pop()) != null) {
          node = x.lastChild;
          cacheEntry.rowNode.appendChild(node);
          cacheEntry.cellNodesByColumnIdx[columnIdx] = node;
        }
      }
    }

    function renderRows(range) {
      var parentNode = $canvas[0],
          stringArray = [],
          rows = [],
          needToReselectCell = false,
          dataLength = getDataLength();

      for (var i = range.top, ii = range.bottom; i <= ii; i++) {
        if (rowsCache[i]) {
          continue;
        }
        renderedRows++;
        rows.push(i);

        // Create an entry right away so that appendRowHtml() can
        // start populatating it.
        rowsCache[i] = {
          "rowNode": null,

          // ColSpans of rendered cells (by column idx).
          // Can also be used for checking whether a cell has been rendered.
          "cellColSpans": [],

          // Cell nodes (by column idx).  Lazy-populated by ensureCellNodesInRowsCache().
          "cellNodesByColumnIdx": [],

          // Column indices of cell nodes that have been rendered, but not yet indexed in
          // cellNodesByColumnIdx.  These are in the same order as cell nodes added at the
          // end of the row.
          "cellRenderQueue": []
        };

        appendRowHtml(stringArray, i, range, dataLength);
        if (activeCellNode && activeRow === i) {
          needToReselectCell = true;
        }
        counter_rows_rendered++;
      }

      if (!rows.length) { return; }

      var x = document.createElement("div");
      x.innerHTML = stringArray.join("");

      for (var i = 0, ii = rows.length; i < ii; i++) {
        rowsCache[rows[i]].rowNode = parentNode.appendChild(x.firstChild);
      }

      if (needToReselectCell) {
        activeCellNode = getCellNode(activeRow, activeCell);
      }
    }

    function startPostProcessing() {
      if (!options.enableAsyncPostRender) {
        return;
      }
      clearTimeout(h_postrender);
      h_postrender = setTimeout(asyncPostProcessRows, options.asyncPostRenderDelay);
    }

    function invalidatePostProcessingResults(row) {
      delete postProcessedRows[row];
      postProcessFromRow = Math.min(postProcessFromRow, row);
      postProcessToRow = Math.max(postProcessToRow, row);
      startPostProcessing();
    }

    function updateRowPositions() {
      for (var row in rowsCache) {
        rowsCache[row].rowNode.style.top = getRowTop(row) + "px";
      }
    }

    function render() {
      if (!initialized) { return; }
      var visible = getVisibleRange();
      var rendered = getRenderedRange();

      // remove rows no longer in the viewport
      cleanupRows(rendered);

      // add new rows & missing cells in existing rows
      if (lastRenderedScrollLeft != scrollLeft) {
        cleanUpAndRenderCells(rendered);
      }

      // render missing rows
      renderRows(rendered);

      postProcessFromRow = visible.top;
      postProcessToRow = Math.min(getDataLengthIncludingAddNew() - 1, visible.bottom);
      startPostProcessing();

      lastRenderedScrollTop = scrollTop;
      lastRenderedScrollLeft = scrollLeft;
      h_render = null;
    }

    function handleHeaderRowScroll() {
      var scrollLeft = $headerRowScroller[0].scrollLeft;
      if (scrollLeft != $viewport[0].scrollLeft) {
        $viewport[0].scrollLeft = scrollLeft;
      }
    }

    function handleScroll() {
      scrollTop = $viewport[0].scrollTop;
      scrollLeft = $viewport[0].scrollLeft;
      var vScrollDist = Math.abs(scrollTop - prevScrollTop);
      var hScrollDist = Math.abs(scrollLeft - prevScrollLeft);

      if (hScrollDist) {
        prevScrollLeft = scrollLeft;
        $headerScroller[0].scrollLeft = scrollLeft;
        $topPanelScroller[0].scrollLeft = scrollLeft;
        $headerRowScroller[0].scrollLeft = scrollLeft;
      }

      if (vScrollDist) {
        vScrollDir = prevScrollTop < scrollTop ? 1 : -1;
        prevScrollTop = scrollTop;

        // switch virtual pages if needed
        if (vScrollDist < viewportH) {
          scrollTo(scrollTop + offset);
        } else {
          var oldOffset = offset;
          if (h == viewportH) {
            page = 0;
          } else {
            page = Math.min(n - 1, Math.floor(scrollTop * ((th - viewportH) / (h - viewportH)) * (1 / ph)));
          }
          offset = Math.round(page * cj);
          if (oldOffset != offset) {
            invalidateAllRows();
          }
        }
      }

      if (hScrollDist || vScrollDist) {
        if (h_render) {
          clearTimeout(h_render);
        }

        if (Math.abs(lastRenderedScrollTop - scrollTop) > 20 ||
            Math.abs(lastRenderedScrollLeft - scrollLeft) > 20) {
          if (options.forceSyncScrolling || (
              Math.abs(lastRenderedScrollTop - scrollTop) < viewportH &&
              Math.abs(lastRenderedScrollLeft - scrollLeft) < viewportW)) {
            render();
          } else {
            h_render = setTimeout(render, 50);
          }

          trigger(self.onViewportChanged, {});
        }
      }

      trigger(self.onScroll, {scrollLeft: scrollLeft, scrollTop: scrollTop});
    }

    function asyncPostProcessRows() {
      var dataLength = getDataLength();
      while (postProcessFromRow <= postProcessToRow) {
        var row = (vScrollDir >= 0) ? postProcessFromRow++ : postProcessToRow--;
        var cacheEntry = rowsCache[row];
        if (!cacheEntry || row >= dataLength) {
          continue;
        }

        if (!postProcessedRows[row]) {
          postProcessedRows[row] = {};
        }

        ensureCellNodesInRowsCache(row);
        for (var columnIdx in cacheEntry.cellNodesByColumnIdx) {
          if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(columnIdx)) {
            continue;
          }

          columnIdx = columnIdx | 0;

          var m = columns[columnIdx];
          if (m.asyncPostRender && !postProcessedRows[row][columnIdx]) {
            var node = cacheEntry.cellNodesByColumnIdx[columnIdx];
            if (node) {
              m.asyncPostRender(node, row, getDataItem(row), m);
            }
            postProcessedRows[row][columnIdx] = true;
          }
        }

        h_postrender = setTimeout(asyncPostProcessRows, options.asyncPostRenderDelay);
        return;
      }
    }

    function updateCellCssStylesOnRenderedRows(addedHash, removedHash) {
      var node, columnId, addedRowHash, removedRowHash;
      for (var row in rowsCache) {
        removedRowHash = removedHash && removedHash[row];
        addedRowHash = addedHash && addedHash[row];

        if (removedRowHash) {
          for (columnId in removedRowHash) {
            if (!addedRowHash || removedRowHash[columnId] != addedRowHash[columnId]) {
              node = getCellNode(row, getColumnIndex(columnId));
              if (node) {
                $(node).removeClass(removedRowHash[columnId]);
              }
            }
          }
        }

        if (addedRowHash) {
          for (columnId in addedRowHash) {
            if (!removedRowHash || removedRowHash[columnId] != addedRowHash[columnId]) {
              node = getCellNode(row, getColumnIndex(columnId));
              if (node) {
                $(node).addClass(addedRowHash[columnId]);
              }
            }
          }
        }
      }
    }

    function addCellCssStyles(key, hash) {
      if (cellCssClasses[key]) {
        throw "addCellCssStyles: cell CSS hash with key '" + key + "' already exists.";
      }

      cellCssClasses[key] = hash;
      updateCellCssStylesOnRenderedRows(hash, null);

      trigger(self.onCellCssStylesChanged, { "key": key, "hash": hash });
    }

    function removeCellCssStyles(key) {
      if (!cellCssClasses[key]) {
        return;
      }

      updateCellCssStylesOnRenderedRows(null, cellCssClasses[key]);
      delete cellCssClasses[key];

      trigger(self.onCellCssStylesChanged, { "key": key, "hash": null });
    }

    function setCellCssStyles(key, hash) {
      var prevHash = cellCssClasses[key];

      cellCssClasses[key] = hash;
      updateCellCssStylesOnRenderedRows(hash, prevHash);

      trigger(self.onCellCssStylesChanged, { "key": key, "hash": hash });
    }

    function getCellCssStyles(key) {
      return cellCssClasses[key];
    }

    function flashCell(row, cell, speed) {
      speed = speed || 100;
      if (rowsCache[row]) {
        var $cell = $(getCellNode(row, cell));

        function toggleCellClass(times) {
          if (!times) {
            return;
          }
          setTimeout(function () {
                $cell.queue(function () {
                  $cell.toggleClass(options.cellFlashingCssClass).dequeue();
                  toggleCellClass(times - 1);
                });
              },
              speed);
        }

        toggleCellClass(4);
      }
    }

    //////////////////////////////////////////////////////////////////////////////////////////////
    // Interactivity

    function handleMouseWheel(e) {
      var rowNode = $(e.target).closest(".bk-slick-row")[0];
      if (rowNode != rowNodeFromLastMouseWheelEvent) {
        if (zombieRowNodeFromLastMouseWheelEvent && zombieRowNodeFromLastMouseWheelEvent != rowNode) {
          $canvas[0].removeChild(zombieRowNodeFromLastMouseWheelEvent);
          zombieRowNodeFromLastMouseWheelEvent = null;
        }
        rowNodeFromLastMouseWheelEvent = rowNode;
      }
    }

    function handleDragInit(e, dd) {
      var cell = getCellFromEvent(e);
      if (!cell || !cellExists(cell.row, cell.cell)) {
        return false;
      }

      var retval = trigger(self.onDragInit, dd, e);
      if (e.isImmediatePropagationStopped()) {
        return retval;
      }

      // if nobody claims to be handling drag'n'drop by stopping immediate propagation,
      // cancel out of it
      return false;
    }

    function handleDragStart(e, dd) {
      var cell = getCellFromEvent(e);
      if (!cell || !cellExists(cell.row, cell.cell)) {
        return false;
      }

      var retval = trigger(self.onDragStart, dd, e);
      if (e.isImmediatePropagationStopped()) {
        return retval;
      }

      return false;
    }

    function handleDrag(e, dd) {
      return trigger(self.onDrag, dd, e);
    }

    function handleDragEnd(e, dd) {
      trigger(self.onDragEnd, dd, e);
    }

    function handleKeyDown(e) {
      trigger(self.onKeyDown, {row: activeRow, cell: activeCell}, e);
      var handled = e.isImmediatePropagationStopped();

      if (!handled) {
        if (!e.shiftKey && !e.altKey && !e.ctrlKey) {
          if (e.which == 27) {
            if (!getEditorLock().isActive()) {
              return; // no editing mode to cancel, allow bubbling and default processing (exit without cancelling the event)
            }
            cancelEditAndSetFocus();
          } else if (e.which == 34) {
            navigatePageDown();
            handled = true;
          } else if (e.which == 33) {
            navigatePageUp();
            handled = true;
          } else if (e.which == 37) {
            handled = navigateLeft();
          } else if (e.which == 39) {
            handled = navigateRight();
          } else if (e.which == 38) {
            handled = navigateUp();
          } else if (e.which == 40) {
            handled = navigateDown();
          } else if (e.which == 9) {
            handled = navigateNext();
          } else if (e.which == 13) {
            if (options.editable) {
              if (currentEditor) {
                // adding new row
                if (activeRow === getDataLength()) {
                  navigateDown();
                } else {
                  commitEditAndSetFocus();
                }
              } else {
                if (getEditorLock().commitCurrentEdit()) {
                  makeActiveCellEditable();
                }
              }
            }
            handled = true;
          }
        } else if (e.which == 9 && e.shiftKey && !e.ctrlKey && !e.altKey) {
          handled = navigatePrev();
        }
      }

      if (handled) {
        // the event has been handled so don't let parent element (bubbling/propagation) or browser (default) handle it
        e.stopPropagation();
        e.preventDefault();
        try {
          e.originalEvent.keyCode = 0; // prevent default behaviour for special keys in IE browsers (F3, F5, etc.)
        }
        // ignore exceptions - setting the original event's keycode throws access denied exception for "Ctrl"
        // (hitting control key only, nothing else), "Shift" (maybe others)
        catch (error) {
        }
      }
    }

    function handleClick(e) {
      if (!currentEditor) {
        // if this click resulted in some cell child node getting focus,
        // don't steal it back - keyboard events will still bubble up
        // IE9+ seems to default DIVs to tabIndex=0 instead of -1, so check for cell clicks directly.
        if (e.target != document.activeElement || $(e.target).hasClass("bk-slick-cell")) {
          setFocus();
        }
      }

      var cell = getCellFromEvent(e);
      if (!cell || (currentEditor !== null && activeRow == cell.row && activeCell == cell.cell)) {
        return;
      }

      trigger(self.onClick, {row: cell.row, cell: cell.cell}, e);
      if (e.isImmediatePropagationStopped()) {
        return;
      }

      if ((activeCell != cell.cell || activeRow != cell.row) && canCellBeActive(cell.row, cell.cell)) {
        if (!getEditorLock().isActive() || getEditorLock().commitCurrentEdit()) {
          scrollRowIntoView(cell.row, false);
          setActiveCellInternal(getCellNode(cell.row, cell.cell));
        }
      }
    }

    function handleContextMenu(e) {
      var $cell = $(e.target).closest(".bk-slick-cell", $canvas);
      if ($cell.length === 0) {
        return;
      }

      // are we editing this cell?
      if (activeCellNode === $cell[0] && currentEditor !== null) {
        return;
      }

      trigger(self.onContextMenu, {}, e);
    }

    function handleDblClick(e) {
      var cell = getCellFromEvent(e);
      if (!cell || (currentEditor !== null && activeRow == cell.row && activeCell == cell.cell)) {
        return;
      }

      trigger(self.onDblClick, {row: cell.row, cell: cell.cell}, e);
      if (e.isImmediatePropagationStopped()) {
        return;
      }

      if (options.editable) {
        gotoCell(cell.row, cell.cell, true);
      }
    }

    function handleHeaderMouseEnter(e) {
      trigger(self.onHeaderMouseEnter, {
        "column": $(this).data("column")
      }, e);
    }

    function handleHeaderMouseLeave(e) {
      trigger(self.onHeaderMouseLeave, {
        "column": $(this).data("column")
      }, e);
    }

    function handleHeaderContextMenu(e) {
      var $header = $(e.target).closest(".bk-slick-header-column", ".bk-slick-header-columns");
      var column = $header && $header.data("column");
      trigger(self.onHeaderContextMenu, {column: column}, e);
    }

    function handleHeaderClick(e) {
      var $header = $(e.target).closest(".bk-slick-header-column", ".bk-slick-header-columns");
      var column = $header && $header.data("column");
      if (column) {
        trigger(self.onHeaderClick, {column: column}, e);
      }
    }

    function handleMouseEnter(e) {
      trigger(self.onMouseEnter, {}, e);
    }

    function handleMouseLeave(e) {
      trigger(self.onMouseLeave, {}, e);
    }

    function cellExists(row, cell) {
      return !(row < 0 || row >= getDataLength() || cell < 0 || cell >= columns.length);
    }

    function getCellFromPoint(x, y) {
      var row = getRowFromPosition(y);
      var cell = 0;

      var w = 0;
      for (var i = 0; i < columns.length && w < x; i++) {
        w += columns[i].width;
        cell++;
      }

      if (cell < 0) {
        cell = 0;
      }

      return {row: row, cell: cell - 1};
    }

    function getCellFromNode(cellNode) {
      // read column number from .l<columnNumber> CSS class
      var cls = /l\d+/.exec(cellNode.className);
      if (!cls) {
        throw "getCellFromNode: cannot get cell - " + cellNode.className;
      }
      return parseInt(cls[0].substr(1, cls[0].length - 1), 10);
    }

    function getRowFromNode(rowNode) {
      for (var row in rowsCache) {
        if (rowsCache[row].rowNode === rowNode) {
          return row | 0;
        }
      }

      return null;
    }

    function getCellFromEvent(e) {
      var $cell = $(e.target).closest(".bk-slick-cell", $canvas);
      if (!$cell.length) {
        return null;
      }

      var row = getRowFromNode($cell[0].parentNode);
      var cell = getCellFromNode($cell[0]);

      if (row == null || cell == null) {
        return null;
      } else {
        return {
          "row": row,
          "cell": cell
        };
      }
    }

    function getCellNodeBox(row, cell) {
      if (!cellExists(row, cell)) {
        return null;
      }

      var y1 = getRowTop(row);
      var y2 = y1 + options.rowHeight - 1;
      var x1 = 0;
      for (var i = 0; i < cell; i++) {
        x1 += columns[i].width;
      }
      var x2 = x1 + columns[cell].width;

      return {
        top: y1,
        left: x1,
        bottom: y2,
        right: x2
      };
    }

    //////////////////////////////////////////////////////////////////////////////////////////////
    // Cell switching

    function resetActiveCell() {
      setActiveCellInternal(null, false);
    }

    function setFocus() {
      if (tabbingDirection == -1) {
        $focusSink[0].focus();
      } else {
        $focusSink2[0].focus();
      }
    }

    function scrollCellIntoView(row, cell, doPaging) {
      scrollRowIntoView(row, doPaging);

      var colspan = getColspan(row, cell);
      var left = columnPosLeft[cell],
        right = columnPosRight[cell + (colspan > 1 ? colspan - 1 : 0)],
        scrollRight = scrollLeft + viewportW;

      if (left < scrollLeft) {
        $viewport.scrollLeft(left);
        handleScroll();
        render();
      } else if (right > scrollRight) {
        $viewport.scrollLeft(Math.min(left, right - $viewport[0].clientWidth));
        handleScroll();
        render();
      }
    }

    function setActiveCellInternal(newCell, opt_editMode) {
      if (activeCellNode !== null) {
        makeActiveCellNormal();
        $(activeCellNode).removeClass("active");
        if (rowsCache[activeRow]) {
          $(rowsCache[activeRow].rowNode).removeClass("active");
        }
      }

      var activeCellChanged = (activeCellNode !== newCell);
      activeCellNode = newCell;

      if (activeCellNode != null) {
        activeRow = getRowFromNode(activeCellNode.parentNode);
        activeCell = activePosX = getCellFromNode(activeCellNode);

        if (opt_editMode == null) {
          opt_editMode = (activeRow == getDataLength()) || options.autoEdit;
        }

        $(activeCellNode).addClass("active");
        $(rowsCache[activeRow].rowNode).addClass("active");

        if (options.editable && opt_editMode && isCellPotentiallyEditable(activeRow, activeCell)) {
          clearTimeout(h_editorLoader);

          if (options.asyncEditorLoading) {
            h_editorLoader = setTimeout(function () {
              makeActiveCellEditable();
            }, options.asyncEditorLoadDelay);
          } else {
            makeActiveCellEditable();
          }
        }
      } else {
        activeRow = activeCell = null;
      }

      if (activeCellChanged) {
        trigger(self.onActiveCellChanged, getActiveCell());
      }
    }

    function clearTextSelection() {
      if (document.selection && document.selection.empty) {
        try {
          //IE fails here if selected element is not in dom
          document.selection.empty();
        } catch (e) { }
      } else if (window.getSelection) {
        var sel = window.getSelection();
        if (sel && sel.removeAllRanges) {
          sel.removeAllRanges();
        }
      }
    }

    function isCellPotentiallyEditable(row, cell) {
      var dataLength = getDataLength();
      // is the data for this row loaded?
      if (row < dataLength && !getDataItem(row)) {
        return false;
      }

      // are we in the Add New row?  can we create new from this cell?
      if (columns[cell].cannotTriggerInsert && row >= dataLength) {
        return false;
      }

      // does this cell have an editor?
      if (!getEditor(row, cell)) {
        return false;
      }

      return true;
    }

    function makeActiveCellNormal() {
      if (!currentEditor) {
        return;
      }
      trigger(self.onBeforeCellEditorDestroy, {editor: currentEditor});
      currentEditor.destroy();
      currentEditor = null;

      if (activeCellNode) {
        var d = getDataItem(activeRow);
        $(activeCellNode).removeClass("editable invalid");
        if (d) {
          var column = columns[activeCell];
          var formatter = getFormatter(activeRow, column);
          activeCellNode.innerHTML = formatter(activeRow, activeCell, getDataItemValueForColumn(d, column), column, d);
          invalidatePostProcessingResults(activeRow);
        }
      }

      // if there previously was text selected on a page (such as selected text in the edit cell just removed),
      // IE can't set focus to anything else correctly
      if (navigator.userAgent.toLowerCase().match(/msie/)) {
        clearTextSelection();
      }

      getEditorLock().deactivate(editController);
    }

    function makeActiveCellEditable(editor) {
      if (!activeCellNode) {
        return;
      }
      if (!options.editable) {
        throw "Grid : makeActiveCellEditable : should never get called when options.editable is false";
      }

      // cancel pending async call if there is one
      clearTimeout(h_editorLoader);

      if (!isCellPotentiallyEditable(activeRow, activeCell)) {
        return;
      }

      var columnDef = columns[activeCell];
      var item = getDataItem(activeRow);

      if (trigger(self.onBeforeEditCell, {row: activeRow, cell: activeCell, item: item, column: columnDef}) === false) {
        setFocus();
        return;
      }

      getEditorLock().activate(editController);
      $(activeCellNode).addClass("editable");

      // don't clear the cell if a custom editor is passed through
      if (!editor) {
        activeCellNode.innerHTML = "";
      }

      currentEditor = new (editor || getEditor(activeRow, activeCell))({
        grid: self,
        gridPosition: absBox($container[0]),
        position: absBox(activeCellNode),
        container: activeCellNode,
        column: columnDef,
        item: item || {},
        commitChanges: commitEditAndSetFocus,
        cancelChanges: cancelEditAndSetFocus
      });

      if (item) {
        currentEditor.loadValue(item);
      }

      serializedEditorValue = currentEditor.serializeValue();

      if (currentEditor.position) {
        handleActiveCellPositionChange();
      }
    }

    function commitEditAndSetFocus() {
      // if the commit fails, it would do so due to a validation error
      // if so, do not steal the focus from the editor
      if (getEditorLock().commitCurrentEdit()) {
        setFocus();
        if (options.autoEdit) {
          navigateDown();
        }
      }
    }

    function cancelEditAndSetFocus() {
      if (getEditorLock().cancelCurrentEdit()) {
        setFocus();
      }
    }

    function absBox(elem) {
      var box = {
        top: elem.offsetTop,
        left: elem.offsetLeft,
        bottom: 0,
        right: 0,
        width: $(elem).outerWidth(),
        height: $(elem).outerHeight(),
        visible: true};
      box.bottom = box.top + box.height;
      box.right = box.left + box.width;

      // walk up the tree
      var offsetParent = elem.offsetParent;
      while ((elem = elem.parentNode) != document.body) {
        if (box.visible && elem.scrollHeight != elem.offsetHeight && $(elem).css("overflowY") != "visible") {
          box.visible = box.bottom > elem.scrollTop && box.top < elem.scrollTop + elem.clientHeight;
        }

        if (box.visible && elem.scrollWidth != elem.offsetWidth && $(elem).css("overflowX") != "visible") {
          box.visible = box.right > elem.scrollLeft && box.left < elem.scrollLeft + elem.clientWidth;
        }

        box.left -= elem.scrollLeft;
        box.top -= elem.scrollTop;

        if (elem === offsetParent) {
          box.left += elem.offsetLeft;
          box.top += elem.offsetTop;
          offsetParent = elem.offsetParent;
        }

        box.bottom = box.top + box.height;
        box.right = box.left + box.width;
      }

      return box;
    }

    function getActiveCellPosition() {
      return absBox(activeCellNode);
    }

    function getGridPosition() {
      return absBox($container[0])
    }

    function handleActiveCellPositionChange() {
      if (!activeCellNode) {
        return;
      }

      trigger(self.onActiveCellPositionChanged, {});

      if (currentEditor) {
        var cellBox = getActiveCellPosition();
        if (currentEditor.show && currentEditor.hide) {
          if (!cellBox.visible) {
            currentEditor.hide();
          } else {
            currentEditor.show();
          }
        }

        if (currentEditor.position) {
          currentEditor.position(cellBox);
        }
      }
    }

    function getCellEditor() {
      return currentEditor;
    }

    function getActiveCell() {
      if (!activeCellNode) {
        return null;
      } else {
        return {row: activeRow, cell: activeCell};
      }
    }

    function getActiveCellNode() {
      return activeCellNode;
    }

    function scrollRowIntoView(row, doPaging) {
      var rowAtTop = row * options.rowHeight;
      var rowAtBottom = (row + 1) * options.rowHeight - viewportH + (viewportHasHScroll ? scrollbarDimensions.height : 0);

      // need to page down?
      if ((row + 1) * options.rowHeight > scrollTop + viewportH + offset) {
        scrollTo(doPaging ? rowAtTop : rowAtBottom);
        render();
      }
      // or page up?
      else if (row * options.rowHeight < scrollTop + offset) {
        scrollTo(doPaging ? rowAtBottom : rowAtTop);
        render();
      }
    }

    function scrollRowToTop(row) {
      scrollTo(row * options.rowHeight);
      render();
    }

    function scrollPage(dir) {
      var deltaRows = dir * numVisibleRows;
      scrollTo((getRowFromPosition(scrollTop) + deltaRows) * options.rowHeight);
      render();

      if (options.enableCellNavigation && activeRow != null) {
        var row = activeRow + deltaRows;
        var dataLengthIncludingAddNew = getDataLengthIncludingAddNew();
        if (row >= dataLengthIncludingAddNew) {
          row = dataLengthIncludingAddNew - 1;
        }
        if (row < 0) {
          row = 0;
        }

        var cell = 0, prevCell = null;
        var prevActivePosX = activePosX;
        while (cell <= activePosX) {
          if (canCellBeActive(row, cell)) {
            prevCell = cell;
          }
          cell += getColspan(row, cell);
        }

        if (prevCell !== null) {
          setActiveCellInternal(getCellNode(row, prevCell));
          activePosX = prevActivePosX;
        } else {
          resetActiveCell();
        }
      }
    }

    function navigatePageDown() {
      scrollPage(1);
    }

    function navigatePageUp() {
      scrollPage(-1);
    }

    function getColspan(row, cell) {
      var metadata = data.getItemMetadata && data.getItemMetadata(row);
      if (!metadata || !metadata.columns) {
        return 1;
      }

      var columnData = metadata.columns[columns[cell].id] || metadata.columns[cell];
      var colspan = (columnData && columnData.colspan);
      if (colspan === "*") {
        colspan = columns.length - cell;
      } else {
        colspan = colspan || 1;
      }

      return colspan;
    }

    function findFirstFocusableCell(row) {
      var cell = 0;
      while (cell < columns.length) {
        if (canCellBeActive(row, cell)) {
          return cell;
        }
        cell += getColspan(row, cell);
      }
      return null;
    }

    function findLastFocusableCell(row) {
      var cell = 0;
      var lastFocusableCell = null;
      while (cell < columns.length) {
        if (canCellBeActive(row, cell)) {
          lastFocusableCell = cell;
        }
        cell += getColspan(row, cell);
      }
      return lastFocusableCell;
    }

    function gotoRight(row, cell, posX) {
      if (cell >= columns.length) {
        return null;
      }

      do {
        cell += getColspan(row, cell);
      }
      while (cell < columns.length && !canCellBeActive(row, cell));

      if (cell < columns.length) {
        return {
          "row": row,
          "cell": cell,
          "posX": cell
        };
      }
      return null;
    }

    function gotoLeft(row, cell, posX) {
      if (cell <= 0) {
        return null;
      }

      var firstFocusableCell = findFirstFocusableCell(row);
      if (firstFocusableCell === null || firstFocusableCell >= cell) {
        return null;
      }

      var prev = {
        "row": row,
        "cell": firstFocusableCell,
        "posX": firstFocusableCell
      };
      var pos;
      while (true) {
        pos = gotoRight(prev.row, prev.cell, prev.posX);
        if (!pos) {
          return null;
        }
        if (pos.cell >= cell) {
          return prev;
        }
        prev = pos;
      }
    }

    function gotoDown(row, cell, posX) {
      var prevCell;
      var dataLengthIncludingAddNew = getDataLengthIncludingAddNew();
      while (true) {
        if (++row >= dataLengthIncludingAddNew) {
          return null;
        }

        prevCell = cell = 0;
        while (cell <= posX) {
          prevCell = cell;
          cell += getColspan(row, cell);
        }

        if (canCellBeActive(row, prevCell)) {
          return {
            "row": row,
            "cell": prevCell,
            "posX": posX
          };
        }
      }
    }

    function gotoUp(row, cell, posX) {
      var prevCell;
      while (true) {
        if (--row < 0) {
          return null;
        }

        prevCell = cell = 0;
        while (cell <= posX) {
          prevCell = cell;
          cell += getColspan(row, cell);
        }

        if (canCellBeActive(row, prevCell)) {
          return {
            "row": row,
            "cell": prevCell,
            "posX": posX
          };
        }
      }
    }

    function gotoNext(row, cell, posX) {
      if (row == null && cell == null) {
        row = cell = posX = 0;
        if (canCellBeActive(row, cell)) {
          return {
            "row": row,
            "cell": cell,
            "posX": cell
          };
        }
      }

      var pos = gotoRight(row, cell, posX);
      if (pos) {
        return pos;
      }

      var firstFocusableCell = null;
      var dataLengthIncludingAddNew = getDataLengthIncludingAddNew();
      while (++row < dataLengthIncludingAddNew) {
        firstFocusableCell = findFirstFocusableCell(row);
        if (firstFocusableCell !== null) {
          return {
            "row": row,
            "cell": firstFocusableCell,
            "posX": firstFocusableCell
          };
        }
      }
      return null;
    }

    function gotoPrev(row, cell, posX) {
      if (row == null && cell == null) {
        row = getDataLengthIncludingAddNew() - 1;
        cell = posX = columns.length - 1;
        if (canCellBeActive(row, cell)) {
          return {
            "row": row,
            "cell": cell,
            "posX": cell
          };
        }
      }

      var pos;
      var lastSelectableCell;
      while (!pos) {
        pos = gotoLeft(row, cell, posX);
        if (pos) {
          break;
        }
        if (--row < 0) {
          return null;
        }

        cell = 0;
        lastSelectableCell = findLastFocusableCell(row);
        if (lastSelectableCell !== null) {
          pos = {
            "row": row,
            "cell": lastSelectableCell,
            "posX": lastSelectableCell
          };
        }
      }
      return pos;
    }

    function navigateRight() {
      return navigate("right");
    }

    function navigateLeft() {
      return navigate("left");
    }

    function navigateDown() {
      return navigate("down");
    }

    function navigateUp() {
      return navigate("up");
    }

    function navigateNext() {
      return navigate("next");
    }

    function navigatePrev() {
      return navigate("prev");
    }

    /**
     * @param {string} dir Navigation direction.
     * @return {boolean} Whether navigation resulted in a change of active cell.
     */
    function navigate(dir) {
      if (!options.enableCellNavigation) {
        return false;
      }

      if (!activeCellNode && dir != "prev" && dir != "next") {
        return false;
      }

      if (!getEditorLock().commitCurrentEdit()) {
        return true;
      }
      setFocus();

      var tabbingDirections = {
        "up": -1,
        "down": 1,
        "left": -1,
        "right": 1,
        "prev": -1,
        "next": 1
      };
      tabbingDirection = tabbingDirections[dir];

      var stepFunctions = {
        "up": gotoUp,
        "down": gotoDown,
        "left": gotoLeft,
        "right": gotoRight,
        "prev": gotoPrev,
        "next": gotoNext
      };
      var stepFn = stepFunctions[dir];
      var pos = stepFn(activeRow, activeCell, activePosX);
      if (pos) {
        var isAddNewRow = (pos.row == getDataLength());
        scrollCellIntoView(pos.row, pos.cell, !isAddNewRow);
        setActiveCellInternal(getCellNode(pos.row, pos.cell));
        activePosX = pos.posX;
        return true;
      } else {
        setActiveCellInternal(getCellNode(activeRow, activeCell));
        return false;
      }
    }

    function getCellNode(row, cell) {
      if (rowsCache[row]) {
        ensureCellNodesInRowsCache(row);
        return rowsCache[row].cellNodesByColumnIdx[cell];
      }
      return null;
    }

    function setActiveCell(row, cell) {
      if (!initialized) { return; }
      if (row > getDataLength() || row < 0 || cell >= columns.length || cell < 0) {
        return;
      }

      if (!options.enableCellNavigation) {
        return;
      }

      scrollCellIntoView(row, cell, false);
      setActiveCellInternal(getCellNode(row, cell), false);
    }

    function canCellBeActive(row, cell) {
      if (!options.enableCellNavigation || row >= getDataLengthIncludingAddNew() ||
          row < 0 || cell >= columns.length || cell < 0) {
        return false;
      }

      var rowMetadata = data.getItemMetadata && data.getItemMetadata(row);
      if (rowMetadata && typeof rowMetadata.focusable === "boolean") {
        return rowMetadata.focusable;
      }

      var columnMetadata = rowMetadata && rowMetadata.columns;
      if (columnMetadata && columnMetadata[columns[cell].id] && typeof columnMetadata[columns[cell].id].focusable === "boolean") {
        return columnMetadata[columns[cell].id].focusable;
      }
      if (columnMetadata && columnMetadata[cell] && typeof columnMetadata[cell].focusable === "boolean") {
        return columnMetadata[cell].focusable;
      }

      return columns[cell].focusable;
    }

    function canCellBeSelected(row, cell) {
      if (row >= getDataLength() || row < 0 || cell >= columns.length || cell < 0) {
        return false;
      }

      var rowMetadata = data.getItemMetadata && data.getItemMetadata(row);
      if (rowMetadata && typeof rowMetadata.selectable === "boolean") {
        return rowMetadata.selectable;
      }

      var columnMetadata = rowMetadata && rowMetadata.columns && (rowMetadata.columns[columns[cell].id] || rowMetadata.columns[cell]);
      if (columnMetadata && typeof columnMetadata.selectable === "boolean") {
        return columnMetadata.selectable;
      }

      return columns[cell].selectable;
    }

    function gotoCell(row, cell, forceEdit) {
      if (!initialized) { return; }
      if (!canCellBeActive(row, cell)) {
        return;
      }

      if (!getEditorLock().commitCurrentEdit()) {
        return;
      }

      scrollCellIntoView(row, cell, false);

      var newCell = getCellNode(row, cell);

      // if selecting the 'add new' row, start editing right away
      setActiveCellInternal(newCell, forceEdit || (row === getDataLength()) || options.autoEdit);

      // if no editor was created, set the focus back on the grid
      if (!currentEditor) {
        setFocus();
      }
    }


    //////////////////////////////////////////////////////////////////////////////////////////////
    // IEditor implementation for the editor lock

    function commitCurrentEdit() {
      var item = getDataItem(activeRow);
      var column = columns[activeCell];

      if (currentEditor) {
        if (currentEditor.isValueChanged()) {
          var validationResults = currentEditor.validate();

          if (validationResults.valid) {
            if (activeRow < getDataLength()) {
              var editCommand = {
                row: activeRow,
                cell: activeCell,
                editor: currentEditor,
                serializedValue: currentEditor.serializeValue(),
                prevSerializedValue: serializedEditorValue,
                execute: function () {
                  this.editor.applyValue(item, this.serializedValue);
                  updateRow(this.row);
                  trigger(self.onCellChange, {
                    row: activeRow,
                    cell: activeCell,
                    item: item
                  });
                },
                undo: function () {
                  this.editor.applyValue(item, this.prevSerializedValue);
                  updateRow(this.row);
                  trigger(self.onCellChange, {
                    row: activeRow,
                    cell: activeCell,
                    item: item
                  });
                }
              };

              if (options.editCommandHandler) {
                makeActiveCellNormal();
                options.editCommandHandler(item, column, editCommand);
              } else {
                editCommand.execute();
                makeActiveCellNormal();
              }

            } else {
              var newItem = {};
              currentEditor.applyValue(newItem, currentEditor.serializeValue());
              makeActiveCellNormal();
              trigger(self.onAddNewRow, {item: newItem, column: column});
            }

            // check whether the lock has been re-acquired by event handlers
            return !getEditorLock().isActive();
          } else {
            // Re-add the CSS class to trigger transitions, if any.
            $(activeCellNode).removeClass("invalid");
            $(activeCellNode).width();  // force layout
            $(activeCellNode).addClass("invalid");

            trigger(self.onValidationError, {
              editor: currentEditor,
              cellNode: activeCellNode,
              validationResults: validationResults,
              row: activeRow,
              cell: activeCell,
              column: column
            });

            currentEditor.focus();
            return false;
          }
        }

        makeActiveCellNormal();
      }
      return true;
    }

    function cancelCurrentEdit() {
      makeActiveCellNormal();
      return true;
    }

    function rowsToRanges(rows) {
      var ranges = [];
      var lastCell = columns.length - 1;
      for (var i = 0; i < rows.length; i++) {
        ranges.push(new Slick.Range(rows[i], 0, rows[i], lastCell));
      }
      return ranges;
    }

    function getSelectedRows() {
      if (!selectionModel) {
        throw "Selection model is not set";
      }
      return selectedRows;
    }

    function setSelectedRows(rows) {
      if (!selectionModel) {
        throw "Selection model is not set";
      }
      selectionModel.setSelectedRanges(rowsToRanges(rows));
    }


    //////////////////////////////////////////////////////////////////////////////////////////////
    // Debug

    this.debug = function () {
      var s = "";

      s += ("\n" + "counter_rows_rendered:  " + counter_rows_rendered);
      s += ("\n" + "counter_rows_removed:  " + counter_rows_removed);
      s += ("\n" + "renderedRows:  " + renderedRows);
      s += ("\n" + "numVisibleRows:  " + numVisibleRows);
      s += ("\n" + "maxSupportedCssHeight:  " + maxSupportedCssHeight);
      s += ("\n" + "n(umber of pages):  " + n);
      s += ("\n" + "(current) page:  " + page);
      s += ("\n" + "page height (ph):  " + ph);
      s += ("\n" + "vScrollDir:  " + vScrollDir);

      alert(s);
    };

    // a debug helper to be able to access private members
    this.eval = function (expr) {
      return eval(expr);
    };

    //////////////////////////////////////////////////////////////////////////////////////////////
    // Public API

    $.extend(this, {
      "slickGridVersion": "2.1",

      // Events
      "onScroll": new Slick.Event(),
      "onSort": new Slick.Event(),
      "onHeaderMouseEnter": new Slick.Event(),
      "onHeaderMouseLeave": new Slick.Event(),
      "onHeaderContextMenu": new Slick.Event(),
      "onHeaderClick": new Slick.Event(),
      "onHeaderCellRendered": new Slick.Event(),
      "onBeforeHeaderCellDestroy": new Slick.Event(),
      "onHeaderRowCellRendered": new Slick.Event(),
      "onBeforeHeaderRowCellDestroy": new Slick.Event(),
      "onMouseEnter": new Slick.Event(),
      "onMouseLeave": new Slick.Event(),
      "onClick": new Slick.Event(),
      "onDblClick": new Slick.Event(),
      "onContextMenu": new Slick.Event(),
      "onKeyDown": new Slick.Event(),
      "onAddNewRow": new Slick.Event(),
      "onValidationError": new Slick.Event(),
      "onViewportChanged": new Slick.Event(),
      "onColumnsReordered": new Slick.Event(),
      "onColumnsResized": new Slick.Event(),
      "onCellChange": new Slick.Event(),
      "onBeforeEditCell": new Slick.Event(),
      "onBeforeCellEditorDestroy": new Slick.Event(),
      "onBeforeDestroy": new Slick.Event(),
      "onActiveCellChanged": new Slick.Event(),
      "onActiveCellPositionChanged": new Slick.Event(),
      "onDragInit": new Slick.Event(),
      "onDragStart": new Slick.Event(),
      "onDrag": new Slick.Event(),
      "onDragEnd": new Slick.Event(),
      "onSelectedRowsChanged": new Slick.Event(),
      "onCellCssStylesChanged": new Slick.Event(),

      // Methods
      "registerPlugin": registerPlugin,
      "unregisterPlugin": unregisterPlugin,
      "getColumns": getColumns,
      "setColumns": setColumns,
      "getColumnIndex": getColumnIndex,
      "updateColumnHeader": updateColumnHeader,
      "setSortColumn": setSortColumn,
      "setSortColumns": setSortColumns,
      "getSortColumns": getSortColumns,
      "autosizeColumns": autosizeColumns,
      "getOptions": getOptions,
      "setOptions": setOptions,
      "getData": getData,
      "getDataLength": getDataLength,
      "getDataItem": getDataItem,
      "setData": setData,
      "getSelectionModel": getSelectionModel,
      "setSelectionModel": setSelectionModel,
      "getSelectedRows": getSelectedRows,
      "setSelectedRows": setSelectedRows,
      "getContainerNode": getContainerNode,

      "render": render,
      "invalidate": invalidate,
      "invalidateRow": invalidateRow,
      "invalidateRows": invalidateRows,
      "invalidateAllRows": invalidateAllRows,
      "updateCell": updateCell,
      "updateRow": updateRow,
      "getViewport": getVisibleRange,
      "getRenderedRange": getRenderedRange,
      "resizeCanvas": resizeCanvas,
      "updateRowCount": updateRowCount,
      "scrollRowIntoView": scrollRowIntoView,
      "scrollRowToTop": scrollRowToTop,
      "scrollCellIntoView": scrollCellIntoView,
      "getCanvasNode": getCanvasNode,
      "focus": setFocus,

      "getCellFromPoint": getCellFromPoint,
      "getCellFromEvent": getCellFromEvent,
      "getActiveCell": getActiveCell,
      "setActiveCell": setActiveCell,
      "getActiveCellNode": getActiveCellNode,
      "getActiveCellPosition": getActiveCellPosition,
      "resetActiveCell": resetActiveCell,
      "editActiveCell": makeActiveCellEditable,
      "getCellEditor": getCellEditor,
      "getCellNode": getCellNode,
      "getCellNodeBox": getCellNodeBox,
      "canCellBeSelected": canCellBeSelected,
      "canCellBeActive": canCellBeActive,
      "navigatePrev": navigatePrev,
      "navigateNext": navigateNext,
      "navigateUp": navigateUp,
      "navigateDown": navigateDown,
      "navigateLeft": navigateLeft,
      "navigateRight": navigateRight,
      "navigatePageUp": navigatePageUp,
      "navigatePageDown": navigatePageDown,
      "gotoCell": gotoCell,
      "getTopPanel": getTopPanel,
      "setTopPanelVisibility": setTopPanelVisibility,
      "setHeaderRowVisibility": setHeaderRowVisibility,
      "getHeaderRow": getHeaderRow,
      "getHeaderRowColumn": getHeaderRowColumn,
      "getGridPosition": getGridPosition,
      "flashCell": flashCell,
      "addCellCssStyles": addCellCssStyles,
      "setCellCssStyles": setCellCssStyles,
      "removeCellCssStyles": removeCellCssStyles,
      "getCellCssStyles": getCellCssStyles,

      "init": finishInitialization,
      "destroy": destroy,

      // IEditor implementation
      "getEditorLock": getEditorLock,
      "getEditController": getEditController
    });

    init();
  }

  return SlickGrid;
});

define('slick_grid/plugins/slick.rowselectionmodel',["jquery", "../slick.core"], function ($, Slick) {

  function RowSelectionModel(options) {
    var _grid;
    var _ranges = [];
    var _self = this;
    var _handler = new Slick.EventHandler();
    var _inHandler;
    var _options;
    var _defaults = {
      selectActiveRow: true
    };

    function init(grid) {
      _options = $.extend(true, {}, _defaults, options);
      _grid = grid;
      _handler.subscribe(_grid.onActiveCellChanged,
          wrapHandler(handleActiveCellChange));
      _handler.subscribe(_grid.onKeyDown,
          wrapHandler(handleKeyDown));
      _handler.subscribe(_grid.onClick,
          wrapHandler(handleClick));
    }

    function destroy() {
      _handler.unsubscribeAll();
    }

    function wrapHandler(handler) {
      return function () {
        if (!_inHandler) {
          _inHandler = true;
          handler.apply(this, arguments);
          _inHandler = false;
        }
      };
    }

    function rangesToRows(ranges) {
      var rows = [];
      for (var i = 0; i < ranges.length; i++) {
        for (var j = ranges[i].fromRow; j <= ranges[i].toRow; j++) {
          rows.push(j);
        }
      }
      return rows;
    }

    function rowsToRanges(rows) {
      var ranges = [];
      var lastCell = _grid.getColumns().length - 1;
      for (var i = 0; i < rows.length; i++) {
        ranges.push(new Slick.Range(rows[i], 0, rows[i], lastCell));
      }
      return ranges;
    }

    function getRowsRange(from, to) {
      var i, rows = [];
      for (i = from; i <= to; i++) {
        rows.push(i);
      }
      for (i = to; i < from; i++) {
        rows.push(i);
      }
      return rows;
    }

    function getSelectedRows() {
      return rangesToRows(_ranges);
    }

    function setSelectedRows(rows) {
      setSelectedRanges(rowsToRanges(rows));
    }

    function setSelectedRanges(ranges) {
      _ranges = ranges;
      _self.onSelectedRangesChanged.notify(_ranges);
    }

    function getSelectedRanges() {
      return _ranges;
    }

    function handleActiveCellChange(e, data) {
      if (_options.selectActiveRow && data.row != null) {
        setSelectedRanges([new Slick.Range(data.row, 0, data.row, _grid.getColumns().length - 1)]);
      }
    }

    function handleKeyDown(e) {
      var activeRow = _grid.getActiveCell();
      if (activeRow && e.shiftKey && !e.ctrlKey && !e.altKey && !e.metaKey && (e.which == 38 || e.which == 40)) {
        var selectedRows = getSelectedRows();
        selectedRows.sort(function (x, y) {
          return x - y
        });

        if (!selectedRows.length) {
          selectedRows = [activeRow.row];
        }

        var top = selectedRows[0];
        var bottom = selectedRows[selectedRows.length - 1];
        var active;

        if (e.which == 40) {
          active = activeRow.row < bottom || top == bottom ? ++bottom : ++top;
        } else {
          active = activeRow.row < bottom ? --bottom : --top;
        }

        if (active >= 0 && active < _grid.getDataLength()) {
          _grid.scrollRowIntoView(active);
          _ranges = rowsToRanges(getRowsRange(top, bottom));
          setSelectedRanges(_ranges);
        }

        e.preventDefault();
        e.stopPropagation();
      }
    }

    function handleClick(e) {
      var cell = _grid.getCellFromEvent(e);
      if (!cell || !_grid.canCellBeActive(cell.row, cell.cell)) {
        return false;
      }

      if (!_grid.getOptions().multiSelect || (
          !e.ctrlKey && !e.shiftKey && !e.metaKey)) {
        return false;
      }

      var selection = rangesToRows(_ranges);
      var idx = $.inArray(cell.row, selection);

      if (idx === -1 && (e.ctrlKey || e.metaKey)) {
        selection.push(cell.row);
        _grid.setActiveCell(cell.row, cell.cell);
      } else if (idx !== -1 && (e.ctrlKey || e.metaKey)) {
        selection = $.grep(selection, function (o, i) {
          return (o !== cell.row);
        });
        _grid.setActiveCell(cell.row, cell.cell);
      } else if (selection.length && e.shiftKey) {
        var last = selection.pop();
        var from = Math.min(cell.row, last);
        var to = Math.max(cell.row, last);
        selection = [];
        for (var i = from; i <= to; i++) {
          if (i !== last) {
            selection.push(i);
          }
        }
        selection.push(last);
        _grid.setActiveCell(cell.row, cell.cell);
      }

      _ranges = rowsToRanges(selection);
      setSelectedRanges(_ranges);
      e.stopImmediatePropagation();

      return true;
    }

    $.extend(this, {
      "getSelectedRows": getSelectedRows,
      "setSelectedRows": setSelectedRows,

      "getSelectedRanges": getSelectedRanges,
      "setSelectedRanges": setSelectedRanges,

      "init": init,
      "destroy": destroy,

      "onSelectedRangesChanged": new Slick.Event()
    });
  }

  return RowSelectionModel;
});

define('slick_grid/plugins/slick.checkboxselectcolumn',["jquery", "../slick.core"], function ($, Slick) {

  function CheckboxSelectColumn(options) {
    var _grid;
    var _self = this;
    var _handler = new Slick.EventHandler();
    var _selectedRowsLookup = {};
    var _defaults = {
      columnId: "_checkbox_selector",
      cssClass: null,
      toolTip: "Select/Deselect All",
      width: 30
    };

    var _options = $.extend(true, {}, _defaults, options);

    function init(grid) {
      _grid = grid;
      _handler
        .subscribe(_grid.onSelectedRowsChanged, handleSelectedRowsChanged)
        .subscribe(_grid.onClick, handleClick)
        .subscribe(_grid.onHeaderClick, handleHeaderClick)
        .subscribe(_grid.onKeyDown, handleKeyDown);
    }

    function destroy() {
      _handler.unsubscribeAll();
    }

    function handleSelectedRowsChanged(e, args) {
      var selectedRows = _grid.getSelectedRows();
      var lookup = {}, row, i;
      for (i = 0; i < selectedRows.length; i++) {
        row = selectedRows[i];
        lookup[row] = true;
        if (lookup[row] !== _selectedRowsLookup[row]) {
          _grid.invalidateRow(row);
          delete _selectedRowsLookup[row];
        }
      }
      for (i in _selectedRowsLookup) {
        _grid.invalidateRow(i);
      }
      _selectedRowsLookup = lookup;
      _grid.render();

      if (selectedRows.length && selectedRows.length == _grid.getDataLength()) {
        _grid.updateColumnHeader(_options.columnId, "<input type='checkbox' checked='checked'>", _options.toolTip);
      } else {
        _grid.updateColumnHeader(_options.columnId, "<input type='checkbox'>", _options.toolTip);
      }
    }

    function handleKeyDown(e, args) {
      if (e.which == 32) {
        if (_grid.getColumns()[args.cell].id === _options.columnId) {
          // if editing, try to commit
          if (!_grid.getEditorLock().isActive() || _grid.getEditorLock().commitCurrentEdit()) {
            toggleRowSelection(args.row);
          }
          e.preventDefault();
          e.stopImmediatePropagation();
        }
      }
    }

    function handleClick(e, args) {
      // clicking on a row select checkbox
      if (_grid.getColumns()[args.cell].id === _options.columnId && $(e.target).is(":checkbox")) {
        // if editing, try to commit
        if (_grid.getEditorLock().isActive() && !_grid.getEditorLock().commitCurrentEdit()) {
          e.preventDefault();
          e.stopImmediatePropagation();
          return;
        }

        toggleRowSelection(args.row);
        e.stopPropagation();
        e.stopImmediatePropagation();
      }
    }

    function toggleRowSelection(row) {
      if (_selectedRowsLookup[row]) {
        _grid.setSelectedRows($.grep(_grid.getSelectedRows(), function (n) {
          return n != row
        }));
      } else {
        _grid.setSelectedRows(_grid.getSelectedRows().concat(row));
      }
    }

    function handleHeaderClick(e, args) {
      if (args.column.id == _options.columnId && $(e.target).is(":checkbox")) {
        // if editing, try to commit
        if (_grid.getEditorLock().isActive() && !_grid.getEditorLock().commitCurrentEdit()) {
          e.preventDefault();
          e.stopImmediatePropagation();
          return;
        }

        if ($(e.target).is(":checked")) {
          var rows = [];
          for (var i = 0; i < _grid.getDataLength(); i++) {
            rows.push(i);
          }
          _grid.setSelectedRows(rows);
        } else {
          _grid.setSelectedRows([]);
        }
        e.stopPropagation();
        e.stopImmediatePropagation();
      }
    }

    function getColumnDefinition() {
      return {
        id: _options.columnId,
        name: "<input type='checkbox'>",
        toolTip: _options.toolTip,
        field: "sel",
        width: _options.width,
        resizable: false,
        sortable: false,
        cssClass: _options.cssClass,
        formatter: checkboxSelectionFormatter
      };
    }

    function checkboxSelectionFormatter(row, cell, value, columnDef, dataContext) {
      if (dataContext) {
        return _selectedRowsLookup[row]
            ? "<input type='checkbox' checked='checked'>"
            : "<input type='checkbox'>";
      }
      return null;
    }

    $.extend(this, {
      "init": init,
      "destroy": destroy,

      "getColumnDefinition": getColumnDefinition
    });
  }

  return CheckboxSelectColumn;
});

/*!
 * jQuery UI Mouse 1.11.2
 * http://jqueryui.com
 *
 * Copyright 2014 jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/mouse/
 */
(function( factory ) {
	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define('jquery_ui/mouse',[
			"jquery",
			"./widget"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
}(function( $ ) {

var mouseHandled = false;
$( document ).mouseup( function() {
	mouseHandled = false;
});

return $.widget("ui.mouse", {
	version: "1.11.2",
	options: {
		cancel: "input,textarea,button,select,option",
		distance: 1,
		delay: 0
	},
	_mouseInit: function() {
		var that = this;

		this.element
			.bind("mousedown." + this.widgetName, function(event) {
				return that._mouseDown(event);
			})
			.bind("click." + this.widgetName, function(event) {
				if (true === $.data(event.target, that.widgetName + ".preventClickEvent")) {
					$.removeData(event.target, that.widgetName + ".preventClickEvent");
					event.stopImmediatePropagation();
					return false;
				}
			});

		this.started = false;
	},

	// TODO: make sure destroying one instance of mouse doesn't mess with
	// other instances of mouse
	_mouseDestroy: function() {
		this.element.unbind("." + this.widgetName);
		if ( this._mouseMoveDelegate ) {
			this.document
				.unbind("mousemove." + this.widgetName, this._mouseMoveDelegate)
				.unbind("mouseup." + this.widgetName, this._mouseUpDelegate);
		}
	},

	_mouseDown: function(event) {
		// don't let more than one widget handle mouseStart
		if ( mouseHandled ) {
			return;
		}

		this._mouseMoved = false;

		// we may have missed mouseup (out of window)
		(this._mouseStarted && this._mouseUp(event));

		this._mouseDownEvent = event;

		var that = this,
			btnIsLeft = (event.which === 1),
			// event.target.nodeName works around a bug in IE 8 with
			// disabled inputs (#7620)
			elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false);
		if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
			return true;
		}

		this.mouseDelayMet = !this.options.delay;
		if (!this.mouseDelayMet) {
			this._mouseDelayTimer = setTimeout(function() {
				that.mouseDelayMet = true;
			}, this.options.delay);
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted = (this._mouseStart(event) !== false);
			if (!this._mouseStarted) {
				event.preventDefault();
				return true;
			}
		}

		// Click event may never have fired (Gecko & Opera)
		if (true === $.data(event.target, this.widgetName + ".preventClickEvent")) {
			$.removeData(event.target, this.widgetName + ".preventClickEvent");
		}

		// these delegates are required to keep context
		this._mouseMoveDelegate = function(event) {
			return that._mouseMove(event);
		};
		this._mouseUpDelegate = function(event) {
			return that._mouseUp(event);
		};

		this.document
			.bind( "mousemove." + this.widgetName, this._mouseMoveDelegate )
			.bind( "mouseup." + this.widgetName, this._mouseUpDelegate );

		event.preventDefault();

		mouseHandled = true;
		return true;
	},

	_mouseMove: function(event) {
		// Only check for mouseups outside the document if you've moved inside the document
		// at least once. This prevents the firing of mouseup in the case of IE<9, which will
		// fire a mousemove event if content is placed under the cursor. See #7778
		// Support: IE <9
		if ( this._mouseMoved ) {
			// IE mouseup check - mouseup happened when mouse was out of window
			if ($.ui.ie && ( !document.documentMode || document.documentMode < 9 ) && !event.button) {
				return this._mouseUp(event);

			// Iframe mouseup check - mouseup occurred in another document
			} else if ( !event.which ) {
				return this._mouseUp( event );
			}
		}

		if ( event.which || event.button ) {
			this._mouseMoved = true;
		}

		if (this._mouseStarted) {
			this._mouseDrag(event);
			return event.preventDefault();
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted =
				(this._mouseStart(this._mouseDownEvent, event) !== false);
			(this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
		}

		return !this._mouseStarted;
	},

	_mouseUp: function(event) {
		this.document
			.unbind( "mousemove." + this.widgetName, this._mouseMoveDelegate )
			.unbind( "mouseup." + this.widgetName, this._mouseUpDelegate );

		if (this._mouseStarted) {
			this._mouseStarted = false;

			if (event.target === this._mouseDownEvent.target) {
				$.data(event.target, this.widgetName + ".preventClickEvent", true);
			}

			this._mouseStop(event);
		}

		mouseHandled = false;
		return false;
	},

	_mouseDistanceMet: function(event) {
		return (Math.max(
				Math.abs(this._mouseDownEvent.pageX - event.pageX),
				Math.abs(this._mouseDownEvent.pageY - event.pageY)
			) >= this.options.distance
		);
	},

	_mouseDelayMet: function(/* event */) {
		return this.mouseDelayMet;
	},

	// These are placeholder methods, to be overriden by extending plugin
	_mouseStart: function(/* event */) {},
	_mouseDrag: function(/* event */) {},
	_mouseStop: function(/* event */) {},
	_mouseCapture: function(/* event */) { return true; }
});

}));

/*!
 * jQuery UI Sortable 1.11.2
 * http://jqueryui.com
 *
 * Copyright 2014 jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/sortable/
 */
(function( factory ) {
	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define('jquery_ui/sortable',[
			"jquery",
			"./core",
			"./mouse",
			"./widget"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
}(function( $ ) {

return $.widget("ui.sortable", $.ui.mouse, {
	version: "1.11.2",
	widgetEventPrefix: "sort",
	ready: false,
	options: {
		appendTo: "parent",
		axis: false,
		connectWith: false,
		containment: false,
		cursor: "auto",
		cursorAt: false,
		dropOnEmpty: true,
		forcePlaceholderSize: false,
		forceHelperSize: false,
		grid: false,
		handle: false,
		helper: "original",
		items: "> *",
		opacity: false,
		placeholder: false,
		revert: false,
		scroll: true,
		scrollSensitivity: 20,
		scrollSpeed: 20,
		scope: "default",
		tolerance: "intersect",
		zIndex: 1000,

		// callbacks
		activate: null,
		beforeStop: null,
		change: null,
		deactivate: null,
		out: null,
		over: null,
		receive: null,
		remove: null,
		sort: null,
		start: null,
		stop: null,
		update: null
	},

	_isOverAxis: function( x, reference, size ) {
		return ( x >= reference ) && ( x < ( reference + size ) );
	},

	_isFloating: function( item ) {
		return (/left|right/).test(item.css("float")) || (/inline|table-cell/).test(item.css("display"));
	},

	_create: function() {

		var o = this.options;
		this.containerCache = {};
		this.element.addClass("bk-ui-sortable");

		//Get the items
		this.refresh();

		//Let's determine if the items are being displayed horizontally
		this.floating = this.items.length ? o.axis === "x" || this._isFloating(this.items[0].item) : false;

		//Let's determine the parent's offset
		this.offset = this.element.offset();

		//Initialize mouse events for interaction
		this._mouseInit();

		this._setHandleClassName();

		//We're ready to go
		this.ready = true;

	},

	_setOption: function( key, value ) {
		this._super( key, value );

		if ( key === "handle" ) {
			this._setHandleClassName();
		}
	},

	_setHandleClassName: function() {
		this.element.find( ".bk-ui-sortable-handle" ).removeClass( "bk-ui-sortable-handle" );
		$.each( this.items, function() {
			( this.instance.options.handle ?
				this.item.find( this.instance.options.handle ) : this.item )
				.addClass( "bk-ui-sortable-handle" );
		});
	},

	_destroy: function() {
		this.element
			.removeClass( "bk-ui-sortable bk-ui-sortable-disabled" )
			.find( ".bk-ui-sortable-handle" )
				.removeClass( "bk-ui-sortable-handle" );
		this._mouseDestroy();

		for ( var i = this.items.length - 1; i >= 0; i-- ) {
			this.items[i].item.removeData(this.widgetName + "-item");
		}

		return this;
	},

	_mouseCapture: function(event, overrideHandle) {
		var currentItem = null,
			validHandle = false,
			that = this;

		if (this.reverting) {
			return false;
		}

		if(this.options.disabled || this.options.type === "static") {
			return false;
		}

		//We have to refresh the items data once first
		this._refreshItems(event);

		//Find out if the clicked node (or one of its parents) is a actual item in this.items
		$(event.target).parents().each(function() {
			if($.data(this, that.widgetName + "-item") === that) {
				currentItem = $(this);
				return false;
			}
		});
		if($.data(event.target, that.widgetName + "-item") === that) {
			currentItem = $(event.target);
		}

		if(!currentItem) {
			return false;
		}
		if(this.options.handle && !overrideHandle) {
			$(this.options.handle, currentItem).find("*").addBack().each(function() {
				if(this === event.target) {
					validHandle = true;
				}
			});
			if(!validHandle) {
				return false;
			}
		}

		this.currentItem = currentItem;
		this._removeCurrentsFromItems();
		return true;

	},

	_mouseStart: function(event, overrideHandle, noActivation) {

		var i, body,
			o = this.options;

		this.currentContainer = this;

		//We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture
		this.refreshPositions();

		//Create and append the visible helper
		this.helper = this._createHelper(event);

		//Cache the helper size
		this._cacheHelperProportions();

		/*
		 * - Position generation -
		 * This block generates everything position related - it's the core of draggables.
		 */

		//Cache the margins of the original element
		this._cacheMargins();

		//Get the next scrolling parent
		this.scrollParent = this.helper.scrollParent();

		//The element's absolute position on the page minus margins
		this.offset = this.currentItem.offset();
		this.offset = {
			top: this.offset.top - this.margins.top,
			left: this.offset.left - this.margins.left
		};

		$.extend(this.offset, {
			click: { //Where the click happened, relative to the element
				left: event.pageX - this.offset.left,
				top: event.pageY - this.offset.top
			},
			parent: this._getParentOffset(),
			relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
		});

		// Only after we got the offset, we can change the helper's position to absolute
		// TODO: Still need to figure out a way to make relative sorting possible
		this.helper.css("position", "absolute");
		this.cssPosition = this.helper.css("position");

		//Generate the original position
		this.originalPosition = this._generatePosition(event);
		this.originalPageX = event.pageX;
		this.originalPageY = event.pageY;

		//Adjust the mouse offset relative to the helper if "cursorAt" is supplied
		(o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));

		//Cache the former DOM position
		this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] };

		//If the helper is not the original, hide the original so it's not playing any role during the drag, won't cause anything bad this way
		if(this.helper[0] !== this.currentItem[0]) {
			this.currentItem.hide();
		}

		//Create the placeholder
		this._createPlaceholder();

		//Set a containment if given in the options
		if(o.containment) {
			this._setContainment();
		}

		if( o.cursor && o.cursor !== "auto" ) { // cursor option
			body = this.document.find( "body" );

			// support: IE
			this.storedCursor = body.css( "cursor" );
			body.css( "cursor", o.cursor );

			this.storedStylesheet = $( "<style>*{ cursor: "+o.cursor+" !important; }</style>" ).appendTo( body );
		}

		if(o.opacity) { // opacity option
			if (this.helper.css("opacity")) {
				this._storedOpacity = this.helper.css("opacity");
			}
			this.helper.css("opacity", o.opacity);
		}

		if(o.zIndex) { // zIndex option
			if (this.helper.css("zIndex")) {
				this._storedZIndex = this.helper.css("zIndex");
			}
			this.helper.css("zIndex", o.zIndex);
		}

		//Prepare scrolling
		if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") {
			this.overflowOffset = this.scrollParent.offset();
		}

		//Call callbacks
		this._trigger("start", event, this._uiHash());

		//Recache the helper size
		if(!this._preserveHelperProportions) {
			this._cacheHelperProportions();
		}


		//Post "activate" events to possible containers
		if( !noActivation ) {
			for ( i = this.containers.length - 1; i >= 0; i-- ) {
				this.containers[ i ]._trigger( "activate", event, this._uiHash( this ) );
			}
		}

		//Prepare possible droppables
		if($.ui.ddmanager) {
			$.ui.ddmanager.current = this;
		}

		if ($.ui.ddmanager && !o.dropBehaviour) {
			$.ui.ddmanager.prepareOffsets(this, event);
		}

		this.dragging = true;

		this.helper.addClass("bk-ui-sortable-helper");
		this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position
		return true;

	},

	_mouseDrag: function(event) {
		var i, item, itemElement, intersection,
			o = this.options,
			scrolled = false;

		//Compute the helpers position
		this.position = this._generatePosition(event);
		this.positionAbs = this._convertPositionTo("absolute");

		if (!this.lastPositionAbs) {
			this.lastPositionAbs = this.positionAbs;
		}

		//Do scrolling
		if(this.options.scroll) {
			if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") {

				if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) {
					this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed;
				} else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity) {
					this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed;
				}

				if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) {
					this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed;
				} else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity) {
					this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed;
				}

			} else {

				if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) {
					scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
				} else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) {
					scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
				}

				if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) {
					scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
				} else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) {
					scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
				}

			}

			if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) {
				$.ui.ddmanager.prepareOffsets(this, event);
			}
		}

		//Regenerate the absolute position used for position checks
		this.positionAbs = this._convertPositionTo("absolute");

		//Set the helper position
		if(!this.options.axis || this.options.axis !== "y") {
			this.helper[0].style.left = this.position.left+"px";
		}
		if(!this.options.axis || this.options.axis !== "x") {
			this.helper[0].style.top = this.position.top+"px";
		}

		//Rearrange
		for (i = this.items.length - 1; i >= 0; i--) {

			//Cache variables and intersection, continue if no intersection
			item = this.items[i];
			itemElement = item.item[0];
			intersection = this._intersectsWithPointer(item);
			if (!intersection) {
				continue;
			}

			// Only put the placeholder inside the current Container, skip all
			// items from other containers. This works because when moving
			// an item from one container to another the
			// currentContainer is switched before the placeholder is moved.
			//
			// Without this, moving items in "sub-sortables" can cause
			// the placeholder to jitter between the outer and inner container.
			if (item.instance !== this.currentContainer) {
				continue;
			}

			// cannot intersect with itself
			// no useless actions that have been done before
			// no action if the item moved is the parent of the item checked
			if (itemElement !== this.currentItem[0] &&
				this.placeholder[intersection === 1 ? "next" : "prev"]()[0] !== itemElement &&
				!$.contains(this.placeholder[0], itemElement) &&
				(this.options.type === "semi-dynamic" ? !$.contains(this.element[0], itemElement) : true)
			) {

				this.direction = intersection === 1 ? "down" : "up";

				if (this.options.tolerance === "pointer" || this._intersectsWithSides(item)) {
					this._rearrange(event, item);
				} else {
					break;
				}

				this._trigger("change", event, this._uiHash());
				break;
			}
		}

		//Post events to containers
		this._contactContainers(event);

		//Interconnect with droppables
		if($.ui.ddmanager) {
			$.ui.ddmanager.drag(this, event);
		}

		//Call callbacks
		this._trigger("sort", event, this._uiHash());

		this.lastPositionAbs = this.positionAbs;
		return false;

	},

	_mouseStop: function(event, noPropagation) {

		if(!event) {
			return;
		}

		//If we are using droppables, inform the manager about the drop
		if ($.ui.ddmanager && !this.options.dropBehaviour) {
			$.ui.ddmanager.drop(this, event);
		}

		if(this.options.revert) {
			var that = this,
				cur = this.placeholder.offset(),
				axis = this.options.axis,
				animation = {};

			if ( !axis || axis === "x" ) {
				animation.left = cur.left - this.offset.parent.left - this.margins.left + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollLeft);
			}
			if ( !axis || axis === "y" ) {
				animation.top = cur.top - this.offset.parent.top - this.margins.top + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollTop);
			}
			this.reverting = true;
			$(this.helper).animate( animation, parseInt(this.options.revert, 10) || 500, function() {
				that._clear(event);
			});
		} else {
			this._clear(event, noPropagation);
		}

		return false;

	},

	cancel: function() {

		if(this.dragging) {

			this._mouseUp({ target: null });

			if(this.options.helper === "original") {
				this.currentItem.css(this._storedCSS).removeClass("bk-ui-sortable-helper");
			} else {
				this.currentItem.show();
			}

			//Post deactivating events to containers
			for (var i = this.containers.length - 1; i >= 0; i--){
				this.containers[i]._trigger("deactivate", null, this._uiHash(this));
				if(this.containers[i].containerCache.over) {
					this.containers[i]._trigger("out", null, this._uiHash(this));
					this.containers[i].containerCache.over = 0;
				}
			}

		}

		if (this.placeholder) {
			//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
			if(this.placeholder[0].parentNode) {
				this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
			}
			if(this.options.helper !== "original" && this.helper && this.helper[0].parentNode) {
				this.helper.remove();
			}

			$.extend(this, {
				helper: null,
				dragging: false,
				reverting: false,
				_noFinalSort: null
			});

			if(this.domPosition.prev) {
				$(this.domPosition.prev).after(this.currentItem);
			} else {
				$(this.domPosition.parent).prepend(this.currentItem);
			}
		}

		return this;

	},

	serialize: function(o) {

		var items = this._getItemsAsjQuery(o && o.connected),
			str = [];
		o = o || {};

		$(items).each(function() {
			var res = ($(o.item || this).attr(o.attribute || "id") || "").match(o.expression || (/(.+)[\-=_](.+)/));
			if (res) {
				str.push((o.key || res[1]+"[]")+"="+(o.key && o.expression ? res[1] : res[2]));
			}
		});

		if(!str.length && o.key) {
			str.push(o.key + "=");
		}

		return str.join("&");

	},

	toArray: function(o) {

		var items = this._getItemsAsjQuery(o && o.connected),
			ret = [];

		o = o || {};

		items.each(function() { ret.push($(o.item || this).attr(o.attribute || "id") || ""); });
		return ret;

	},

	/* Be careful with the following core functions */
	_intersectsWith: function(item) {

		var x1 = this.positionAbs.left,
			x2 = x1 + this.helperProportions.width,
			y1 = this.positionAbs.top,
			y2 = y1 + this.helperProportions.height,
			l = item.left,
			r = l + item.width,
			t = item.top,
			b = t + item.height,
			dyClick = this.offset.click.top,
			dxClick = this.offset.click.left,
			isOverElementHeight = ( this.options.axis === "x" ) || ( ( y1 + dyClick ) > t && ( y1 + dyClick ) < b ),
			isOverElementWidth = ( this.options.axis === "y" ) || ( ( x1 + dxClick ) > l && ( x1 + dxClick ) < r ),
			isOverElement = isOverElementHeight && isOverElementWidth;

		if ( this.options.tolerance === "pointer" ||
			this.options.forcePointerForContainers ||
			(this.options.tolerance !== "pointer" && this.helperProportions[this.floating ? "width" : "height"] > item[this.floating ? "width" : "height"])
		) {
			return isOverElement;
		} else {

			return (l < x1 + (this.helperProportions.width / 2) && // Right Half
				x2 - (this.helperProportions.width / 2) < r && // Left Half
				t < y1 + (this.helperProportions.height / 2) && // Bottom Half
				y2 - (this.helperProportions.height / 2) < b ); // Top Half

		}
	},

	_intersectsWithPointer: function(item) {

		var isOverElementHeight = (this.options.axis === "x") || this._isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height),
			isOverElementWidth = (this.options.axis === "y") || this._isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width),
			isOverElement = isOverElementHeight && isOverElementWidth,
			verticalDirection = this._getDragVerticalDirection(),
			horizontalDirection = this._getDragHorizontalDirection();

		if (!isOverElement) {
			return false;
		}

		return this.floating ?
			( ((horizontalDirection && horizontalDirection === "right") || verticalDirection === "down") ? 2 : 1 )
			: ( verticalDirection && (verticalDirection === "down" ? 2 : 1) );

	},

	_intersectsWithSides: function(item) {

		var isOverBottomHalf = this._isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height),
			isOverRightHalf = this._isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width),
			verticalDirection = this._getDragVerticalDirection(),
			horizontalDirection = this._getDragHorizontalDirection();

		if (this.floating && horizontalDirection) {
			return ((horizontalDirection === "right" && isOverRightHalf) || (horizontalDirection === "left" && !isOverRightHalf));
		} else {
			return verticalDirection && ((verticalDirection === "down" && isOverBottomHalf) || (verticalDirection === "up" && !isOverBottomHalf));
		}

	},

	_getDragVerticalDirection: function() {
		var delta = this.positionAbs.top - this.lastPositionAbs.top;
		return delta !== 0 && (delta > 0 ? "down" : "up");
	},

	_getDragHorizontalDirection: function() {
		var delta = this.positionAbs.left - this.lastPositionAbs.left;
		return delta !== 0 && (delta > 0 ? "right" : "left");
	},

	refresh: function(event) {
		this._refreshItems(event);
		this._setHandleClassName();
		this.refreshPositions();
		return this;
	},

	_connectWith: function() {
		var options = this.options;
		return options.connectWith.constructor === String ? [options.connectWith] : options.connectWith;
	},

	_getItemsAsjQuery: function(connected) {

		var i, j, cur, inst,
			items = [],
			queries = [],
			connectWith = this._connectWith();

		if(connectWith && connected) {
			for (i = connectWith.length - 1; i >= 0; i--){
				cur = $(connectWith[i]);
				for ( j = cur.length - 1; j >= 0; j--){
					inst = $.data(cur[j], this.widgetFullName);
					if(inst && inst !== this && !inst.options.disabled) {
						queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".bk-ui-sortable-helper").not(".bk-ui-sortable-placeholder"), inst]);
					}
				}
			}
		}

		queries.push([$.isFunction(this.options.items) ? this.options.items.call(this.element, null, { options: this.options, item: this.currentItem }) : $(this.options.items, this.element).not(".bk-ui-sortable-helper").not(".bk-ui-sortable-placeholder"), this]);

		function addItems() {
			items.push( this );
		}
		for (i = queries.length - 1; i >= 0; i--){
			queries[i][0].each( addItems );
		}

		return $(items);

	},

	_removeCurrentsFromItems: function() {

		var list = this.currentItem.find(":data(" + this.widgetName + "-item)");

		this.items = $.grep(this.items, function (item) {
			for (var j=0; j < list.length; j++) {
				if(list[j] === item.item[0]) {
					return false;
				}
			}
			return true;
		});

	},

	_refreshItems: function(event) {

		this.items = [];
		this.containers = [this];

		var i, j, cur, inst, targetData, _queries, item, queriesLength,
			items = this.items,
			queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]],
			connectWith = this._connectWith();

		if(connectWith && this.ready) { //Shouldn't be run the first time through due to massive slow-down
			for (i = connectWith.length - 1; i >= 0; i--){
				cur = $(connectWith[i]);
				for (j = cur.length - 1; j >= 0; j--){
					inst = $.data(cur[j], this.widgetFullName);
					if(inst && inst !== this && !inst.options.disabled) {
						queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]);
						this.containers.push(inst);
					}
				}
			}
		}

		for (i = queries.length - 1; i >= 0; i--) {
			targetData = queries[i][1];
			_queries = queries[i][0];

			for (j=0, queriesLength = _queries.length; j < queriesLength; j++) {
				item = $(_queries[j]);

				item.data(this.widgetName + "-item", targetData); // Data for target checking (mouse manager)

				items.push({
					item: item,
					instance: targetData,
					width: 0, height: 0,
					left: 0, top: 0
				});
			}
		}

	},

	refreshPositions: function(fast) {

		//This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change
		if(this.offsetParent && this.helper) {
			this.offset.parent = this._getParentOffset();
		}

		var i, item, t, p;

		for (i = this.items.length - 1; i >= 0; i--){
			item = this.items[i];

			//We ignore calculating positions of all connected containers when we're not over them
			if(item.instance !== this.currentContainer && this.currentContainer && item.item[0] !== this.currentItem[0]) {
				continue;
			}

			t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item;

			if (!fast) {
				item.width = t.outerWidth();
				item.height = t.outerHeight();
			}

			p = t.offset();
			item.left = p.left;
			item.top = p.top;
		}

		if(this.options.custom && this.options.custom.refreshContainers) {
			this.options.custom.refreshContainers.call(this);
		} else {
			for (i = this.containers.length - 1; i >= 0; i--){
				p = this.containers[i].element.offset();
				this.containers[i].containerCache.left = p.left;
				this.containers[i].containerCache.top = p.top;
				this.containers[i].containerCache.width = this.containers[i].element.outerWidth();
				this.containers[i].containerCache.height = this.containers[i].element.outerHeight();
			}
		}

		return this;
	},

	_createPlaceholder: function(that) {
		that = that || this;
		var className,
			o = that.options;

		if(!o.placeholder || o.placeholder.constructor === String) {
			className = o.placeholder;
			o.placeholder = {
				element: function() {

					var nodeName = that.currentItem[0].nodeName.toLowerCase(),
						element = $( "<" + nodeName + ">", that.document[0] )
							.addClass(className || that.currentItem[0].className+" bk-ui-sortable-placeholder")
							.removeClass("bk-ui-sortable-helper");

					if ( nodeName === "tr" ) {
						that.currentItem.children().each(function() {
							$( "<td>&#160;</td>", that.document[0] )
								.attr( "colspan", $( this ).attr( "colspan" ) || 1 )
								.appendTo( element );
						});
					} else if ( nodeName === "img" ) {
						element.attr( "src", that.currentItem.attr( "src" ) );
					}

					if ( !className ) {
						element.css( "visibility", "hidden" );
					}

					return element;
				},
				update: function(container, p) {

					// 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that
					// 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified
					if(className && !o.forcePlaceholderSize) {
						return;
					}

					//If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item
					if(!p.height()) { p.height(that.currentItem.innerHeight() - parseInt(that.currentItem.css("paddingTop")||0, 10) - parseInt(that.currentItem.css("paddingBottom")||0, 10)); }
					if(!p.width()) { p.width(that.currentItem.innerWidth() - parseInt(that.currentItem.css("paddingLeft")||0, 10) - parseInt(that.currentItem.css("paddingRight")||0, 10)); }
				}
			};
		}

		//Create the placeholder
		that.placeholder = $(o.placeholder.element.call(that.element, that.currentItem));

		//Append it after the actual current item
		that.currentItem.after(that.placeholder);

		//Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317)
		o.placeholder.update(that, that.placeholder);

	},

	_contactContainers: function(event) {
		var i, j, dist, itemWithLeastDistance, posProperty, sizeProperty, cur, nearBottom, floating, axis,
			innermostContainer = null,
			innermostIndex = null;

		// get innermost container that intersects with item
		for (i = this.containers.length - 1; i >= 0; i--) {

			// never consider a container that's located within the item itself
			if($.contains(this.currentItem[0], this.containers[i].element[0])) {
				continue;
			}

			if(this._intersectsWith(this.containers[i].containerCache)) {

				// if we've already found a container and it's more "inner" than this, then continue
				if(innermostContainer && $.contains(this.containers[i].element[0], innermostContainer.element[0])) {
					continue;
				}

				innermostContainer = this.containers[i];
				innermostIndex = i;

			} else {
				// container doesn't intersect. trigger "out" event if necessary
				if(this.containers[i].containerCache.over) {
					this.containers[i]._trigger("out", event, this._uiHash(this));
					this.containers[i].containerCache.over = 0;
				}
			}

		}

		// if no intersecting containers found, return
		if(!innermostContainer) {
			return;
		}

		// move the item into the container if it's not there already
		if(this.containers.length === 1) {
			if (!this.containers[innermostIndex].containerCache.over) {
				this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
				this.containers[innermostIndex].containerCache.over = 1;
			}
		} else {

			//When entering a new container, we will find the item with the least distance and append our item near it
			dist = 10000;
			itemWithLeastDistance = null;
			floating = innermostContainer.floating || this._isFloating(this.currentItem);
			posProperty = floating ? "left" : "top";
			sizeProperty = floating ? "width" : "height";
			axis = floating ? "clientX" : "clientY";

			for (j = this.items.length - 1; j >= 0; j--) {
				if(!$.contains(this.containers[innermostIndex].element[0], this.items[j].item[0])) {
					continue;
				}
				if(this.items[j].item[0] === this.currentItem[0]) {
					continue;
				}

				cur = this.items[j].item.offset()[posProperty];
				nearBottom = false;
				if ( event[ axis ] - cur > this.items[ j ][ sizeProperty ] / 2 ) {
					nearBottom = true;
				}

				if ( Math.abs( event[ axis ] - cur ) < dist ) {
					dist = Math.abs( event[ axis ] - cur );
					itemWithLeastDistance = this.items[ j ];
					this.direction = nearBottom ? "up": "down";
				}
			}

			//Check if dropOnEmpty is enabled
			if(!itemWithLeastDistance && !this.options.dropOnEmpty) {
				return;
			}

			if(this.currentContainer === this.containers[innermostIndex]) {
				if ( !this.currentContainer.containerCache.over ) {
					this.containers[ innermostIndex ]._trigger( "over", event, this._uiHash() );
					this.currentContainer.containerCache.over = 1;
				}
				return;
			}

			itemWithLeastDistance ? this._rearrange(event, itemWithLeastDistance, null, true) : this._rearrange(event, null, this.containers[innermostIndex].element, true);
			this._trigger("change", event, this._uiHash());
			this.containers[innermostIndex]._trigger("change", event, this._uiHash(this));
			this.currentContainer = this.containers[innermostIndex];

			//Update the placeholder
			this.options.placeholder.update(this.currentContainer, this.placeholder);

			this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
			this.containers[innermostIndex].containerCache.over = 1;
		}


	},

	_createHelper: function(event) {

		var o = this.options,
			helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper === "clone" ? this.currentItem.clone() : this.currentItem);

		//Add the helper to the DOM if that didn't happen already
		if(!helper.parents("body").length) {
			$(o.appendTo !== "parent" ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]);
		}

		if(helper[0] === this.currentItem[0]) {
			this._storedCSS = { width: this.currentItem[0].style.width, height: this.currentItem[0].style.height, position: this.currentItem.css("position"), top: this.currentItem.css("top"), left: this.currentItem.css("left") };
		}

		if(!helper[0].style.width || o.forceHelperSize) {
			helper.width(this.currentItem.width());
		}
		if(!helper[0].style.height || o.forceHelperSize) {
			helper.height(this.currentItem.height());
		}

		return helper;

	},

	_adjustOffsetFromHelper: function(obj) {
		if (typeof obj === "string") {
			obj = obj.split(" ");
		}
		if ($.isArray(obj)) {
			obj = {left: +obj[0], top: +obj[1] || 0};
		}
		if ("left" in obj) {
			this.offset.click.left = obj.left + this.margins.left;
		}
		if ("right" in obj) {
			this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
		}
		if ("top" in obj) {
			this.offset.click.top = obj.top + this.margins.top;
		}
		if ("bottom" in obj) {
			this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
		}
	},

	_getParentOffset: function() {


		//Get the offsetParent and cache its position
		this.offsetParent = this.helper.offsetParent();
		var po = this.offsetParent.offset();

		// This is a special case where we need to modify a offset calculated on start, since the following happened:
		// 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
		// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
		//    the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
		if(this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) {
			po.left += this.scrollParent.scrollLeft();
			po.top += this.scrollParent.scrollTop();
		}

		// This needs to be actually done for all browsers, since pageX/pageY includes this information
		// with an ugly IE fix
		if( this.offsetParent[0] === document.body || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) {
			po = { top: 0, left: 0 };
		}

		return {
			top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
			left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
		};

	},

	_getRelativeOffset: function() {

		if(this.cssPosition === "relative") {
			var p = this.currentItem.position();
			return {
				top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
				left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
			};
		} else {
			return { top: 0, left: 0 };
		}

	},

	_cacheMargins: function() {
		this.margins = {
			left: (parseInt(this.currentItem.css("marginLeft"),10) || 0),
			top: (parseInt(this.currentItem.css("marginTop"),10) || 0)
		};
	},

	_cacheHelperProportions: function() {
		this.helperProportions = {
			width: this.helper.outerWidth(),
			height: this.helper.outerHeight()
		};
	},

	_setContainment: function() {

		var ce, co, over,
			o = this.options;
		if(o.containment === "parent") {
			o.containment = this.helper[0].parentNode;
		}
		if(o.containment === "document" || o.containment === "window") {
			this.containment = [
				0 - this.offset.relative.left - this.offset.parent.left,
				0 - this.offset.relative.top - this.offset.parent.top,
				$(o.containment === "document" ? document : window).width() - this.helperProportions.width - this.margins.left,
				($(o.containment === "document" ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
			];
		}

		if(!(/^(document|window|parent)$/).test(o.containment)) {
			ce = $(o.containment)[0];
			co = $(o.containment).offset();
			over = ($(ce).css("overflow") !== "hidden");

			this.containment = [
				co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left,
				co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top,
				co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left,
				co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top
			];
		}

	},

	_convertPositionTo: function(d, pos) {

		if(!pos) {
			pos = this.position;
		}
		var mod = d === "absolute" ? 1 : -1,
			scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent,
			scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);

		return {
			top: (
				pos.top	+																// The absolute mouse position
				this.offset.relative.top * mod +										// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.top * mod -											// The offsetParent's offset without borders (offset + border)
				( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod)
			),
			left: (
				pos.left +																// The absolute mouse position
				this.offset.relative.left * mod +										// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.left * mod	-										// The offsetParent's offset without borders (offset + border)
				( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod)
			)
		};

	},

	_generatePosition: function(event) {

		var top, left,
			o = this.options,
			pageX = event.pageX,
			pageY = event.pageY,
			scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);

		// This is another very weird special case that only happens for relative elements:
		// 1. If the css position is relative
		// 2. and the scroll parent is the document or similar to the offset parent
		// we have to refresh the relative offset during the scroll so there are no jumps
		if(this.cssPosition === "relative" && !(this.scrollParent[0] !== document && this.scrollParent[0] !== this.offsetParent[0])) {
			this.offset.relative = this._getRelativeOffset();
		}

		/*
		 * - Position constraining -
		 * Constrain the position to a mix of grid, containment.
		 */

		if(this.originalPosition) { //If we are not dragging yet, we won't check for options

			if(this.containment) {
				if(event.pageX - this.offset.click.left < this.containment[0]) {
					pageX = this.containment[0] + this.offset.click.left;
				}
				if(event.pageY - this.offset.click.top < this.containment[1]) {
					pageY = this.containment[1] + this.offset.click.top;
				}
				if(event.pageX - this.offset.click.left > this.containment[2]) {
					pageX = this.containment[2] + this.offset.click.left;
				}
				if(event.pageY - this.offset.click.top > this.containment[3]) {
					pageY = this.containment[3] + this.offset.click.top;
				}
			}

			if(o.grid) {
				top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1];
				pageY = this.containment ? ( (top - this.offset.click.top >= this.containment[1] && top - this.offset.click.top <= this.containment[3]) ? top : ((top - this.offset.click.top >= this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;

				left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0];
				pageX = this.containment ? ( (left - this.offset.click.left >= this.containment[0] && left - this.offset.click.left <= this.containment[2]) ? left : ((left - this.offset.click.left >= this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
			}

		}

		return {
			top: (
				pageY -																// The absolute mouse position
				this.offset.click.top -													// Click offset (relative to the element)
				this.offset.relative.top	-											// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.top +												// The offsetParent's offset without borders (offset + border)
				( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ))
			),
			left: (
				pageX -																// The absolute mouse position
				this.offset.click.left -												// Click offset (relative to the element)
				this.offset.relative.left	-											// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.left +												// The offsetParent's offset without borders (offset + border)
				( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ))
			)
		};

	},

	_rearrange: function(event, i, a, hardRefresh) {

		a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction === "down" ? i.item[0] : i.item[0].nextSibling));

		//Various things done here to improve the performance:
		// 1. we create a setTimeout, that calls refreshPositions
		// 2. on the instance, we have a counter variable, that get's higher after every append
		// 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same
		// 4. this lets only the last addition to the timeout stack through
		this.counter = this.counter ? ++this.counter : 1;
		var counter = this.counter;

		this._delay(function() {
			if(counter === this.counter) {
				this.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove
			}
		});

	},

	_clear: function(event, noPropagation) {

		this.reverting = false;
		// We delay all events that have to be triggered to after the point where the placeholder has been removed and
		// everything else normalized again
		var i,
			delayedTriggers = [];

		// We first have to update the dom position of the actual currentItem
		// Note: don't do it if the current item is already removed (by a user), or it gets reappended (see #4088)
		if(!this._noFinalSort && this.currentItem.parent().length) {
			this.placeholder.before(this.currentItem);
		}
		this._noFinalSort = null;

		if(this.helper[0] === this.currentItem[0]) {
			for(i in this._storedCSS) {
				if(this._storedCSS[i] === "auto" || this._storedCSS[i] === "static") {
					this._storedCSS[i] = "";
				}
			}
			this.currentItem.css(this._storedCSS).removeClass("bk-ui-sortable-helper");
		} else {
			this.currentItem.show();
		}

		if(this.fromOutside && !noPropagation) {
			delayedTriggers.push(function(event) { this._trigger("receive", event, this._uiHash(this.fromOutside)); });
		}
		if((this.fromOutside || this.domPosition.prev !== this.currentItem.prev().not(".bk-ui-sortable-helper")[0] || this.domPosition.parent !== this.currentItem.parent()[0]) && !noPropagation) {
			delayedTriggers.push(function(event) { this._trigger("update", event, this._uiHash()); }); //Trigger update callback if the DOM position has changed
		}

		// Check if the items Container has Changed and trigger appropriate
		// events.
		if (this !== this.currentContainer) {
			if(!noPropagation) {
				delayedTriggers.push(function(event) { this._trigger("remove", event, this._uiHash()); });
				delayedTriggers.push((function(c) { return function(event) { c._trigger("receive", event, this._uiHash(this)); };  }).call(this, this.currentContainer));
				delayedTriggers.push((function(c) { return function(event) { c._trigger("update", event, this._uiHash(this));  }; }).call(this, this.currentContainer));
			}
		}


		//Post events to containers
		function delayEvent( type, instance, container ) {
			return function( event ) {
				container._trigger( type, event, instance._uiHash( instance ) );
			};
		}
		for (i = this.containers.length - 1; i >= 0; i--){
			if (!noPropagation) {
				delayedTriggers.push( delayEvent( "deactivate", this, this.containers[ i ] ) );
			}
			if(this.containers[i].containerCache.over) {
				delayedTriggers.push( delayEvent( "out", this, this.containers[ i ] ) );
				this.containers[i].containerCache.over = 0;
			}
		}

		//Do what was originally in plugins
		if ( this.storedCursor ) {
			this.document.find( "body" ).css( "cursor", this.storedCursor );
			this.storedStylesheet.remove();
		}
		if(this._storedOpacity) {
			this.helper.css("opacity", this._storedOpacity);
		}
		if(this._storedZIndex) {
			this.helper.css("zIndex", this._storedZIndex === "auto" ? "" : this._storedZIndex);
		}

		this.dragging = false;

		if(!noPropagation) {
			this._trigger("beforeStop", event, this._uiHash());
		}

		//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
		this.placeholder[0].parentNode.removeChild(this.placeholder[0]);

		if ( !this.cancelHelperRemoval ) {
			if ( this.helper[ 0 ] !== this.currentItem[ 0 ] ) {
				this.helper.remove();
			}
			this.helper = null;
		}

		if(!noPropagation) {
			for (i=0; i < delayedTriggers.length; i++) {
				delayedTriggers[i].call(this, event);
			} //Trigger all delayed events
			this._trigger("stop", event, this._uiHash());
		}

		this.fromOutside = false;
		return !this.cancelHelperRemoval;

	},

	_trigger: function() {
		if ($.Widget.prototype._trigger.apply(this, arguments) === false) {
			this.cancel();
		}
	},

	_uiHash: function(_inst) {
		var inst = _inst || this;
		return {
			helper: inst.helper,
			placeholder: inst.placeholder || $([]),
			position: inst.position,
			originalPosition: inst.originalPosition,
			offset: inst.positionAbs,
			item: inst.currentItem,
			sender: _inst ? _inst.element : null
		};
	}

});

}));

(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('widget/data_table',["underscore", "jquery", "common/continuum_view", "common/has_properties", "common/collection", "util/dom_util", "slick_grid/slick.grid", "slick_grid/plugins/slick.rowselectionmodel", "slick_grid/plugins/slick.checkboxselectcolumn", "jquery_ui/sortable"], function(_, $, ContinuumView, HasProperties, Collection, DOMUtil, SlickGrid, RowSelectionModel, CheckboxSelectColumn, $1) {
    var DataProvider, DataTable, DataTableView, DataTables, _ref, _ref1, _ref2;
    DataProvider = (function() {
      function DataProvider(source) {
        var _i, _ref, _results;
        this.source = source;
        this.data = this.source.get('data');
        this.fields = _.keys(this.data);
        if (!_.contains(this.fields, "index")) {
          this.data["index"] = (function() {
            _results = [];
            for (var _i = 0, _ref = this.getLength(); 0 <= _ref ? _i < _ref : _i > _ref; 0 <= _ref ? _i++ : _i--){ _results.push(_i); }
            return _results;
          }).apply(this);
          this.fields.push("index");
        }
      }

      DataProvider.prototype.getLength = function() {
        return this.source.get_length();
      };

      DataProvider.prototype.getItem = function(index) {
        var field, item, _i, _len, _ref;
        item = {
          index: index
        };
        _ref = this.fields;
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          field = _ref[_i];
          item[field] = this.data[field][index];
        }
        return item;
      };

      DataProvider.prototype._setItem = function(index, item) {
        var field, value;
        for (field in item) {
          value = item[field];
          this.data[field][index] = value;
        }
      };

      DataProvider.prototype.setItem = function(index, item) {
        this._setItem(index, item);
        return this.updateSource();
      };

      DataProvider.prototype.getField = function(index, field) {
        return this.data[field][index];
      };

      DataProvider.prototype._setField = function(index, field, value) {
        this.data[field][index] = value;
      };

      DataProvider.prototype.setField = function(index, field, value) {
        this._setField(index, field, value);
        return this.updateSource();
      };

      DataProvider.prototype.updateSource = function() {
        return this.source.forceTrigger("data");
      };

      DataProvider.prototype.getItemMetadata = function(index) {
        return null;
      };

      DataProvider.prototype.getRecords = function() {
        var i;
        return (function() {
          var _i, _ref, _results;
          _results = [];
          for (i = _i = 0, _ref = this.getLength(); 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
            _results.push(this.getItem(i));
          }
          return _results;
        }).call(this);
      };

      DataProvider.prototype.sort = function(columns) {
        var cols, column, i, record, records, _i, _len;
        cols = (function() {
          var _i, _len, _results;
          _results = [];
          for (_i = 0, _len = columns.length; _i < _len; _i++) {
            column = columns[_i];
            _results.push([column.sortCol.field, column.sortAsc ? 1 : -1]);
          }
          return _results;
        })();
        if (_.isEmpty(cols)) {
          cols = [["index", 1]];
        }
        records = this.getRecords();
        records.sort(function(record1, record2) {
          var field, result, sign, value1, value2, _i, _len, _ref;
          for (_i = 0, _len = cols.length; _i < _len; _i++) {
            _ref = cols[_i], field = _ref[0], sign = _ref[1];
            value1 = record1[field];
            value2 = record2[field];
            result = value1 === value2 ? 0 : value1 > value2 ? sign : -sign;
            if (result !== 0) {
              return result;
            }
          }
          return 0;
        });
        for (i = _i = 0, _len = records.length; _i < _len; i = ++_i) {
          record = records[i];
          this._setItem(i, record);
        }
        return this.updateSource();
      };

      return DataProvider;

    })();
    DataTableView = (function(_super) {
      __extends(DataTableView, _super);

      function DataTableView() {
        _ref = DataTableView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      DataTableView.prototype.attributes = {
        "class": "bk-data-table"
      };

      DataTableView.prototype.initialize = function(options) {
        var source,
          _this = this;
        DataTableView.__super__.initialize.call(this, options);
        DOMUtil.waitForElement(this.el, function() {
          return _this.render();
        });
        this.listenTo(this.model, 'change', function() {
          return _this.render();
        });
        source = this.mget("source");
        this.listenTo(source, 'change:data', function() {
          return _this.updateGrid();
        });
        return this.listenTo(source, 'change:selected', function() {
          return _this.updateSelection();
        });
      };

      DataTableView.prototype.updateGrid = function() {
        this.data = new DataProvider(this.mget("source"));
        this.grid.setData(this.data);
        return this.grid.render();
      };

      DataTableView.prototype.updateSelection = function() {
        var selected;
        selected = this.mget("source").get("selected");
        return this.grid.setSelectedRows(selected);
      };

      DataTableView.prototype.newIndexColumn = function() {
        return {
          id: _.uniqueId(),
          name: "#",
          field: "index",
          width: 40,
          behavior: "select",
          cannotTriggerInsert: true,
          resizable: false,
          selectable: false,
          sortable: true,
          cssClass: "bk-cell-index"
        };
      };

      DataTableView.prototype.render = function() {
        var checkboxSelector, column, columns, height, options, width,
          _this = this;
        columns = (function() {
          var _i, _len, _ref1, _results;
          _ref1 = this.mget("columns");
          _results = [];
          for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
            column = _ref1[_i];
            _results.push(column.toColumn());
          }
          return _results;
        }).call(this);
        if (this.mget("selectable") === "checkbox") {
          checkboxSelector = new CheckboxSelectColumn({
            cssClass: "bk-cell-select"
          });
          columns.unshift(checkboxSelector.getColumnDefinition());
        }
        if (this.mget("row_headers") && (this.mget("source").get_column("index") != null)) {
          columns.unshift(this.newIndexColumn());
        }
        width = this.mget("width");
        height = this.mget("height");
        options = {
          enableCellNavigation: this.mget("selectable") !== false,
          enableColumnReorder: true,
          forceFitColumns: this.mget("fit_columns"),
          autoHeight: height === "auto",
          multiColumnSort: this.mget("sortable"),
          editable: this.mget("editable"),
          autoEdit: false
        };
        if (width != null) {
          this.$el.css({
            width: "" + (this.mget("width")) + "px"
          });
        }
        if ((height != null) && height !== "auto") {
          this.$el.css({
            height: "" + (this.mget("height")) + "px"
          });
        }
        this.data = new DataProvider(this.mget("source"));
        this.grid = new SlickGrid(this.el, this.data, columns, options);
        this.grid.onSort.subscribe(function(event, args) {
          columns = args.sortCols;
          _this.data.sort(columns);
          _this.grid.invalidate();
          return _this.grid.render();
        });
        if (this.mget("selectable") !== false) {
          this.grid.setSelectionModel(new RowSelectionModel({
            selectActiveRow: checkboxSelector == null
          }));
          if (checkboxSelector != null) {
            this.grid.registerPlugin(checkboxSelector);
          }
          return this.grid.onSelectedRowsChanged.subscribe(function(event, args) {
            return _this.mget("source").set("selected", args.rows);
          });
        }
      };

      return DataTableView;

    })(ContinuumView);
    DataTable = (function(_super) {
      __extends(DataTable, _super);

      function DataTable() {
        _ref1 = DataTable.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      DataTable.prototype.type = 'DataTable';

      DataTable.prototype.default_view = DataTableView;

      DataTable.prototype.defaults = function() {
        return _.extend({}, DataTable.__super__.defaults.call(this), {
          columns: [],
          width: null,
          height: 400,
          fit_columns: true,
          sortable: true,
          editable: false,
          selectable: true,
          row_headers: true
        });
      };

      return DataTable;

    })(HasProperties);
    DataTables = (function(_super) {
      __extends(DataTables, _super);

      function DataTables() {
        _ref2 = DataTables.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      DataTables.prototype.model = DataTable;

      return DataTables;

    })(Collection);
    return {
      Model: DataTable,
      Collection: new DataTables(),
      View: DataTableView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=data_table.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('widget/paragraph',["common/has_parent", "common/continuum_view", "common/collection"], function(HasParent, ContinuumView, Collection) {
    var Paragraph, ParagraphView, Paragraphs, paragraphs, _ref, _ref1, _ref2;
    ParagraphView = (function(_super) {
      __extends(ParagraphView, _super);

      function ParagraphView() {
        _ref = ParagraphView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      ParagraphView.prototype.tagName = "p";

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

      ParagraphView.prototype.render = function() {
        if (this.mget('height')) {
          this.$el.height(this.mget('height'));
        }
        if (this.mget('width')) {
          this.$el.width(this.mget('width'));
        }
        return this.$el.text(this.mget('text'));
      };

      return ParagraphView;

    })(ContinuumView);
    Paragraph = (function(_super) {
      __extends(Paragraph, _super);

      function Paragraph() {
        _ref1 = Paragraph.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Paragraph.prototype.type = "Paragraph";

      Paragraph.prototype.default_view = ParagraphView;

      Paragraph.prototype.defaults = function() {
        return _.extend({}, Paragraph.__super__.defaults.call(this), {
          text: ''
        });
      };

      return Paragraph;

    })(HasParent);
    Paragraphs = (function(_super) {
      __extends(Paragraphs, _super);

      function Paragraphs() {
        _ref2 = Paragraphs.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Paragraphs.prototype.model = Paragraph;

      return Paragraphs;

    })(Collection);
    paragraphs = new Paragraphs();
    return {
      "Model": Paragraph,
      "Collection": paragraphs,
      "View": ParagraphView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=paragraph.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('widget/hbox',["common/has_parent", "common/continuum_view", "common/build_views", "common/collection"], function(HasParent, ContinuumView, build_views, Collection) {
    var HBox, HBoxView, HBoxes, hboxes, _ref, _ref1, _ref2;
    HBoxView = (function(_super) {
      __extends(HBoxView, _super);

      function HBoxView() {
        _ref = HBoxView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      HBoxView.prototype.tag = "div";

      HBoxView.prototype.attributes = {
        "class": "bk-hbox"
      };

      HBoxView.prototype.initialize = function(options) {
        HBoxView.__super__.initialize.call(this, options);
        this.views = {};
        this.render();
        return this.listenTo(this.model, 'change', this.render);
      };

      HBoxView.prototype.render = function() {
        var child, children, height, key, val, width, _i, _len, _ref1, _results;
        children = this.mget('children');
        build_views(this.views, children);
        _ref1 = this.views;
        for (key in _ref1) {
          if (!__hasProp.call(_ref1, key)) continue;
          val = _ref1[key];
          val.$el.detach();
        }
        this.$el.empty();
        width = this.mget("width");
        if (width != null) {
          this.$el.css({
            width: width + "px"
          });
        }
        height = this.mget("height");
        if (height != null) {
          this.$el.css({
            height: height + "px"
          });
        }
        _results = [];
        for (_i = 0, _len = children.length; _i < _len; _i++) {
          child = children[_i];
          _results.push(this.$el.append(this.views[child.id].$el));
        }
        return _results;
      };

      return HBoxView;

    })(ContinuumView);
    HBox = (function(_super) {
      __extends(HBox, _super);

      function HBox() {
        _ref1 = HBox.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      HBox.prototype.type = "HBox";

      HBox.prototype.default_view = HBoxView;

      HBox.prototype.defaults = function() {
        return _.extend({}, HBox.__super__.defaults.call(this), {
          children: []
        });
      };

      return HBox;

    })(HasParent);
    HBoxes = (function(_super) {
      __extends(HBoxes, _super);

      function HBoxes() {
        _ref2 = HBoxes.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      HBoxes.prototype.model = HBox;

      return HBoxes;

    })(Collection);
    hboxes = new HBoxes();
    return {
      "Model": HBox,
      "Collection": hboxes,
      "View": HBoxView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=hbox.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('widget/vbox',["common/has_parent", "common/continuum_view", "common/build_views", "common/collection"], function(HasParent, ContinuumView, build_views, Collection) {
    var VBox, VBoxView, VBoxes, vboxes, _ref, _ref1, _ref2;
    VBoxView = (function(_super) {
      __extends(VBoxView, _super);

      function VBoxView() {
        _ref = VBoxView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      VBoxView.prototype.tag = "div";

      VBoxView.prototype.attributes = {
        "class": "bk-vbox"
      };

      VBoxView.prototype.initialize = function(options) {
        VBoxView.__super__.initialize.call(this, options);
        this.views = {};
        this.render();
        return this.listenTo(this.model, 'change', this.render);
      };

      VBoxView.prototype.render = function() {
        var child, children, height, key, val, width, _i, _len, _ref1, _results;
        children = this.mget('children');
        build_views(this.views, children);
        _ref1 = this.views;
        for (key in _ref1) {
          if (!__hasProp.call(_ref1, key)) continue;
          val = _ref1[key];
          val.$el.detach();
        }
        this.$el.empty();
        width = this.mget("width");
        if (width != null) {
          this.$el.css({
            width: width + "px"
          });
        }
        height = this.mget("height");
        if (height != null) {
          this.$el.css({
            height: height + "px"
          });
        }
        _results = [];
        for (_i = 0, _len = children.length; _i < _len; _i++) {
          child = children[_i];
          _results.push(this.$el.append(this.views[child.id].$el));
        }
        return _results;
      };

      return VBoxView;

    })(ContinuumView);
    VBox = (function(_super) {
      __extends(VBox, _super);

      function VBox() {
        _ref1 = VBox.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      VBox.prototype.type = "VBox";

      VBox.prototype.default_view = VBoxView;

      VBox.prototype.defaults = function() {
        return _.extend({}, VBox.__super__.defaults.call(this), {
          children: []
        });
      };

      return VBox;

    })(HasParent);
    VBoxes = (function(_super) {
      __extends(VBoxes, _super);

      function VBoxes() {
        _ref2 = VBoxes.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      VBoxes.prototype.model = VBox;

      return VBoxes;

    })(Collection);
    vboxes = new VBoxes();
    return {
      "Model": VBox,
      "Collection": vboxes,
      "View": VBoxView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=vbox.js.map
*/;
define('widget/text_input_template',[],function(){
  var template = function(__obj) {
  var _safe = function(value) {
    if (typeof value === 'undefined' && value == null)
      value = '';
    var result = new String(value);
    result.ecoSafe = true;
    return result;
  };
  return (function() {
    var __out = [], __self = this, _print = function(value) {
      if (typeof value !== 'undefined' && value != null)
        __out.push(value.ecoSafe ? value : __self.escape(value));
    }, _capture = function(callback) {
      var out = __out, result;
      __out = [];
      callback.call(this);
      result = __out.join('');
      __out = out;
      return _safe(result);
    };
    (function() {
      _print(_safe('<label for="'));
    
      _print(this.id);
    
      _print(_safe('"> '));
    
      _print(this.title);
    
      _print(_safe(' </label>\n<input class="bk-widget-form-input" type="text" id="'));
    
      _print(this.id);
    
      _print(_safe('" name="'));
    
      _print(this.name);
    
      _print(_safe('" value="'));
    
      _print(this.value);
    
      _print(_safe('"/>\n'));
    
    }).call(this);
    
    return __out.join('');
  }).call((function() {
    var obj = {
      escape: function(value) {
        return ('' + value)
          .replace(/&/g, '&amp;')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;')
          .replace(/"/g, '&quot;');
      },
      safe: _safe
    }, key;
    for (key in __obj) obj[key] = __obj[key];
    return obj;
  })());
};
  return template;
});

(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('widget/text_input',["common/collection", "common/build_views", "common/continuum_view", "common/has_parent", "common/logging", "./text_input_template"], function(Collection, build_views, ContinuumView, HasParent, Logging, template) {
    var TextInput, TextInputView, TextInputs, logger, _ref, _ref1, _ref2;
    logger = Logging.logger;
    TextInputView = (function(_super) {
      __extends(TextInputView, _super);

      function TextInputView() {
        _ref = TextInputView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      TextInputView.prototype.tagName = "div";

      TextInputView.prototype.attributes = {
        "class": "bk-widget-form-group"
      };

      TextInputView.prototype.template = template;

      TextInputView.prototype.events = {
        "change input": "change_input"
      };

      TextInputView.prototype.change_input = function() {
        var value;
        value = this.$('input').val();
        logger.debug("widget/text_input: value = " + value);
        this.mset('value', value);
        return this.model.save();
      };

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

      TextInputView.prototype.render = function() {
        this.$el.html(this.template(this.model.attributes));
        return this;
      };

      return TextInputView;

    })(ContinuumView);
    TextInput = (function(_super) {
      __extends(TextInput, _super);

      function TextInput() {
        _ref1 = TextInput.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      TextInput.prototype.type = "TextInput";

      TextInput.prototype.default_view = TextInputView;

      TextInput.prototype.defaults = function() {
        return _.extend({}, TextInput.__super__.defaults.call(this), {
          name: "",
          value: "",
          title: ""
        });
      };

      return TextInput;

    })(HasParent);
    TextInputs = (function(_super) {
      __extends(TextInputs, _super);

      function TextInputs() {
        _ref2 = TextInputs.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      TextInputs.prototype.model = TextInput;

      return TextInputs;

    })(Collection);
    return {
      View: TextInputView,
      Model: TextInput,
      Collection: new TextInputs()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=text_input.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('widget/autocomplete_input',["jquery_ui/autocomplete", "common/collection", "./text_input"], function($1, Collection, TextInput) {
    var AutocompleteInput, AutocompleteInputView, AutocompleteInputs, _ref, _ref1, _ref2;
    AutocompleteInputView = (function(_super) {
      __extends(AutocompleteInputView, _super);

      function AutocompleteInputView() {
        _ref = AutocompleteInputView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      AutocompleteInputView.prototype.render = function() {
        var $input;
        AutocompleteInputView.__super__.render.call(this);
        $input = this.$el.find("input");
        $input.autocomplete({
          source: this.mget("completions")
        });
        return $input.autocomplete("widget").addClass("bk-autocomplete-input");
      };

      return AutocompleteInputView;

    })(TextInput.View);
    AutocompleteInput = (function(_super) {
      __extends(AutocompleteInput, _super);

      function AutocompleteInput() {
        _ref1 = AutocompleteInput.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      AutocompleteInput.prototype.type = "AutocompleteInput";

      AutocompleteInput.prototype.default_view = AutocompleteInputView;

      AutocompleteInput.prototype.defaults = function() {
        return _.extend({}, AutocompleteInput.__super__.defaults.call(this), {
          completions: []
        });
      };

      return AutocompleteInput;

    })(TextInput.Model);
    AutocompleteInputs = (function(_super) {
      __extends(AutocompleteInputs, _super);

      function AutocompleteInputs() {
        _ref2 = AutocompleteInputs.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      AutocompleteInputs.prototype.model = AutocompleteInput;

      return AutocompleteInputs;

    })(Collection);
    return {
      View: AutocompleteInputView,
      Model: AutocompleteInput,
      Collection: new AutocompleteInputs()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=autocomplete_input.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('widget/vboxform',["common/has_parent", "common/continuum_view", "common/build_views", "common/collection"], function(HasParent, ContinuumView, build_views, Collection) {
    var VBoxForm, VBoxFormView, VBoxForms, vboxforms, _ref, _ref1, _ref2;
    VBoxFormView = (function(_super) {
      __extends(VBoxFormView, _super);

      function VBoxFormView() {
        _ref = VBoxFormView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      VBoxFormView.prototype.tagName = "form";

      VBoxFormView.prototype.attributes = {
        "class": "bk-widget-form",
        role: "form"
      };

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

      VBoxFormView.prototype.render = function() {
        var child, children, key, val, _i, _len, _ref1, _results;
        children = this.mget('children');
        build_views(this.views, children);
        _ref1 = this.views;
        for (key in _ref1) {
          if (!__hasProp.call(_ref1, key)) continue;
          val = _ref1[key];
          val.$el.detach();
        }
        this.$el.empty();
        _results = [];
        for (_i = 0, _len = children.length; _i < _len; _i++) {
          child = children[_i];
          this.$el.append("<br/");
          _results.push(this.$el.append(this.views[child.id].$el));
        }
        return _results;
      };

      return VBoxFormView;

    })(ContinuumView);
    VBoxForm = (function(_super) {
      __extends(VBoxForm, _super);

      function VBoxForm() {
        _ref1 = VBoxForm.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      VBoxForm.prototype.type = "VBoxForm";

      VBoxForm.prototype.default_view = VBoxFormView;

      VBoxForm.prototype.defaults = function() {
        return _.extend({}, VBoxForm.__super__.defaults.call(this), {
          children: []
        });
      };

      return VBoxForm;

    })(HasParent);
    VBoxForms = (function(_super) {
      __extends(VBoxForms, _super);

      function VBoxForms() {
        _ref2 = VBoxForms.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      VBoxForms.prototype.model = VBoxForm;

      return VBoxForms;

    })(Collection);
    vboxforms = new VBoxForms();
    return {
      "Model": VBoxForm,
      "Collection": vboxforms,
      "View": VBoxFormView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=vboxform.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('widget/pretext',["common/collection", "./paragraph"], function(Collection, Paragraph) {
    var PreText, PreTextView, PreTexts, pretexts, _ref, _ref1, _ref2;
    PreTextView = (function(_super) {
      __extends(PreTextView, _super);

      function PreTextView() {
        _ref = PreTextView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      PreTextView.prototype.tagName = "pre";

      PreTextView.prototype.attributes = {
        style: "overflow:scroll"
      };

      return PreTextView;

    })(Paragraph.View);
    PreText = (function(_super) {
      __extends(PreText, _super);

      function PreText() {
        _ref1 = PreText.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      PreText.prototype.type = "PreText";

      PreText.prototype.default_view = PreTextView;

      PreText.prototype.defaults = function() {
        return _.extend({}, PreText.__super__.defaults.call(this), {
          text: '',
          height: 400,
          width: 400
        });
      };

      return PreText;

    })(Paragraph.Model);
    PreTexts = (function(_super) {
      __extends(PreTexts, _super);

      function PreTexts() {
        _ref2 = PreTexts.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      PreTexts.prototype.model = PreText;

      return PreTexts;

    })(Collection);
    pretexts = new PreTexts();
    return {
      "Model": PreText,
      "Collection": pretexts,
      "View": PreTextView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=pretext.js.map
*/;
define('widget/selecttemplate',[],function(){
  var template = function(__obj) {
  var _safe = function(value) {
    if (typeof value === 'undefined' && value == null)
      value = '';
    var result = new String(value);
    result.ecoSafe = true;
    return result;
  };
  return (function() {
    var __out = [], __self = this, _print = function(value) {
      if (typeof value !== 'undefined' && value != null)
        __out.push(value.ecoSafe ? value : __self.escape(value));
    }, _capture = function(callback) {
      var out = __out, result;
      __out = [];
      callback.call(this);
      result = __out.join('');
      __out = out;
      return _safe(result);
    };
    (function() {
      var option, _i, _len, _ref;
    
      _print(_safe('<label for="'));
    
      _print(this.id);
    
      _print(_safe('"> '));
    
      _print(this.title);
    
      _print(_safe(' </label>\n<select class="bk-widget-form-input" id="'));
    
      _print(this.id);
    
      _print(_safe('" name="'));
    
      _print(this.name);
    
      _print(_safe('">\n  '));
    
      _ref = this.options;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        option = _ref[_i];
        _print(_safe('\n    '));
        if (_.isString(option)) {
          _print(_safe('\n      <option '));
          _print(option === this.value ? _print(_safe('selected="selected"')) : void 0);
          _print(_safe(' value="'));
          _print(option);
          _print(_safe('">'));
          _print(option);
          _print(_safe('</option>\n    '));
        } else {
          _print(_safe('\n      <option '));
          _print(option.value === this.value ? _print(_safe('selected="selected"')) : void 0);
          _print(_safe(' value="'));
          _print(option.value);
          _print(_safe('">'));
          _print(option.name);
          _print(_safe('</option>\n    '));
        }
        _print(_safe('\n  '));
      }
    
      _print(_safe('\n</select>\n'));
    
    }).call(this);
    
    return __out.join('');
  }).call((function() {
    var obj = {
      escape: function(value) {
        return ('' + value)
          .replace(/&/g, '&amp;')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;')
          .replace(/"/g, '&quot;');
      },
      safe: _safe
    }, key;
    for (key in __obj) obj[key] = __obj[key];
    return obj;
  })());
};
  return template;
});

(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('widget/selectbox',["common/collection", "underscore", "common/continuum_view", "common/has_parent", "common/logging", "./selecttemplate"], function(Collection, build_views, ContinuumView, HasParent, Logging, template) {
    var Select, SelectView, Selects, logger, _ref, _ref1, _ref2;
    logger = Logging.logger;
    SelectView = (function(_super) {
      __extends(SelectView, _super);

      function SelectView() {
        _ref = SelectView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      SelectView.prototype.tagName = "div";

      SelectView.prototype.template = template;

      SelectView.prototype.events = {
        "change select": "change_input"
      };

      SelectView.prototype.change_input = function() {
        var value;
        value = this.$('select').val();
        logger.debug("selectbox: value = " + value);
        this.mset('value', value);
        return this.model.save();
      };

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

      SelectView.prototype.render = function() {
        var html;
        this.$el.empty();
        html = this.template(this.model.attributes);
        this.$el.html(html);
        return this;
      };

      return SelectView;

    })(ContinuumView);
    Select = (function(_super) {
      __extends(Select, _super);

      function Select() {
        _ref1 = Select.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Select.prototype.type = "Select";

      Select.prototype.default_view = SelectView;

      Select.prototype.defaults = function() {
        return _.extend({}, Select.__super__.defaults.call(this), {
          title: '',
          value: '',
          options: []
        });
      };

      return Select;

    })(HasParent);
    Selects = (function(_super) {
      __extends(Selects, _super);

      function Selects() {
        _ref2 = Selects.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Selects.prototype.model = Select;

      return Selects;

    })(Collection);
    return {
      Model: Select,
      Collection: new Selects(),
      View: SelectView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=selectbox.js.map
*/;
define('widget/slidertemplate',[],function(){
  var template = function(__obj) {
  var _safe = function(value) {
    if (typeof value === 'undefined' && value == null)
      value = '';
    var result = new String(value);
    result.ecoSafe = true;
    return result;
  };
  return (function() {
    var __out = [], __self = this, _print = function(value) {
      if (typeof value !== 'undefined' && value != null)
        __out.push(value.ecoSafe ? value : __self.escape(value));
    }, _capture = function(callback) {
      var out = __out, result;
      __out = [];
      callback.call(this);
      result = __out.join('');
      __out = out;
      return _safe(result);
    };
    (function() {
      _print(_safe('<label for="'));
    
      _print(this.id);
    
      _print(_safe('"> '));
    
      _print(this.title);
    
      _print(_safe(': </label>\n<input type="text" id="'));
    
      _print(this.id);
    
      _print(_safe('" readonly style="border:0; color:#f6931f; font-weight:bold;">\n<div class="bk-slider-'));
    
      _print(this.orientation);
    
      _print(_safe('">\n  <div class="slider " id="'));
    
      _print(this.id);
    
      _print(_safe('">\n</div>\n'));
    
    }).call(this);
    
    return __out.join('');
  }).call((function() {
    var obj = {
      escape: function(value) {
        return ('' + value)
          .replace(/&/g, '&amp;')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;')
          .replace(/"/g, '&quot;');
      },
      safe: _safe
    }, key;
    for (key in __obj) obj[key] = __obj[key];
    return obj;
  })());
};
  return template;
});

/*!
 * jQuery UI Slider 1.11.2
 * http://jqueryui.com
 *
 * Copyright 2014 jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/slider/
 */
(function( factory ) {
	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define('jquery_ui/slider',[
			"jquery",
			"./core",
			"./mouse",
			"./widget"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
}(function( $ ) {

return $.widget( "ui.slider", $.ui.mouse, {
	version: "1.11.2",
	widgetEventPrefix: "slide",

	options: {
		animate: false,
		distance: 0,
		max: 100,
		min: 0,
		orientation: "horizontal",
		range: false,
		step: 1,
		value: 0,
		values: null,

		// callbacks
		change: null,
		slide: null,
		start: null,
		stop: null
	},

	// number of pages in a slider
	// (how many times can you page up/down to go through the whole range)
	numPages: 5,

	_create: function() {
		this._keySliding = false;
		this._mouseSliding = false;
		this._animateOff = true;
		this._handleIndex = null;
		this._detectOrientation();
		this._mouseInit();
		this._calculateNewMax();

		this.element
			.addClass( "bk-ui-slider" +
				" bk-ui-slider-" + this.orientation +
				" bk-ui-widget" +
				" bk-ui-widget-content" +
				" bk-ui-corner-all");

		this._refresh();
		this._setOption( "disabled", this.options.disabled );

		this._animateOff = false;
	},

	_refresh: function() {
		this._createRange();
		this._createHandles();
		this._setupEvents();
		this._refreshValue();
	},

	_createHandles: function() {
		var i, handleCount,
			options = this.options,
			existingHandles = this.element.find( ".bk-ui-slider-handle" ).addClass( "bk-ui-state-default bk-ui-corner-all" ),
			handle = "<span class='bk-ui-slider-handle bk-ui-state-default bk-ui-corner-all' tabindex='0'></span>",
			handles = [];

		handleCount = ( options.values && options.values.length ) || 1;

		if ( existingHandles.length > handleCount ) {
			existingHandles.slice( handleCount ).remove();
			existingHandles = existingHandles.slice( 0, handleCount );
		}

		for ( i = existingHandles.length; i < handleCount; i++ ) {
			handles.push( handle );
		}

		this.handles = existingHandles.add( $( handles.join( "" ) ).appendTo( this.element ) );

		this.handle = this.handles.eq( 0 );

		this.handles.each(function( i ) {
			$( this ).data( "bk-ui-slider-handle-index", i );
		});
	},

	_createRange: function() {
		var options = this.options,
			classes = "";

		if ( options.range ) {
			if ( options.range === true ) {
				if ( !options.values ) {
					options.values = [ this._valueMin(), this._valueMin() ];
				} else if ( options.values.length && options.values.length !== 2 ) {
					options.values = [ options.values[0], options.values[0] ];
				} else if ( $.isArray( options.values ) ) {
					options.values = options.values.slice(0);
				}
			}

			if ( !this.range || !this.range.length ) {
				this.range = $( "<div></div>" )
					.appendTo( this.element );

				classes = "bk-ui-slider-range" +
				// note: this isn't the most fittingly semantic framework class for this element,
				// but worked best visually with a variety of themes
				" bk-ui-widget-header bk-ui-corner-all";
			} else {
				this.range.removeClass( "bk-ui-slider-range-min bk-ui-slider-range-max" )
					// Handle range switching from true to min/max
					.css({
						"left": "",
						"bottom": ""
					});
			}

			this.range.addClass( classes +
				( ( options.range === "min" || options.range === "max" ) ? " bk-ui-slider-range-" + options.range : "" ) );
		} else {
			if ( this.range ) {
				this.range.remove();
			}
			this.range = null;
		}
	},

	_setupEvents: function() {
		this._off( this.handles );
		this._on( this.handles, this._handleEvents );
		this._hoverable( this.handles );
		this._focusable( this.handles );
	},

	_destroy: function() {
		this.handles.remove();
		if ( this.range ) {
			this.range.remove();
		}

		this.element
			.removeClass( "bk-ui-slider" +
				" bk-ui-slider-horizontal" +
				" bk-ui-slider-vertical" +
				" bk-ui-widget" +
				" bk-ui-widget-content" +
				" bk-ui-corner-all" );

		this._mouseDestroy();
	},

	_mouseCapture: function( event ) {
		var position, normValue, distance, closestHandle, index, allowed, offset, mouseOverHandle,
			that = this,
			o = this.options;

		if ( o.disabled ) {
			return false;
		}

		this.elementSize = {
			width: this.element.outerWidth(),
			height: this.element.outerHeight()
		};
		this.elementOffset = this.element.offset();

		position = { x: event.pageX, y: event.pageY };
		normValue = this._normValueFromMouse( position );
		distance = this._valueMax() - this._valueMin() + 1;
		this.handles.each(function( i ) {
			var thisDistance = Math.abs( normValue - that.values(i) );
			if (( distance > thisDistance ) ||
				( distance === thisDistance &&
					(i === that._lastChangedValue || that.values(i) === o.min ))) {
				distance = thisDistance;
				closestHandle = $( this );
				index = i;
			}
		});

		allowed = this._start( event, index );
		if ( allowed === false ) {
			return false;
		}
		this._mouseSliding = true;

		this._handleIndex = index;

		closestHandle
			.addClass( "bk-ui-state-active" )
			.focus();

		offset = closestHandle.offset();
		mouseOverHandle = !$( event.target ).parents().addBack().is( ".bk-ui-slider-handle" );
		this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : {
			left: event.pageX - offset.left - ( closestHandle.width() / 2 ),
			top: event.pageY - offset.top -
				( closestHandle.height() / 2 ) -
				( parseInt( closestHandle.css("borderTopWidth"), 10 ) || 0 ) -
				( parseInt( closestHandle.css("borderBottomWidth"), 10 ) || 0) +
				( parseInt( closestHandle.css("marginTop"), 10 ) || 0)
		};

		if ( !this.handles.hasClass( "bk-ui-state-hover" ) ) {
			this._slide( event, index, normValue );
		}
		this._animateOff = true;
		return true;
	},

	_mouseStart: function() {
		return true;
	},

	_mouseDrag: function( event ) {
		var position = { x: event.pageX, y: event.pageY },
			normValue = this._normValueFromMouse( position );

		this._slide( event, this._handleIndex, normValue );

		return false;
	},

	_mouseStop: function( event ) {
		this.handles.removeClass( "bk-ui-state-active" );
		this._mouseSliding = false;

		this._stop( event, this._handleIndex );
		this._change( event, this._handleIndex );

		this._handleIndex = null;
		this._clickOffset = null;
		this._animateOff = false;

		return false;
	},

	_detectOrientation: function() {
		this.orientation = ( this.options.orientation === "vertical" ) ? "vertical" : "horizontal";
	},

	_normValueFromMouse: function( position ) {
		var pixelTotal,
			pixelMouse,
			percentMouse,
			valueTotal,
			valueMouse;

		if ( this.orientation === "horizontal" ) {
			pixelTotal = this.elementSize.width;
			pixelMouse = position.x - this.elementOffset.left - ( this._clickOffset ? this._clickOffset.left : 0 );
		} else {
			pixelTotal = this.elementSize.height;
			pixelMouse = position.y - this.elementOffset.top - ( this._clickOffset ? this._clickOffset.top : 0 );
		}

		percentMouse = ( pixelMouse / pixelTotal );
		if ( percentMouse > 1 ) {
			percentMouse = 1;
		}
		if ( percentMouse < 0 ) {
			percentMouse = 0;
		}
		if ( this.orientation === "vertical" ) {
			percentMouse = 1 - percentMouse;
		}

		valueTotal = this._valueMax() - this._valueMin();
		valueMouse = this._valueMin() + percentMouse * valueTotal;

		return this._trimAlignValue( valueMouse );
	},

	_start: function( event, index ) {
		var uiHash = {
			handle: this.handles[ index ],
			value: this.value()
		};
		if ( this.options.values && this.options.values.length ) {
			uiHash.value = this.values( index );
			uiHash.values = this.values();
		}
		return this._trigger( "start", event, uiHash );
	},

	_slide: function( event, index, newVal ) {
		var otherVal,
			newValues,
			allowed;

		if ( this.options.values && this.options.values.length ) {
			otherVal = this.values( index ? 0 : 1 );

			if ( ( this.options.values.length === 2 && this.options.range === true ) &&
					( ( index === 0 && newVal > otherVal) || ( index === 1 && newVal < otherVal ) )
				) {
				newVal = otherVal;
			}

			if ( newVal !== this.values( index ) ) {
				newValues = this.values();
				newValues[ index ] = newVal;
				// A slide can be canceled by returning false from the slide callback
				allowed = this._trigger( "slide", event, {
					handle: this.handles[ index ],
					value: newVal,
					values: newValues
				} );
				otherVal = this.values( index ? 0 : 1 );
				if ( allowed !== false ) {
					this.values( index, newVal );
				}
			}
		} else {
			if ( newVal !== this.value() ) {
				// A slide can be canceled by returning false from the slide callback
				allowed = this._trigger( "slide", event, {
					handle: this.handles[ index ],
					value: newVal
				} );
				if ( allowed !== false ) {
					this.value( newVal );
				}
			}
		}
	},

	_stop: function( event, index ) {
		var uiHash = {
			handle: this.handles[ index ],
			value: this.value()
		};
		if ( this.options.values && this.options.values.length ) {
			uiHash.value = this.values( index );
			uiHash.values = this.values();
		}

		this._trigger( "stop", event, uiHash );
	},

	_change: function( event, index ) {
		if ( !this._keySliding && !this._mouseSliding ) {
			var uiHash = {
				handle: this.handles[ index ],
				value: this.value()
			};
			if ( this.options.values && this.options.values.length ) {
				uiHash.value = this.values( index );
				uiHash.values = this.values();
			}

			//store the last changed value index for reference when handles overlap
			this._lastChangedValue = index;

			this._trigger( "change", event, uiHash );
		}
	},

	value: function( newValue ) {
		if ( arguments.length ) {
			this.options.value = this._trimAlignValue( newValue );
			this._refreshValue();
			this._change( null, 0 );
			return;
		}

		return this._value();
	},

	values: function( index, newValue ) {
		var vals,
			newValues,
			i;

		if ( arguments.length > 1 ) {
			this.options.values[ index ] = this._trimAlignValue( newValue );
			this._refreshValue();
			this._change( null, index );
			return;
		}

		if ( arguments.length ) {
			if ( $.isArray( arguments[ 0 ] ) ) {
				vals = this.options.values;
				newValues = arguments[ 0 ];
				for ( i = 0; i < vals.length; i += 1 ) {
					vals[ i ] = this._trimAlignValue( newValues[ i ] );
					this._change( null, i );
				}
				this._refreshValue();
			} else {
				if ( this.options.values && this.options.values.length ) {
					return this._values( index );
				} else {
					return this.value();
				}
			}
		} else {
			return this._values();
		}
	},

	_setOption: function( key, value ) {
		var i,
			valsLength = 0;

		if ( key === "range" && this.options.range === true ) {
			if ( value === "min" ) {
				this.options.value = this._values( 0 );
				this.options.values = null;
			} else if ( value === "max" ) {
				this.options.value = this._values( this.options.values.length - 1 );
				this.options.values = null;
			}
		}

		if ( $.isArray( this.options.values ) ) {
			valsLength = this.options.values.length;
		}

		if ( key === "disabled" ) {
			this.element.toggleClass( "bk-ui-state-disabled", !!value );
		}

		this._super( key, value );

		switch ( key ) {
			case "orientation":
				this._detectOrientation();
				this.element
					.removeClass( "bk-ui-slider-horizontal bk-ui-slider-vertical" )
					.addClass( "bk-ui-slider-" + this.orientation );
				this._refreshValue();

				// Reset positioning from previous orientation
				this.handles.css( value === "horizontal" ? "bottom" : "left", "" );
				break;
			case "value":
				this._animateOff = true;
				this._refreshValue();
				this._change( null, 0 );
				this._animateOff = false;
				break;
			case "values":
				this._animateOff = true;
				this._refreshValue();
				for ( i = 0; i < valsLength; i += 1 ) {
					this._change( null, i );
				}
				this._animateOff = false;
				break;
			case "step":
			case "min":
			case "max":
				this._animateOff = true;
				this._calculateNewMax();
				this._refreshValue();
				this._animateOff = false;
				break;
			case "range":
				this._animateOff = true;
				this._refresh();
				this._animateOff = false;
				break;
		}
	},

	//internal value getter
	// _value() returns value trimmed by min and max, aligned by step
	_value: function() {
		var val = this.options.value;
		val = this._trimAlignValue( val );

		return val;
	},

	//internal values getter
	// _values() returns array of values trimmed by min and max, aligned by step
	// _values( index ) returns single value trimmed by min and max, aligned by step
	_values: function( index ) {
		var val,
			vals,
			i;

		if ( arguments.length ) {
			val = this.options.values[ index ];
			val = this._trimAlignValue( val );

			return val;
		} else if ( this.options.values && this.options.values.length ) {
			// .slice() creates a copy of the array
			// this copy gets trimmed by min and max and then returned
			vals = this.options.values.slice();
			for ( i = 0; i < vals.length; i += 1) {
				vals[ i ] = this._trimAlignValue( vals[ i ] );
			}

			return vals;
		} else {
			return [];
		}
	},

	// returns the step-aligned value that val is closest to, between (inclusive) min and max
	_trimAlignValue: function( val ) {
		if ( val <= this._valueMin() ) {
			return this._valueMin();
		}
		if ( val >= this._valueMax() ) {
			return this._valueMax();
		}
		var step = ( this.options.step > 0 ) ? this.options.step : 1,
			valModStep = (val - this._valueMin()) % step,
			alignValue = val - valModStep;

		if ( Math.abs(valModStep) * 2 >= step ) {
			alignValue += ( valModStep > 0 ) ? step : ( -step );
		}

		// Since JavaScript has problems with large floats, round
		// the final value to 5 digits after the decimal point (see #4124)
		return parseFloat( alignValue.toFixed(5) );
	},

	_calculateNewMax: function() {
		var remainder = ( this.options.max - this._valueMin() ) % this.options.step;
		this.max = this.options.max - remainder;
	},

	_valueMin: function() {
		return this.options.min;
	},

	_valueMax: function() {
		return this.max;
	},

	_refreshValue: function() {
		var lastValPercent, valPercent, value, valueMin, valueMax,
			oRange = this.options.range,
			o = this.options,
			that = this,
			animate = ( !this._animateOff ) ? o.animate : false,
			_set = {};

		if ( this.options.values && this.options.values.length ) {
			this.handles.each(function( i ) {
				valPercent = ( that.values(i) - that._valueMin() ) / ( that._valueMax() - that._valueMin() ) * 100;
				_set[ that.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
				$( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );
				if ( that.options.range === true ) {
					if ( that.orientation === "horizontal" ) {
						if ( i === 0 ) {
							that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { left: valPercent + "%" }, o.animate );
						}
						if ( i === 1 ) {
							that.range[ animate ? "animate" : "css" ]( { width: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } );
						}
					} else {
						if ( i === 0 ) {
							that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { bottom: ( valPercent ) + "%" }, o.animate );
						}
						if ( i === 1 ) {
							that.range[ animate ? "animate" : "css" ]( { height: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } );
						}
					}
				}
				lastValPercent = valPercent;
			});
		} else {
			value = this.value();
			valueMin = this._valueMin();
			valueMax = this._valueMax();
			valPercent = ( valueMax !== valueMin ) ?
					( value - valueMin ) / ( valueMax - valueMin ) * 100 :
					0;
			_set[ this.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
			this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );

			if ( oRange === "min" && this.orientation === "horizontal" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { width: valPercent + "%" }, o.animate );
			}
			if ( oRange === "max" && this.orientation === "horizontal" ) {
				this.range[ animate ? "animate" : "css" ]( { width: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } );
			}
			if ( oRange === "min" && this.orientation === "vertical" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { height: valPercent + "%" }, o.animate );
			}
			if ( oRange === "max" && this.orientation === "vertical" ) {
				this.range[ animate ? "animate" : "css" ]( { height: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } );
			}
		}
	},

	_handleEvents: {
		keydown: function( event ) {
			var allowed, curVal, newVal, step,
				index = $( event.target ).data( "bk-ui-slider-handle-index" );

			switch ( event.keyCode ) {
				case $.ui.keyCode.HOME:
				case $.ui.keyCode.END:
				case $.ui.keyCode.PAGE_UP:
				case $.ui.keyCode.PAGE_DOWN:
				case $.ui.keyCode.UP:
				case $.ui.keyCode.RIGHT:
				case $.ui.keyCode.DOWN:
				case $.ui.keyCode.LEFT:
					event.preventDefault();
					if ( !this._keySliding ) {
						this._keySliding = true;
						$( event.target ).addClass( "bk-ui-state-active" );
						allowed = this._start( event, index );
						if ( allowed === false ) {
							return;
						}
					}
					break;
			}

			step = this.options.step;
			if ( this.options.values && this.options.values.length ) {
				curVal = newVal = this.values( index );
			} else {
				curVal = newVal = this.value();
			}

			switch ( event.keyCode ) {
				case $.ui.keyCode.HOME:
					newVal = this._valueMin();
					break;
				case $.ui.keyCode.END:
					newVal = this._valueMax();
					break;
				case $.ui.keyCode.PAGE_UP:
					newVal = this._trimAlignValue(
						curVal + ( ( this._valueMax() - this._valueMin() ) / this.numPages )
					);
					break;
				case $.ui.keyCode.PAGE_DOWN:
					newVal = this._trimAlignValue(
						curVal - ( (this._valueMax() - this._valueMin()) / this.numPages ) );
					break;
				case $.ui.keyCode.UP:
				case $.ui.keyCode.RIGHT:
					if ( curVal === this._valueMax() ) {
						return;
					}
					newVal = this._trimAlignValue( curVal + step );
					break;
				case $.ui.keyCode.DOWN:
				case $.ui.keyCode.LEFT:
					if ( curVal === this._valueMin() ) {
						return;
					}
					newVal = this._trimAlignValue( curVal - step );
					break;
			}

			this._slide( event, index, newVal );
		},
		keyup: function( event ) {
			var index = $( event.target ).data( "bk-ui-slider-handle-index" );

			if ( this._keySliding ) {
				this._keySliding = false;
				this._stop( event, index );
				this._change( event, index );
				$( event.target ).removeClass( "bk-ui-state-active" );
			}
		}
	}
});

}));

(function() {
  var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('widget/slider',["common/collection", "underscore", "common/continuum_view", "common/has_parent", "common/logging", "./slidertemplate", "jquery_ui/slider"], function(Collection, _, ContinuumView, HasParent, Logging, slidertemplate) {
    var Slider, SliderView, Sliders, logger, _ref, _ref1, _ref2;
    logger = Logging.logger;
    SliderView = (function(_super) {
      __extends(SliderView, _super);

      function SliderView() {
        this.slide = __bind(this.slide, this);
        _ref = SliderView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      SliderView.prototype.tagName = "div";

      SliderView.prototype.template = slidertemplate;

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

      SliderView.prototype.render = function() {
        var html, max, min, step;
        this.$el.empty();
        html = this.template(this.model.attributes);
        this.$el.html(html);
        max = this.mget('end');
        min = this.mget('start');
        step = this.mget('step') || ((max - min) / 50);
        logger.debug("slider render: min, max, step = (" + min + ", " + max + ", " + step + ")");
        this.$('.slider').slider({
          orientation: this.mget('orientation'),
          animate: "fast",
          slide: _.throttle(this.slide, 200),
          value: this.mget('value'),
          min: min,
          max: max,
          step: step
        });
        return this.$("#" + (this.mget('id'))).val(this.$('.slider').slider('value'));
      };

      SliderView.prototype.slide = function(event, ui) {
        var value;
        value = ui.value;
        logger.debug("slide value = " + value);
        this.$("#" + (this.mget('id'))).val(ui.value);
        this.mset('value', value);
        return this.model.save();
      };

      return SliderView;

    })(ContinuumView);
    Slider = (function(_super) {
      __extends(Slider, _super);

      function Slider() {
        _ref1 = Slider.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Slider.prototype.type = "Slider";

      Slider.prototype.default_view = SliderView;

      Slider.prototype.defaults = function() {
        return _.extend({}, Slider.__super__.defaults.call(this), {
          title: '',
          value: 0.5,
          start: 0,
          end: 1,
          step: 0,
          orientation: "horizontal"
        });
      };

      return Slider;

    })(HasParent);
    Sliders = (function(_super) {
      __extends(Sliders, _super);

      function Sliders() {
        _ref2 = Sliders.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Sliders.prototype.model = Slider;

      return Sliders;

    })(Collection);
    return {
      Model: Slider,
      Collection: new Sliders(),
      View: SliderView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=slider.js.map
*/;
/*!
 * jQuery UI Draggable 1.11.2
 * http://jqueryui.com
 *
 * Copyright 2014 jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/draggable/
 */
(function( factory ) {
	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define('jquery_ui/draggable',[
			"jquery",
			"./core",
			"./mouse",
			"./widget"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
}(function( $ ) {

$.widget("ui.draggable", $.ui.mouse, {
	version: "1.11.2",
	widgetEventPrefix: "drag",
	options: {
		addClasses: true,
		appendTo: "parent",
		axis: false,
		connectToSortable: false,
		containment: false,
		cursor: "auto",
		cursorAt: false,
		grid: false,
		handle: false,
		helper: "original",
		iframeFix: false,
		opacity: false,
		refreshPositions: false,
		revert: false,
		revertDuration: 500,
		scope: "default",
		scroll: true,
		scrollSensitivity: 20,
		scrollSpeed: 20,
		snap: false,
		snapMode: "both",
		snapTolerance: 20,
		stack: false,
		zIndex: false,

		// callbacks
		drag: null,
		start: null,
		stop: null
	},
	_create: function() {

		if ( this.options.helper === "original" ) {
			this._setPositionRelative();
		}
		if (this.options.addClasses){
			this.element.addClass("bk-ui-draggable");
		}
		if (this.options.disabled){
			this.element.addClass("bk-ui-draggable-disabled");
		}
		this._setHandleClassName();

		this._mouseInit();
	},

	_setOption: function( key, value ) {
		this._super( key, value );
		if ( key === "handle" ) {
			this._removeHandleClassName();
			this._setHandleClassName();
		}
	},

	_destroy: function() {
		if ( ( this.helper || this.element ).is( ".bk-ui-draggable-dragging" ) ) {
			this.destroyOnClear = true;
			return;
		}
		this.element.removeClass( "bk-ui-draggable bk-ui-draggable-dragging bk-ui-draggable-disabled" );
		this._removeHandleClassName();
		this._mouseDestroy();
	},

	_mouseCapture: function(event) {
		var o = this.options;

		this._blurActiveElement( event );

		// among others, prevent a drag on a resizable-handle
		if (this.helper || o.disabled || $(event.target).closest(".bk-ui-resizable-handle").length > 0) {
			return false;
		}

		//Quit if we're not on a valid handle
		this.handle = this._getHandle(event);
		if (!this.handle) {
			return false;
		}

		this._blockFrames( o.iframeFix === true ? "iframe" : o.iframeFix );

		return true;

	},

	_blockFrames: function( selector ) {
		this.iframeBlocks = this.document.find( selector ).map(function() {
			var iframe = $( this );

			return $( "<div>" )
				.css( "position", "absolute" )
				.appendTo( iframe.parent() )
				.outerWidth( iframe.outerWidth() )
				.outerHeight( iframe.outerHeight() )
				.offset( iframe.offset() )[ 0 ];
		});
	},

	_unblockFrames: function() {
		if ( this.iframeBlocks ) {
			this.iframeBlocks.remove();
			delete this.iframeBlocks;
		}
	},

	_blurActiveElement: function( event ) {
		var document = this.document[ 0 ];

		// Only need to blur if the event occurred on the draggable itself, see #10527
		if ( !this.handleElement.is( event.target ) ) {
			return;
		}

		// support: IE9
		// IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe>
		try {

			// Support: IE9, IE10
			// If the <body> is blurred, IE will switch windows, see #9520
			if ( document.activeElement && document.activeElement.nodeName.toLowerCase() !== "body" ) {

				// Blur any element that currently has focus, see #4261
				$( document.activeElement ).blur();
			}
		} catch ( error ) {}
	},

	_mouseStart: function(event) {

		var o = this.options;

		//Create and append the visible helper
		this.helper = this._createHelper(event);

		this.helper.addClass("bk-ui-draggable-dragging");

		//Cache the helper size
		this._cacheHelperProportions();

		//If ddmanager is used for droppables, set the global draggable
		if ($.ui.ddmanager) {
			$.ui.ddmanager.current = this;
		}

		/*
		 * - Position generation -
		 * This block generates everything position related - it's the core of draggables.
		 */

		//Cache the margins of the original element
		this._cacheMargins();

		//Store the helper's css position
		this.cssPosition = this.helper.css( "position" );
		this.scrollParent = this.helper.scrollParent( true );
		this.offsetParent = this.helper.offsetParent();
		this.hasFixedAncestor = this.helper.parents().filter(function() {
				return $( this ).css( "position" ) === "fixed";
			}).length > 0;

		//The element's absolute position on the page minus margins
		this.positionAbs = this.element.offset();
		this._refreshOffsets( event );

		//Generate the original position
		this.originalPosition = this.position = this._generatePosition( event, false );
		this.originalPageX = event.pageX;
		this.originalPageY = event.pageY;

		//Adjust the mouse offset relative to the helper if "cursorAt" is supplied
		(o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));

		//Set a containment if given in the options
		this._setContainment();

		//Trigger event + callbacks
		if (this._trigger("start", event) === false) {
			this._clear();
			return false;
		}

		//Recache the helper size
		this._cacheHelperProportions();

		//Prepare the droppable offsets
		if ($.ui.ddmanager && !o.dropBehaviour) {
			$.ui.ddmanager.prepareOffsets(this, event);
		}

		// Reset helper's right/bottom css if they're set and set explicit width/height instead
		// as this prevents resizing of elements with right/bottom set (see #7772)
		this._normalizeRightBottom();

		this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position

		//If the ddmanager is used for droppables, inform the manager that dragging has started (see #5003)
		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.dragStart(this, event);
		}

		return true;
	},

	_refreshOffsets: function( event ) {
		this.offset = {
			top: this.positionAbs.top - this.margins.top,
			left: this.positionAbs.left - this.margins.left,
			scroll: false,
			parent: this._getParentOffset(),
			relative: this._getRelativeOffset()
		};

		this.offset.click = {
			left: event.pageX - this.offset.left,
			top: event.pageY - this.offset.top
		};
	},

	_mouseDrag: function(event, noPropagation) {
		// reset any necessary cached properties (see #5009)
		if ( this.hasFixedAncestor ) {
			this.offset.parent = this._getParentOffset();
		}

		//Compute the helpers position
		this.position = this._generatePosition( event, true );
		this.positionAbs = this._convertPositionTo("absolute");

		//Call plugins and callbacks and use the resulting position if something is returned
		if (!noPropagation) {
			var ui = this._uiHash();
			if (this._trigger("drag", event, ui) === false) {
				this._mouseUp({});
				return false;
			}
			this.position = ui.position;
		}

		this.helper[ 0 ].style.left = this.position.left + "px";
		this.helper[ 0 ].style.top = this.position.top + "px";

		if ($.ui.ddmanager) {
			$.ui.ddmanager.drag(this, event);
		}

		return false;
	},

	_mouseStop: function(event) {

		//If we are using droppables, inform the manager about the drop
		var that = this,
			dropped = false;
		if ($.ui.ddmanager && !this.options.dropBehaviour) {
			dropped = $.ui.ddmanager.drop(this, event);
		}

		//if a drop comes from outside (a sortable)
		if (this.dropped) {
			dropped = this.dropped;
			this.dropped = false;
		}

		if ((this.options.revert === "invalid" && !dropped) || (this.options.revert === "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) {
			$(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() {
				if (that._trigger("stop", event) !== false) {
					that._clear();
				}
			});
		} else {
			if (this._trigger("stop", event) !== false) {
				this._clear();
			}
		}

		return false;
	},

	_mouseUp: function( event ) {
		this._unblockFrames();

		//If the ddmanager is used for droppables, inform the manager that dragging has stopped (see #5003)
		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.dragStop(this, event);
		}

		// Only need to focus if the event occurred on the draggable itself, see #10527
		if ( this.handleElement.is( event.target ) ) {
			// The interaction is over; whether or not the click resulted in a drag, focus the element
			this.element.focus();
		}

		return $.ui.mouse.prototype._mouseUp.call(this, event);
	},

	cancel: function() {

		if (this.helper.is(".bk-ui-draggable-dragging")) {
			this._mouseUp({});
		} else {
			this._clear();
		}

		return this;

	},

	_getHandle: function(event) {
		return this.options.handle ?
			!!$( event.target ).closest( this.element.find( this.options.handle ) ).length :
			true;
	},

	_setHandleClassName: function() {
		this.handleElement = this.options.handle ?
			this.element.find( this.options.handle ) : this.element;
		this.handleElement.addClass( "bk-ui-draggable-handle" );
	},

	_removeHandleClassName: function() {
		this.handleElement.removeClass( "bk-ui-draggable-handle" );
	},

	_createHelper: function(event) {

		var o = this.options,
			helperIsFunction = $.isFunction( o.helper ),
			helper = helperIsFunction ?
				$( o.helper.apply( this.element[ 0 ], [ event ] ) ) :
				( o.helper === "clone" ?
					this.element.clone().removeAttr( "id" ) :
					this.element );

		if (!helper.parents("body").length) {
			helper.appendTo((o.appendTo === "parent" ? this.element[0].parentNode : o.appendTo));
		}

		// http://bugs.jqueryui.com/ticket/9446
		// a helper function can return the original element
		// which wouldn't have been set to relative in _create
		if ( helperIsFunction && helper[ 0 ] === this.element[ 0 ] ) {
			this._setPositionRelative();
		}

		if (helper[0] !== this.element[0] && !(/(fixed|absolute)/).test(helper.css("position"))) {
			helper.css("position", "absolute");
		}

		return helper;

	},

	_setPositionRelative: function() {
		if ( !( /^(?:r|a|f)/ ).test( this.element.css( "position" ) ) ) {
			this.element[ 0 ].style.position = "relative";
		}
	},

	_adjustOffsetFromHelper: function(obj) {
		if (typeof obj === "string") {
			obj = obj.split(" ");
		}
		if ($.isArray(obj)) {
			obj = { left: +obj[0], top: +obj[1] || 0 };
		}
		if ("left" in obj) {
			this.offset.click.left = obj.left + this.margins.left;
		}
		if ("right" in obj) {
			this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
		}
		if ("top" in obj) {
			this.offset.click.top = obj.top + this.margins.top;
		}
		if ("bottom" in obj) {
			this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
		}
	},

	_isRootNode: function( element ) {
		return ( /(html|body)/i ).test( element.tagName ) || element === this.document[ 0 ];
	},

	_getParentOffset: function() {

		//Get the offsetParent and cache its position
		var po = this.offsetParent.offset(),
			document = this.document[ 0 ];

		// This is a special case where we need to modify a offset calculated on start, since the following happened:
		// 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
		// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
		//    the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
		if (this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) {
			po.left += this.scrollParent.scrollLeft();
			po.top += this.scrollParent.scrollTop();
		}

		if ( this._isRootNode( this.offsetParent[ 0 ] ) ) {
			po = { top: 0, left: 0 };
		}

		return {
			top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"), 10) || 0),
			left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"), 10) || 0)
		};

	},

	_getRelativeOffset: function() {
		if ( this.cssPosition !== "relative" ) {
			return { top: 0, left: 0 };
		}

		var p = this.element.position(),
			scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] );

		return {
			top: p.top - ( parseInt(this.helper.css( "top" ), 10) || 0 ) + ( !scrollIsRootNode ? this.scrollParent.scrollTop() : 0 ),
			left: p.left - ( parseInt(this.helper.css( "left" ), 10) || 0 ) + ( !scrollIsRootNode ? this.scrollParent.scrollLeft() : 0 )
		};

	},

	_cacheMargins: function() {
		this.margins = {
			left: (parseInt(this.element.css("marginLeft"), 10) || 0),
			top: (parseInt(this.element.css("marginTop"), 10) || 0),
			right: (parseInt(this.element.css("marginRight"), 10) || 0),
			bottom: (parseInt(this.element.css("marginBottom"), 10) || 0)
		};
	},

	_cacheHelperProportions: function() {
		this.helperProportions = {
			width: this.helper.outerWidth(),
			height: this.helper.outerHeight()
		};
	},

	_setContainment: function() {

		var isUserScrollable, c, ce,
			o = this.options,
			document = this.document[ 0 ];

		this.relativeContainer = null;

		if ( !o.containment ) {
			this.containment = null;
			return;
		}

		if ( o.containment === "window" ) {
			this.containment = [
				$( window ).scrollLeft() - this.offset.relative.left - this.offset.parent.left,
				$( window ).scrollTop() - this.offset.relative.top - this.offset.parent.top,
				$( window ).scrollLeft() + $( window ).width() - this.helperProportions.width - this.margins.left,
				$( window ).scrollTop() + ( $( window ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top
			];
			return;
		}

		if ( o.containment === "document") {
			this.containment = [
				0,
				0,
				$( document ).width() - this.helperProportions.width - this.margins.left,
				( $( document ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top
			];
			return;
		}

		if ( o.containment.constructor === Array ) {
			this.containment = o.containment;
			return;
		}

		if ( o.containment === "parent" ) {
			o.containment = this.helper[ 0 ].parentNode;
		}

		c = $( o.containment );
		ce = c[ 0 ];

		if ( !ce ) {
			return;
		}

		isUserScrollable = /(scroll|auto)/.test( c.css( "overflow" ) );

		this.containment = [
			( parseInt( c.css( "borderLeftWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingLeft" ), 10 ) || 0 ),
			( parseInt( c.css( "borderTopWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingTop" ), 10 ) || 0 ),
			( isUserScrollable ? Math.max( ce.scrollWidth, ce.offsetWidth ) : ce.offsetWidth ) -
				( parseInt( c.css( "borderRightWidth" ), 10 ) || 0 ) -
				( parseInt( c.css( "paddingRight" ), 10 ) || 0 ) -
				this.helperProportions.width -
				this.margins.left -
				this.margins.right,
			( isUserScrollable ? Math.max( ce.scrollHeight, ce.offsetHeight ) : ce.offsetHeight ) -
				( parseInt( c.css( "borderBottomWidth" ), 10 ) || 0 ) -
				( parseInt( c.css( "paddingBottom" ), 10 ) || 0 ) -
				this.helperProportions.height -
				this.margins.top -
				this.margins.bottom
		];
		this.relativeContainer = c;
	},

	_convertPositionTo: function(d, pos) {

		if (!pos) {
			pos = this.position;
		}

		var mod = d === "absolute" ? 1 : -1,
			scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] );

		return {
			top: (
				pos.top	+																// The absolute mouse position
				this.offset.relative.top * mod +										// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.top * mod -										// The offsetParent's offset without borders (offset + border)
				( ( this.cssPosition === "fixed" ? -this.offset.scroll.top : ( scrollIsRootNode ? 0 : this.offset.scroll.top ) ) * mod)
			),
			left: (
				pos.left +																// The absolute mouse position
				this.offset.relative.left * mod +										// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.left * mod	-										// The offsetParent's offset without borders (offset + border)
				( ( this.cssPosition === "fixed" ? -this.offset.scroll.left : ( scrollIsRootNode ? 0 : this.offset.scroll.left ) ) * mod)
			)
		};

	},

	_generatePosition: function( event, constrainPosition ) {

		var containment, co, top, left,
			o = this.options,
			scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ),
			pageX = event.pageX,
			pageY = event.pageY;

		// Cache the scroll
		if ( !scrollIsRootNode || !this.offset.scroll ) {
			this.offset.scroll = {
				top: this.scrollParent.scrollTop(),
				left: this.scrollParent.scrollLeft()
			};
		}

		/*
		 * - Position constraining -
		 * Constrain the position to a mix of grid, containment.
		 */

		// If we are not dragging yet, we won't check for options
		if ( constrainPosition ) {
			if ( this.containment ) {
				if ( this.relativeContainer ){
					co = this.relativeContainer.offset();
					containment = [
						this.containment[ 0 ] + co.left,
						this.containment[ 1 ] + co.top,
						this.containment[ 2 ] + co.left,
						this.containment[ 3 ] + co.top
					];
				} else {
					containment = this.containment;
				}

				if (event.pageX - this.offset.click.left < containment[0]) {
					pageX = containment[0] + this.offset.click.left;
				}
				if (event.pageY - this.offset.click.top < containment[1]) {
					pageY = containment[1] + this.offset.click.top;
				}
				if (event.pageX - this.offset.click.left > containment[2]) {
					pageX = containment[2] + this.offset.click.left;
				}
				if (event.pageY - this.offset.click.top > containment[3]) {
					pageY = containment[3] + this.offset.click.top;
				}
			}

			if (o.grid) {
				//Check for grid elements set to 0 to prevent divide by 0 error causing invalid argument errors in IE (see ticket #6950)
				top = o.grid[1] ? this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1] : this.originalPageY;
				pageY = containment ? ((top - this.offset.click.top >= containment[1] || top - this.offset.click.top > containment[3]) ? top : ((top - this.offset.click.top >= containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;

				left = o.grid[0] ? this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0] : this.originalPageX;
				pageX = containment ? ((left - this.offset.click.left >= containment[0] || left - this.offset.click.left > containment[2]) ? left : ((left - this.offset.click.left >= containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
			}

			if ( o.axis === "y" ) {
				pageX = this.originalPageX;
			}

			if ( o.axis === "x" ) {
				pageY = this.originalPageY;
			}
		}

		return {
			top: (
				pageY -																	// The absolute mouse position
				this.offset.click.top	-												// Click offset (relative to the element)
				this.offset.relative.top -												// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.top +												// The offsetParent's offset without borders (offset + border)
				( this.cssPosition === "fixed" ? -this.offset.scroll.top : ( scrollIsRootNode ? 0 : this.offset.scroll.top ) )
			),
			left: (
				pageX -																	// The absolute mouse position
				this.offset.click.left -												// Click offset (relative to the element)
				this.offset.relative.left -												// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.left +												// The offsetParent's offset without borders (offset + border)
				( this.cssPosition === "fixed" ? -this.offset.scroll.left : ( scrollIsRootNode ? 0 : this.offset.scroll.left ) )
			)
		};

	},

	_clear: function() {
		this.helper.removeClass("bk-ui-draggable-dragging");
		if (this.helper[0] !== this.element[0] && !this.cancelHelperRemoval) {
			this.helper.remove();
		}
		this.helper = null;
		this.cancelHelperRemoval = false;
		if ( this.destroyOnClear ) {
			this.destroy();
		}
	},

	_normalizeRightBottom: function() {
		if ( this.options.axis !== "y" && this.helper.css( "right" ) !== "auto" ) {
			this.helper.width( this.helper.width() );
			this.helper.css( "right", "auto" );
		}
		if ( this.options.axis !== "x" && this.helper.css( "bottom" ) !== "auto" ) {
			this.helper.height( this.helper.height() );
			this.helper.css( "bottom", "auto" );
		}
	},

	// From now on bulk stuff - mainly helpers

	_trigger: function( type, event, ui ) {
		ui = ui || this._uiHash();
		$.ui.plugin.call( this, type, [ event, ui, this ], true );

		// Absolute position and offset (see #6884 ) have to be recalculated after plugins
		if ( /^(drag|start|stop)/.test( type ) ) {
			this.positionAbs = this._convertPositionTo( "absolute" );
			ui.offset = this.positionAbs;
		}
		return $.Widget.prototype._trigger.call( this, type, event, ui );
	},

	plugins: {},

	_uiHash: function() {
		return {
			helper: this.helper,
			position: this.position,
			originalPosition: this.originalPosition,
			offset: this.positionAbs
		};
	}

});

$.ui.plugin.add( "draggable", "connectToSortable", {
	start: function( event, ui, draggable ) {
		var uiSortable = $.extend( {}, ui, {
			item: draggable.element
		});

		draggable.sortables = [];
		$( draggable.options.connectToSortable ).each(function() {
			var sortable = $( this ).sortable( "instance" );

			if ( sortable && !sortable.options.disabled ) {
				draggable.sortables.push( sortable );

				// refreshPositions is called at drag start to refresh the containerCache
				// which is used in drag. This ensures it's initialized and synchronized
				// with any changes that might have happened on the page since initialization.
				sortable.refreshPositions();
				sortable._trigger("activate", event, uiSortable);
			}
		});
	},
	stop: function( event, ui, draggable ) {
		var uiSortable = $.extend( {}, ui, {
			item: draggable.element
		});

		draggable.cancelHelperRemoval = false;

		$.each( draggable.sortables, function() {
			var sortable = this;

			if ( sortable.isOver ) {
				sortable.isOver = 0;

				// Allow this sortable to handle removing the helper
				draggable.cancelHelperRemoval = true;
				sortable.cancelHelperRemoval = false;

				// Use _storedCSS To restore properties in the sortable,
				// as this also handles revert (#9675) since the draggable
				// may have modified them in unexpected ways (#8809)
				sortable._storedCSS = {
					position: sortable.placeholder.css( "position" ),
					top: sortable.placeholder.css( "top" ),
					left: sortable.placeholder.css( "left" )
				};

				sortable._mouseStop(event);

				// Once drag has ended, the sortable should return to using
				// its original helper, not the shared helper from draggable
				sortable.options.helper = sortable.options._helper;
			} else {
				// Prevent this Sortable from removing the helper.
				// However, don't set the draggable to remove the helper
				// either as another connected Sortable may yet handle the removal.
				sortable.cancelHelperRemoval = true;

				sortable._trigger( "deactivate", event, uiSortable );
			}
		});
	},
	drag: function( event, ui, draggable ) {
		$.each( draggable.sortables, function() {
			var innermostIntersecting = false,
				sortable = this;

			// Copy over variables that sortable's _intersectsWith uses
			sortable.positionAbs = draggable.positionAbs;
			sortable.helperProportions = draggable.helperProportions;
			sortable.offset.click = draggable.offset.click;

			if ( sortable._intersectsWith( sortable.containerCache ) ) {
				innermostIntersecting = true;

				$.each( draggable.sortables, function() {
					// Copy over variables that sortable's _intersectsWith uses
					this.positionAbs = draggable.positionAbs;
					this.helperProportions = draggable.helperProportions;
					this.offset.click = draggable.offset.click;

					if ( this !== sortable &&
							this._intersectsWith( this.containerCache ) &&
							$.contains( sortable.element[ 0 ], this.element[ 0 ] ) ) {
						innermostIntersecting = false;
					}

					return innermostIntersecting;
				});
			}

			if ( innermostIntersecting ) {
				// If it intersects, we use a little isOver variable and set it once,
				// so that the move-in stuff gets fired only once.
				if ( !sortable.isOver ) {
					sortable.isOver = 1;

					sortable.currentItem = ui.helper
						.appendTo( sortable.element )
						.data( "bk-ui-sortable-item", true );

					// Store helper option to later restore it
					sortable.options._helper = sortable.options.helper;

					sortable.options.helper = function() {
						return ui.helper[ 0 ];
					};

					// Fire the start events of the sortable with our passed browser event,
					// and our own helper (so it doesn't create a new one)
					event.target = sortable.currentItem[ 0 ];
					sortable._mouseCapture( event, true );
					sortable._mouseStart( event, true, true );

					// Because the browser event is way off the new appended portlet,
					// modify necessary variables to reflect the changes
					sortable.offset.click.top = draggable.offset.click.top;
					sortable.offset.click.left = draggable.offset.click.left;
					sortable.offset.parent.left -= draggable.offset.parent.left -
						sortable.offset.parent.left;
					sortable.offset.parent.top -= draggable.offset.parent.top -
						sortable.offset.parent.top;

					draggable._trigger( "toSortable", event );

					// Inform draggable that the helper is in a valid drop zone,
					// used solely in the revert option to handle "valid/invalid".
					draggable.dropped = sortable.element;

					// Need to refreshPositions of all sortables in the case that
					// adding to one sortable changes the location of the other sortables (#9675)
					$.each( draggable.sortables, function() {
						this.refreshPositions();
					});

					// hack so receive/update callbacks work (mostly)
					draggable.currentItem = draggable.element;
					sortable.fromOutside = draggable;
				}

				if ( sortable.currentItem ) {
					sortable._mouseDrag( event );
					// Copy the sortable's position because the draggable's can potentially reflect
					// a relative position, while sortable is always absolute, which the dragged
					// element has now become. (#8809)
					ui.position = sortable.position;
				}
			} else {
				// If it doesn't intersect with the sortable, and it intersected before,
				// we fake the drag stop of the sortable, but make sure it doesn't remove
				// the helper by using cancelHelperRemoval.
				if ( sortable.isOver ) {

					sortable.isOver = 0;
					sortable.cancelHelperRemoval = true;

					// Calling sortable's mouseStop would trigger a revert,
					// so revert must be temporarily false until after mouseStop is called.
					sortable.options._revert = sortable.options.revert;
					sortable.options.revert = false;

					sortable._trigger( "out", event, sortable._uiHash( sortable ) );
					sortable._mouseStop( event, true );

					// restore sortable behaviors that were modfied
					// when the draggable entered the sortable area (#9481)
					sortable.options.revert = sortable.options._revert;
					sortable.options.helper = sortable.options._helper;

					if ( sortable.placeholder ) {
						sortable.placeholder.remove();
					}

					// Recalculate the draggable's offset considering the sortable
					// may have modified them in unexpected ways (#8809)
					draggable._refreshOffsets( event );
					ui.position = draggable._generatePosition( event, true );

					draggable._trigger( "fromSortable", event );

					// Inform draggable that the helper is no longer in a valid drop zone
					draggable.dropped = false;

					// Need to refreshPositions of all sortables just in case removing
					// from one sortable changes the location of other sortables (#9675)
					$.each( draggable.sortables, function() {
						this.refreshPositions();
					});
				}
			}
		});
	}
});

$.ui.plugin.add("draggable", "cursor", {
	start: function( event, ui, instance ) {
		var t = $( "body" ),
			o = instance.options;

		if (t.css("cursor")) {
			o._cursor = t.css("cursor");
		}
		t.css("cursor", o.cursor);
	},
	stop: function( event, ui, instance ) {
		var o = instance.options;
		if (o._cursor) {
			$("body").css("cursor", o._cursor);
		}
	}
});

$.ui.plugin.add("draggable", "opacity", {
	start: function( event, ui, instance ) {
		var t = $( ui.helper ),
			o = instance.options;
		if (t.css("opacity")) {
			o._opacity = t.css("opacity");
		}
		t.css("opacity", o.opacity);
	},
	stop: function( event, ui, instance ) {
		var o = instance.options;
		if (o._opacity) {
			$(ui.helper).css("opacity", o._opacity);
		}
	}
});

$.ui.plugin.add("draggable", "scroll", {
	start: function( event, ui, i ) {
		if ( !i.scrollParentNotHidden ) {
			i.scrollParentNotHidden = i.helper.scrollParent( false );
		}

		if ( i.scrollParentNotHidden[ 0 ] !== i.document[ 0 ] && i.scrollParentNotHidden[ 0 ].tagName !== "HTML" ) {
			i.overflowOffset = i.scrollParentNotHidden.offset();
		}
	},
	drag: function( event, ui, i  ) {

		var o = i.options,
			scrolled = false,
			scrollParent = i.scrollParentNotHidden[ 0 ],
			document = i.document[ 0 ];

		if ( scrollParent !== document && scrollParent.tagName !== "HTML" ) {
			if ( !o.axis || o.axis !== "x" ) {
				if ( ( i.overflowOffset.top + scrollParent.offsetHeight ) - event.pageY < o.scrollSensitivity ) {
					scrollParent.scrollTop = scrolled = scrollParent.scrollTop + o.scrollSpeed;
				} else if ( event.pageY - i.overflowOffset.top < o.scrollSensitivity ) {
					scrollParent.scrollTop = scrolled = scrollParent.scrollTop - o.scrollSpeed;
				}
			}

			if ( !o.axis || o.axis !== "y" ) {
				if ( ( i.overflowOffset.left + scrollParent.offsetWidth ) - event.pageX < o.scrollSensitivity ) {
					scrollParent.scrollLeft = scrolled = scrollParent.scrollLeft + o.scrollSpeed;
				} else if ( event.pageX - i.overflowOffset.left < o.scrollSensitivity ) {
					scrollParent.scrollLeft = scrolled = scrollParent.scrollLeft - o.scrollSpeed;
				}
			}

		} else {

			if (!o.axis || o.axis !== "x") {
				if (event.pageY - $(document).scrollTop() < o.scrollSensitivity) {
					scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
				} else if ($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) {
					scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
				}
			}

			if (!o.axis || o.axis !== "y") {
				if (event.pageX - $(document).scrollLeft() < o.scrollSensitivity) {
					scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
				} else if ($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) {
					scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
				}
			}

		}

		if (scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) {
			$.ui.ddmanager.prepareOffsets(i, event);
		}

	}
});

$.ui.plugin.add("draggable", "snap", {
	start: function( event, ui, i ) {

		var o = i.options;

		i.snapElements = [];

		$(o.snap.constructor !== String ? ( o.snap.items || ":data(bk-ui-draggable)" ) : o.snap).each(function() {
			var $t = $(this),
				$o = $t.offset();
			if (this !== i.element[0]) {
				i.snapElements.push({
					item: this,
					width: $t.outerWidth(), height: $t.outerHeight(),
					top: $o.top, left: $o.left
				});
			}
		});

	},
	drag: function( event, ui, inst ) {

		var ts, bs, ls, rs, l, r, t, b, i, first,
			o = inst.options,
			d = o.snapTolerance,
			x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width,
			y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height;

		for (i = inst.snapElements.length - 1; i >= 0; i--){

			l = inst.snapElements[i].left - inst.margins.left;
			r = l + inst.snapElements[i].width;
			t = inst.snapElements[i].top - inst.margins.top;
			b = t + inst.snapElements[i].height;

			if ( x2 < l - d || x1 > r + d || y2 < t - d || y1 > b + d || !$.contains( inst.snapElements[ i ].item.ownerDocument, inst.snapElements[ i ].item ) ) {
				if (inst.snapElements[i].snapping) {
					(inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
				}
				inst.snapElements[i].snapping = false;
				continue;
			}

			if (o.snapMode !== "inner") {
				ts = Math.abs(t - y2) <= d;
				bs = Math.abs(b - y1) <= d;
				ls = Math.abs(l - x2) <= d;
				rs = Math.abs(r - x1) <= d;
				if (ts) {
					ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top;
				}
				if (bs) {
					ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top;
				}
				if (ls) {
					ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left;
				}
				if (rs) {
					ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left;
				}
			}

			first = (ts || bs || ls || rs);

			if (o.snapMode !== "outer") {
				ts = Math.abs(t - y1) <= d;
				bs = Math.abs(b - y2) <= d;
				ls = Math.abs(l - x1) <= d;
				rs = Math.abs(r - x2) <= d;
				if (ts) {
					ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top;
				}
				if (bs) {
					ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top;
				}
				if (ls) {
					ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left;
				}
				if (rs) {
					ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left;
				}
			}

			if (!inst.snapElements[i].snapping && (ts || bs || ls || rs || first)) {
				(inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
			}
			inst.snapElements[i].snapping = (ts || bs || ls || rs || first);

		}

	}
});

$.ui.plugin.add("draggable", "stack", {
	start: function( event, ui, instance ) {
		var min,
			o = instance.options,
			group = $.makeArray($(o.stack)).sort(function(a, b) {
				return (parseInt($(a).css("zIndex"), 10) || 0) - (parseInt($(b).css("zIndex"), 10) || 0);
			});

		if (!group.length) { return; }

		min = parseInt($(group[0]).css("zIndex"), 10) || 0;
		$(group).each(function(i) {
			$(this).css("zIndex", min + i);
		});
		this.css("zIndex", (min + group.length));
	}
});

$.ui.plugin.add("draggable", "zIndex", {
	start: function( event, ui, instance ) {
		var t = $( ui.helper ),
			o = instance.options;

		if (t.css("zIndex")) {
			o._zIndex = t.css("zIndex");
		}
		t.css("zIndex", o.zIndex);
	},
	stop: function( event, ui, instance ) {
		var o = instance.options;

		if (o._zIndex) {
			$(ui.helper).css("zIndex", o._zIndex);
		}
	}
});

return $.ui.draggable;

}));

/*!
 * jQuery UI Droppable 1.11.2
 * http://jqueryui.com
 *
 * Copyright 2014 jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/droppable/
 */
(function( factory ) {
	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define('jquery_ui/droppable',[
			"jquery",
			"./core",
			"./widget",
			"./mouse",
			"./draggable"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
}(function( $ ) {

$.widget( "ui.droppable", {
	version: "1.11.2",
	widgetEventPrefix: "drop",
	options: {
		accept: "*",
		activeClass: false,
		addClasses: true,
		greedy: false,
		hoverClass: false,
		scope: "default",
		tolerance: "intersect",

		// callbacks
		activate: null,
		deactivate: null,
		drop: null,
		out: null,
		over: null
	},
	_create: function() {

		var proportions,
			o = this.options,
			accept = o.accept;

		this.isover = false;
		this.isout = true;

		this.accept = $.isFunction( accept ) ? accept : function( d ) {
			return d.is( accept );
		};

		this.proportions = function( /* valueToWrite */ ) {
			if ( arguments.length ) {
				// Store the droppable's proportions
				proportions = arguments[ 0 ];
			} else {
				// Retrieve or derive the droppable's proportions
				return proportions ?
					proportions :
					proportions = {
						width: this.element[ 0 ].offsetWidth,
						height: this.element[ 0 ].offsetHeight
					};
			}
		};

		this._addToManager( o.scope );

		o.addClasses && this.element.addClass( "bk-ui-droppable" );

	},

	_addToManager: function( scope ) {
		// Add the reference and positions to the manager
		$.ui.ddmanager.droppables[ scope ] = $.ui.ddmanager.droppables[ scope ] || [];
		$.ui.ddmanager.droppables[ scope ].push( this );
	},

	_splice: function( drop ) {
		var i = 0;
		for ( ; i < drop.length; i++ ) {
			if ( drop[ i ] === this ) {
				drop.splice( i, 1 );
			}
		}
	},

	_destroy: function() {
		var drop = $.ui.ddmanager.droppables[ this.options.scope ];

		this._splice( drop );

		this.element.removeClass( "bk-ui-droppable bk-ui-droppable-disabled" );
	},

	_setOption: function( key, value ) {

		if ( key === "accept" ) {
			this.accept = $.isFunction( value ) ? value : function( d ) {
				return d.is( value );
			};
		} else if ( key === "scope" ) {
			var drop = $.ui.ddmanager.droppables[ this.options.scope ];

			this._splice( drop );
			this._addToManager( value );
		}

		this._super( key, value );
	},

	_activate: function( event ) {
		var draggable = $.ui.ddmanager.current;
		if ( this.options.activeClass ) {
			this.element.addClass( this.options.activeClass );
		}
		if ( draggable ){
			this._trigger( "activate", event, this.ui( draggable ) );
		}
	},

	_deactivate: function( event ) {
		var draggable = $.ui.ddmanager.current;
		if ( this.options.activeClass ) {
			this.element.removeClass( this.options.activeClass );
		}
		if ( draggable ){
			this._trigger( "deactivate", event, this.ui( draggable ) );
		}
	},

	_over: function( event ) {

		var draggable = $.ui.ddmanager.current;

		// Bail if draggable and droppable are same element
		if ( !draggable || ( draggable.currentItem || draggable.element )[ 0 ] === this.element[ 0 ] ) {
			return;
		}

		if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) {
			if ( this.options.hoverClass ) {
				this.element.addClass( this.options.hoverClass );
			}
			this._trigger( "over", event, this.ui( draggable ) );
		}

	},

	_out: function( event ) {

		var draggable = $.ui.ddmanager.current;

		// Bail if draggable and droppable are same element
		if ( !draggable || ( draggable.currentItem || draggable.element )[ 0 ] === this.element[ 0 ] ) {
			return;
		}

		if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) {
			if ( this.options.hoverClass ) {
				this.element.removeClass( this.options.hoverClass );
			}
			this._trigger( "out", event, this.ui( draggable ) );
		}

	},

	_drop: function( event, custom ) {

		var draggable = custom || $.ui.ddmanager.current,
			childrenIntersection = false;

		// Bail if draggable and droppable are same element
		if ( !draggable || ( draggable.currentItem || draggable.element )[ 0 ] === this.element[ 0 ] ) {
			return false;
		}

		this.element.find( ":data(bk-ui-droppable)" ).not( ".bk-ui-draggable-dragging" ).each(function() {
			var inst = $( this ).droppable( "instance" );
			if (
				inst.options.greedy &&
				!inst.options.disabled &&
				inst.options.scope === draggable.options.scope &&
				inst.accept.call( inst.element[ 0 ], ( draggable.currentItem || draggable.element ) ) &&
				$.ui.intersect( draggable, $.extend( inst, { offset: inst.element.offset() } ), inst.options.tolerance, event )
			) { childrenIntersection = true; return false; }
		});
		if ( childrenIntersection ) {
			return false;
		}

		if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) {
			if ( this.options.activeClass ) {
				this.element.removeClass( this.options.activeClass );
			}
			if ( this.options.hoverClass ) {
				this.element.removeClass( this.options.hoverClass );
			}
			this._trigger( "drop", event, this.ui( draggable ) );
			return this.element;
		}

		return false;

	},

	ui: function( c ) {
		return {
			draggable: ( c.currentItem || c.element ),
			helper: c.helper,
			position: c.position,
			offset: c.positionAbs
		};
	}

});

$.ui.intersect = (function() {
	function isOverAxis( x, reference, size ) {
		return ( x >= reference ) && ( x < ( reference + size ) );
	}

	return function( draggable, droppable, toleranceMode, event ) {

		if ( !droppable.offset ) {
			return false;
		}

		var x1 = ( draggable.positionAbs || draggable.position.absolute ).left + draggable.margins.left,
			y1 = ( draggable.positionAbs || draggable.position.absolute ).top + draggable.margins.top,
			x2 = x1 + draggable.helperProportions.width,
			y2 = y1 + draggable.helperProportions.height,
			l = droppable.offset.left,
			t = droppable.offset.top,
			r = l + droppable.proportions().width,
			b = t + droppable.proportions().height;

		switch ( toleranceMode ) {
		case "fit":
			return ( l <= x1 && x2 <= r && t <= y1 && y2 <= b );
		case "intersect":
			return ( l < x1 + ( draggable.helperProportions.width / 2 ) && // Right Half
				x2 - ( draggable.helperProportions.width / 2 ) < r && // Left Half
				t < y1 + ( draggable.helperProportions.height / 2 ) && // Bottom Half
				y2 - ( draggable.helperProportions.height / 2 ) < b ); // Top Half
		case "pointer":
			return isOverAxis( event.pageY, t, droppable.proportions().height ) && isOverAxis( event.pageX, l, droppable.proportions().width );
		case "touch":
			return (
				( y1 >= t && y1 <= b ) || // Top edge touching
				( y2 >= t && y2 <= b ) || // Bottom edge touching
				( y1 < t && y2 > b ) // Surrounded vertically
			) && (
				( x1 >= l && x1 <= r ) || // Left edge touching
				( x2 >= l && x2 <= r ) || // Right edge touching
				( x1 < l && x2 > r ) // Surrounded horizontally
			);
		default:
			return false;
		}
	};
})();

/*
	This manager tracks offsets of draggables and droppables
*/
$.ui.ddmanager = {
	current: null,
	droppables: { "default": [] },
	prepareOffsets: function( t, event ) {

		var i, j,
			m = $.ui.ddmanager.droppables[ t.options.scope ] || [],
			type = event ? event.type : null, // workaround for #2317
			list = ( t.currentItem || t.element ).find( ":data(bk-ui-droppable)" ).addBack();

		droppablesLoop: for ( i = 0; i < m.length; i++ ) {

			// No disabled and non-accepted
			if ( m[ i ].options.disabled || ( t && !m[ i ].accept.call( m[ i ].element[ 0 ], ( t.currentItem || t.element ) ) ) ) {
				continue;
			}

			// Filter out elements in the current dragged item
			for ( j = 0; j < list.length; j++ ) {
				if ( list[ j ] === m[ i ].element[ 0 ] ) {
					m[ i ].proportions().height = 0;
					continue droppablesLoop;
				}
			}

			m[ i ].visible = m[ i ].element.css( "display" ) !== "none";
			if ( !m[ i ].visible ) {
				continue;
			}

			// Activate the droppable if used directly from draggables
			if ( type === "mousedown" ) {
				m[ i ]._activate.call( m[ i ], event );
			}

			m[ i ].offset = m[ i ].element.offset();
			m[ i ].proportions({ width: m[ i ].element[ 0 ].offsetWidth, height: m[ i ].element[ 0 ].offsetHeight });

		}

	},
	drop: function( draggable, event ) {

		var dropped = false;
		// Create a copy of the droppables in case the list changes during the drop (#9116)
		$.each( ( $.ui.ddmanager.droppables[ draggable.options.scope ] || [] ).slice(), function() {

			if ( !this.options ) {
				return;
			}
			if ( !this.options.disabled && this.visible && $.ui.intersect( draggable, this, this.options.tolerance, event ) ) {
				dropped = this._drop.call( this, event ) || dropped;
			}

			if ( !this.options.disabled && this.visible && this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) {
				this.isout = true;
				this.isover = false;
				this._deactivate.call( this, event );
			}

		});
		return dropped;

	},
	dragStart: function( draggable, event ) {
		// Listen for scrolling so that if the dragging causes scrolling the position of the droppables can be recalculated (see #5003)
		draggable.element.parentsUntil( "body" ).bind( "scroll.droppable", function() {
			if ( !draggable.options.refreshPositions ) {
				$.ui.ddmanager.prepareOffsets( draggable, event );
			}
		});
	},
	drag: function( draggable, event ) {

		// If you have a highly dynamic page, you might try this option. It renders positions every time you move the mouse.
		if ( draggable.options.refreshPositions ) {
			$.ui.ddmanager.prepareOffsets( draggable, event );
		}

		// Run through all droppables and check their positions based on specific tolerance options
		$.each( $.ui.ddmanager.droppables[ draggable.options.scope ] || [], function() {

			if ( this.options.disabled || this.greedyChild || !this.visible ) {
				return;
			}

			var parentInstance, scope, parent,
				intersects = $.ui.intersect( draggable, this, this.options.tolerance, event ),
				c = !intersects && this.isover ? "isout" : ( intersects && !this.isover ? "isover" : null );
			if ( !c ) {
				return;
			}

			if ( this.options.greedy ) {
				// find droppable parents with same scope
				scope = this.options.scope;
				parent = this.element.parents( ":data(bk-ui-droppable)" ).filter(function() {
					return $( this ).droppable( "instance" ).options.scope === scope;
				});

				if ( parent.length ) {
					parentInstance = $( parent[ 0 ] ).droppable( "instance" );
					parentInstance.greedyChild = ( c === "isover" );
				}
			}

			// we just moved into a greedy child
			if ( parentInstance && c === "isover" ) {
				parentInstance.isover = false;
				parentInstance.isout = true;
				parentInstance._out.call( parentInstance, event );
			}

			this[ c ] = true;
			this[c === "isout" ? "isover" : "isout"] = false;
			this[c === "isover" ? "_over" : "_out"].call( this, event );

			// we just moved out of a greedy child
			if ( parentInstance && c === "isout" ) {
				parentInstance.isout = false;
				parentInstance.isover = true;
				parentInstance._over.call( parentInstance, event );
			}
		});

	},
	dragStop: function( draggable, event ) {
		draggable.element.parentsUntil( "body" ).unbind( "scroll.droppable" );
		// Call prepareOffsets one final time since IE does not fire return scroll events when overflow was caused by drag (see #5003)
		if ( !draggable.options.refreshPositions ) {
			$.ui.ddmanager.prepareOffsets( draggable, event );
		}
	}
};

return $.ui.droppable;

}));

(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('common/close_wrapper',["underscore", "./continuum_view"], function(_, ContinuumView) {
    var CloseWrapper, _ref;
    CloseWrapper = (function(_super) {
      __extends(CloseWrapper, _super);

      function CloseWrapper() {
        _ref = CloseWrapper.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      CloseWrapper.prototype.attributes = {
        "class": "bk-closewrapper"
      };

      CloseWrapper.prototype.delegateEvents = function(events) {
        return CloseWrapper.__super__.delegateEvents.call(this, events);
      };

      CloseWrapper.prototype.events = {
        "click .bk-close": "close"
      };

      CloseWrapper.prototype.close = function(options) {
        this.view.remove();
        return this.remove();
      };

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

      CloseWrapper.prototype.render = function() {
        this.view.$el.detach();
        this.$el.empty();
        this.$el.html("<a href='#' class='bk-close'>[x]</a>");
        return this.$el.append(this.view.$el);
      };

      return CloseWrapper;

    })(ContinuumView);
    return {
      View: CloseWrapper
    };
  });

}).call(this);

/*
//@ sourceMappingURL=close_wrapper.js.map
*/;
define('widget/crossfilter_template',[],function(){
  var template = function(__obj) {
  var _safe = function(value) {
    if (typeof value === 'undefined' && value == null)
      value = '';
    var result = new String(value);
    result.ecoSafe = true;
    return result;
  };
  return (function() {
    var __out = [], __self = this, _print = function(value) {
      if (typeof value !== 'undefined' && value != null)
        __out.push(value.ecoSafe ? value : __self.escape(value));
    }, _capture = function(callback) {
      var out = __out, result;
      __out = [];
      callback.call(this);
      result = __out.join('');
      __out = out;
      return _safe(result);
    };
    (function() {
      _print(_safe('<div class="bk-crossfilter-container">\n\n  <table>\n\n    <tr>\n\n      <td class="aligntable">\n\n        <div class="bk-crossfilter-configuration bk-bs-container">\n\n          <div class="bk-crossfilter-row">\n\n            <div class="col-md-5 bk-column-list" />\n\n            <div class="col-md-7 bk-filters-facets">\n\n              <div class="bk-bs-panel bk-bs-panel-primary bk-filters">\n                <div class="bk-bs-panel-heading bk-crossfilter-panel-heading"> Filter </div>\n                <div class="bk-bs-panel-body bk-filters-selections" />\n              </div>\n\n              <div class="bk-bs-panel bk-bs-panel-primary bk-facet bk-facet-x">\n                <div class="bk-bs-panel-heading bk-crossfilter-panel-heading"> Facet X </div>\n                <div class="bk-facets-selections " />\n              </div>\n\n              <div class="bk-bs-panel bk-bs-panel-primary bk-facet bk-facet-y">\n                <div class="bk-bs-panel-heading bk-crossfilter-panel-heading"> Facet Y </div>\n                <div class="bk-facets-selections " />\n              </div>\n\n              <div class="bk-bs-panel bk-bs-panel-primary bk-facet bk-facet-tab">\n                <div class="bk-bs-panel-heading bk-crossfilter-panel-heading"> Facet Tab </div>\n                <div class="bk-facets-selections " />\n              </div>\n\n            </div>\n\n          </div>\n\n        </div>\n\n      </td>\n\n      <td class="aligntable">\n\n        <div class="bk-plot-selection">\n\n          <form class="bk-widget-form">\n            <ul class="bk-crossfilter-selector">\n              <li class="bk-plot-selector col-md-3"> </li>\n              <li class="bk-x-selector col-md-3"> </li>\n              <li class="bk-y-selector col-md-3"> </li>\n              <li class="bk-agg-selector col-md-3"> </li>\n            </ul>\n          </form>\n\n        </div>\n\n        <div class="bk-crossfilter-plot" />\n      </td>\n\n    </tr>\n\n  </table>\n\n</div>\n'));
    
    }).call(this);
    
    return __out.join('');
  }).call((function() {
    var obj = {
      escape: function(value) {
        return ('' + value)
          .replace(/&/g, '&amp;')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;')
          .replace(/"/g, '&quot;');
      },
      safe: _safe
    }, key;
    for (key in __obj) obj[key] = __obj[key];
    return obj;
  })());
};
  return template;
});

define('widget/crossfilter_column_template',[],function(){
  var template = function(__obj) {
  var _safe = function(value) {
    if (typeof value === 'undefined' && value == null)
      value = '';
    var result = new String(value);
    result.ecoSafe = true;
    return result;
  };
  return (function() {
    var __out = [], __self = this, _print = function(value) {
      if (typeof value !== 'undefined' && value != null)
        __out.push(value.ecoSafe ? value : __self.escape(value));
    }, _capture = function(callback) {
      var out = __out, result;
      __out = [];
      callback.call(this);
      result = __out.join('');
      __out = out;
      return _safe(result);
    };
    (function() {
      var field, _i, _len, _ref;
    
      if (this.label === "Continuous") {
        _print(_safe('\n<div class="bk-bs-panel-heading bk-crossfilter-panel-heading bk-crossfilter-panel-continuous-heading">\n'));
      } else {
        _print(_safe('\n<div class="bk-bs-panel-heading bk-crossfilter-panel-heading bk-crossfilter-panel-factor-heading">\n'));
      }
    
      _print(_safe('\n  '));
    
      _print(this.name);
    
      _print(_safe(' <span style="font-size:x-small;">('));
    
      _print(this.label);
    
      _print(_safe(')</span>\n</div>\n\n\n<div class="bk-bs-panel-body">\n\n  <table class="bk-table">\n\n    <tbody>\n\n      '));
    
      _ref = this.fields;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        field = _ref[_i];
        _print(_safe('\n      <tr> <td> '));
        _print(field);
        _print(_safe('  </td> <td> '));
        _print(this[field]);
        _print(_safe('  </td> </tr>\n      '));
      }
    
      _print(_safe('\n\n    </tbody>\n\n  </table>\n\n</div>'));
    
    }).call(this);
    
    return __out.join('');
  }).call((function() {
    var obj = {
      escape: function(value) {
        return ('' + value)
          .replace(/&/g, '&amp;')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;')
          .replace(/"/g, '&quot;');
      },
      safe: _safe
    }, key;
    for (key in __obj) obj[key] = __obj[key];
    return obj;
  })());
};
  return template;
});

define('widget/crossfilter_facet_template',[],function(){
  var template = function(__obj) {
  var _safe = function(value) {
    if (typeof value === 'undefined' && value == null)
      value = '';
    var result = new String(value);
    result.ecoSafe = true;
    return result;
  };
  return (function() {
    var __out = [], __self = this, _print = function(value) {
      if (typeof value !== 'undefined' && value != null)
        __out.push(value.ecoSafe ? value : __self.escape(value));
    }, _capture = function(callback) {
      var out = __out, result;
      __out = [];
      callback.call(this);
      result = __out.join('');
      __out = out;
      return _safe(result);
    };
    (function() {
      _print(this.name);
    
      _print(_safe(' &nbsp; [x]'));
    
    }).call(this);
    
    return __out.join('');
  }).call((function() {
    var obj = {
      escape: function(value) {
        return ('' + value)
          .replace(/&/g, '&amp;')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;')
          .replace(/"/g, '&quot;');
      },
      safe: _safe
    }, key;
    for (key in __obj) obj[key] = __obj[key];
    return obj;
  })());
};
  return template;
});

(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, 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(fn, me){ return function(){ return fn.apply(me, arguments); }; };

  define('widget/crossfilter',["common/collection", "underscore", "jquery_ui/draggable", "jquery_ui/droppable", "common/has_parent", "common/has_properties", "common/continuum_view", "common/close_wrapper", "common/build_views", "./crossfilter_template", "./crossfilter_column_template", "./crossfilter_facet_template"], function(Collection, _, draggable, droppable, HasParent, HasProperties, ContinuumView, CloseWrapper, build_views, crossfilter_template, crossfilter_column_template, crossfilter_facet_template) {
    var ColumnCollection, ColumnView, ColumnsView, ContinuousColumn, ContinuousColumnView, CrossFilter, CrossFilterView, CrossFilters, DiscreteColumn, DiscreteColumnView, FacetView, FacetsView, FilterView, PlotAttributeSelector, TimeColumn, TimeColumnView, column_types, _ref, _ref1, _ref10, _ref11, _ref12, _ref13, _ref14, _ref15, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8, _ref9;
    CrossFilterView = (function(_super) {
      __extends(CrossFilterView, _super);

      function CrossFilterView() {
        _ref = CrossFilterView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      CrossFilterView.prototype.tag = "div";

      CrossFilterView.prototype.attributes = {
        "class": "bk-crossfilter"
      };

      CrossFilterView.prototype.initialize = function(options) {
        CrossFilterView.__super__.initialize.call(this, options);
        this.views = {};
        this.listenTo(this.model, 'change:plot', this.render_plot);
        this.render();
        this.render_plot();
        return this;
      };

      CrossFilterView.prototype.render_plot = function() {
        var plot;
        if (this.plot_view != null) {
          this.plot_view.remove();
        }
        plot = this.mget('plot');
        this.plot_view = new plot.default_view({
          model: plot
        });
        this.$el.find('.bk-crossfilter-plot').empty();
        return this.$el.find('.bk-crossfilter-plot').append(this.plot_view.$el);
      };

      CrossFilterView.prototype.render = function() {
        var html;
        if (this.columnview != null) {
          this.columnview.$el.detach();
        }
        this.$el.empty();
        html = crossfilter_template();
        this.$el.html(html);
        this.filterview = new FilterView({
          el: this.$('.bk-filters'),
          collection: this.model.columns,
          model: this.model
        });
        this.facetsview = new FacetsView({
          el: this.$el,
          model: this.model
        });
        this.plotattributeview = new PlotAttributeSelector({
          el: this.$el,
          model: this.model
        });
        this.columnview = new ColumnsView({
          collection: this.model.columns
        });
        this.$('.bk-column-list').append(this.columnview.el);
        this.$('.bk-crossfilter-configuration').height(this.mget('height'));
        this.$('.bk-crossfilter-configuration').width(400);
        return this;
      };

      return CrossFilterView;

    })(ContinuumView);
    CrossFilter = (function(_super) {
      __extends(CrossFilter, _super);

      function CrossFilter() {
        this._set_columns = __bind(this._set_columns, this);
        _ref1 = CrossFilter.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      CrossFilter.prototype.default_view = CrossFilterView;

      CrossFilter.prototype.type = "CrossFilter";

      CrossFilter.prototype.initialize = function(attrs, options) {
        CrossFilter.__super__.initialize.call(this, attrs, options);
        this.columns = new ColumnCollection();
        this._set_columns();
        return this.listenTo(this, 'change:columns', this._set_columns);
      };

      CrossFilter.prototype._set_columns = function() {
        return this.columns.reset(this.get('columns'));
      };

      CrossFilter.prototype.defaults = function() {
        return _.extend({}, CrossFilter.__super__.defaults.call(this), {
          height: 700,
          width: 1300
        });
      };

      return CrossFilter;

    })(HasParent);
    CrossFilters = (function(_super) {
      __extends(CrossFilters, _super);

      function CrossFilters() {
        _ref2 = CrossFilters.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      CrossFilters.prototype.model = CrossFilter;

      return CrossFilters;

    })(Collection);
    PlotAttributeSelector = (function(_super) {
      __extends(PlotAttributeSelector, _super);

      function PlotAttributeSelector() {
        _ref3 = PlotAttributeSelector.__super__.constructor.apply(this, arguments);
        return _ref3;
      }

      PlotAttributeSelector.prototype.initialize = function(options) {
        PlotAttributeSelector.__super__.initialize.call(this, options);
        this.listenTo(this.model, "change:plot_selector", _.bind(this.render_selector, 'plot'));
        this.listenTo(this.model, "change:x_selector", _.bind(this.render_selector, 'x'));
        this.listenTo(this.model, "change:y_selector", _.bind(this.render_selector, 'y'));
        this.listenTo(this.model, "change:agg_selector", _.bind(this.render_selector, 'agg'));
        this.render_selector('plot');
        this.render_selector('x');
        this.render_selector('y');
        return this.render_selector('agg');
      };

      PlotAttributeSelector.prototype.render_selector = function(selector) {
        var model, node;
        node = this.$(".bk-" + selector + "-selector").empty();
        model = this.mget("" + selector + "_selector");
        this.plot_selector_view = new model.default_view({
          model: model
        });
        return node.append(this.plot_selector_view.$el);
      };

      return PlotAttributeSelector;

    })(ContinuumView);
    ColumnsView = (function(_super) {
      __extends(ColumnsView, _super);

      function ColumnsView() {
        _ref4 = ColumnsView.__super__.constructor.apply(this, arguments);
        return _ref4;
      }

      ColumnsView.prototype.initialize = function(options) {
        ColumnsView.__super__.initialize.call(this, options);
        this.views = {};
        this.listenTo(this.collection, 'all', this.render);
        this.render();
        return this;
      };

      ColumnsView.prototype.render = function() {
        var _this = this;
        _.map(this.views, function(view) {
          return view.$el.detach();
        });
        build_views(this.views, this.collection.models);
        _.map(this.collection.models, function(model) {
          return _this.$el.append(_this.views[model.id].$el);
        });
        return this;
      };

      return ColumnsView;

    })(ContinuumView);
    FacetView = (function(_super) {
      __extends(FacetView, _super);

      function FacetView() {
        _ref5 = FacetView.__super__.constructor.apply(this, arguments);
        return _ref5;
      }

      FacetView.prototype.events = {
        "click": "remove"
      };

      FacetView.prototype.tagName = "span";

      FacetView.prototype.attributes = {
        "class": "bk-facet-label"
      };

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

      FacetView.prototype.render = function() {
        return this.$el.html(crossfilter_facet_template({
          name: this.name
        }));
      };

      return FacetView;

    })(ContinuumView);
    FacetsView = (function(_super) {
      __extends(FacetsView, _super);

      function FacetsView() {
        this.drop_tab = __bind(this.drop_tab, this);
        this.drop_y = __bind(this.drop_y, this);
        this.drop_x = __bind(this.drop_x, this);
        this.drop = __bind(this.drop, this);
        this.add_facet = __bind(this.add_facet, this);
        this.remove_facet = __bind(this.remove_facet, this);
        _ref6 = FacetsView.__super__.constructor.apply(this, arguments);
        return _ref6;
      }

      FacetsView.prototype.initialize = function(options) {
        FacetsView.__super__.initialize.call(this, options);
        this.render_init();
        this.render_all_facets();
        this.listenTo(this.model, 'change:facet_x', this.render_all_facets);
        this.listenTo(this.model, 'change:facet_y', this.render_all_facets);
        return this.listenTo(this.model, 'change:facet_tab', this.render_all_facets);
      };

      FacetsView.prototype.render_init = function() {
        this.facet_x_node = this.$('.bk-facet-x');
        this.facet_y_node = this.$('.bk-facet-y');
        this.facet_tab_node = this.$('.bk-facet-tab');
        this.facet_x_node.droppable({
          drop: this.drop_x,
          tolerance: 'pointer',
          hoverClass: 'bk-droppable-hover'
        });
        this.facet_y_node.droppable({
          drop: this.drop_y,
          tolerance: 'pointer',
          hoverClass: 'bk-droppable-hover'
        });
        return this.facet_tab_node.droppable({
          drop: this.drop_tab,
          tolerance: 'pointer',
          hoverClass: 'bk-droppable-hover'
        });
      };

      FacetsView.prototype.render_all_facets = function() {
        this.render_facets(this.facet_x_node, 'facet_x', this.model.get('facet_x'));
        this.render_facets(this.facet_y_node, 'facet_y', this.model.get('facet_y'));
        this.render_facets(this.facet_tab_node, 'facet_tab', this.model.get('facet_tab'));
      };

      FacetsView.prototype.render_facets = function(node, type, facets) {
        var facet, view, _i, _len, _results;
        node = node.find('.bk-facets-selections');
        node.empty();
        _results = [];
        for (_i = 0, _len = facets.length; _i < _len; _i++) {
          facet = facets[_i];
          view = new FacetView({
            name: facet
          });
          this.listenTo(view, 'remove', function() {
            var save;
            return this.remove_facet(facet, save = true);
          });
          _results.push(node.append(view.$el));
        }
        return _results;
      };

      FacetsView.prototype.remove_facet = function(facet, save) {
        var facets, type, x, _i, _len, _ref7;
        if (save == null) {
          save = true;
        }
        _ref7 = ['facet_x', 'facet_y', 'facet_tab'];
        for (_i = 0, _len = _ref7.length; _i < _len; _i++) {
          type = _ref7[_i];
          facets = _.clone(this.model.get(type));
          facets = (function() {
            var _j, _len1, _results;
            _results = [];
            for (_j = 0, _len1 = facets.length; _j < _len1; _j++) {
              x = facets[_j];
              if (x !== facet) {
                _results.push(x);
              }
            }
            return _results;
          })();
          this.model.set(type, facets);
        }
        if (save) {
          return this.model.save();
        }
      };

      FacetsView.prototype.add_facet = function(type, facet) {
        var facets, save;
        this.remove_facet(facet, save = false);
        facets = _.clone(this.model.get(type));
        if (facets.indexOf(facet) < 0) {
          facets.push(facet);
          this.model.set(type, facets);
        }
        return this.model.save();
      };

      FacetsView.prototype.drop = function(type, e, ui) {
        var column_model, name;
        column_model = ui.helper.data('model');
        name = column_model.get('name');
        return this.add_facet(type, name);
      };

      FacetsView.prototype.drop_x = function(e, ui) {
        return this.drop('facet_x', e, ui);
      };

      FacetsView.prototype.drop_y = function(e, ui) {
        return this.drop('facet_y', e, ui);
      };

      FacetsView.prototype.drop_tab = function(e, ui) {
        return this.drop('facet_tab', e, ui);
      };

      return FacetsView;

    })(ContinuumView);
    FilterView = (function(_super) {
      __extends(FilterView, _super);

      function FilterView() {
        this.drop = __bind(this.drop, this);
        _ref7 = FilterView.__super__.constructor.apply(this, arguments);
        return _ref7;
      }

      FilterView.prototype.initialize = function(options) {
        FilterView.__super__.initialize.call(this, options);
        this.views = {};
        this.render();
        this.render_columns_selectors;
        return this.listenTo(this.model, 'change:filter_widgets', this.render_column_selectors);
      };

      FilterView.prototype.drop = function(e, ui) {
        var column_model, filtering_columns;
        column_model = ui.helper.data('model');
        filtering_columns = _.clone(this.model.get('filtering_columns'));
        filtering_columns.push(column_model.get('name'));
        this.model.set('filtering_columns', filtering_columns);
        return this.model.save();
      };

      FilterView.prototype.render = function() {
        return this.$el.droppable({
          drop: this.drop,
          tolerance: 'pointer',
          hoverClass: 'bk-droppable-hover'
        });
      };

      FilterView.prototype.render_column_selectors = function() {
        var col, filter_widget_dict, filter_widgets, filtering_columns, key, newviews, val, _ref8,
          _this = this;
        _.map(this.views, function(view) {
          return view.$el.detach();
        });
        this.$el.find('.bk-filters-selections').empty();
        filter_widget_dict = {};
        _ref8 = this.mget('filter_widgets');
        for (key in _ref8) {
          if (!__hasProp.call(_ref8, key)) continue;
          val = _ref8[key];
          filter_widget_dict[key] = this.model.resolve_ref(val);
        }
        filtering_columns = this.mget('filtering_columns');
        filter_widgets = (function() {
          var _i, _len, _results;
          _results = [];
          for (_i = 0, _len = filtering_columns.length; _i < _len; _i++) {
            col = filtering_columns[_i];
            if (filter_widget_dict[col] != null) {
              _results.push(filter_widget_dict[col]);
            }
          }
          return _results;
        })();
        newviews = build_views(this.views, filter_widgets);
        _.map(newviews, function(view) {
          return _this.listenTo(view, 'remove', _this.child_remove);
        });
        return _.map(filter_widgets, function(model) {
          var wrapper;
          wrapper = new CloseWrapper.View({
            view: _this.views[model.id]
          });
          return _this.$el.find('.bk-filters-selections').append(wrapper.$el);
        });
      };

      FilterView.prototype.child_remove = function(view) {
        var key, model, newcolumns, to_remove, val, _ref8;
        _ref8 = this.mget('filter_widgets');
        for (key in _ref8) {
          if (!__hasProp.call(_ref8, key)) continue;
          val = _ref8[key];
          model = this.model.resolve_ref(val);
          if (model === view.model) {
            to_remove = key;
            break;
          }
        }
        newcolumns = _.filter(this.mget('filtering_columns'), function(x) {
          return x !== to_remove;
        });
        this.mset('filtering_columns', newcolumns);
        return this.model.save();
      };

      return FilterView;

    })(ContinuumView);
    ColumnView = (function(_super) {
      __extends(ColumnView, _super);

      function ColumnView() {
        _ref8 = ColumnView.__super__.constructor.apply(this, arguments);
        return _ref8;
      }

      ColumnView.prototype.template = crossfilter_column_template;

      ColumnView.prototype.attributes = {
        "class": "bk-crossfilter-column-entry bk-bs-panel bk-bs-panel-primary"
      };

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

      ColumnView.prototype.render = function() {
        var _this = this;
        this.$el.html(this.template(this.model.attributes));
        this.$el.draggable({
          appendTo: 'body',
          containment: 'document',
          helper: 'clone',
          start: function(e, ui) {
            return ui.helper.data('model', _this.model);
          }
        });
        return this;
      };

      return ColumnView;

    })(ContinuumView);
    TimeColumnView = (function(_super) {
      __extends(TimeColumnView, _super);

      function TimeColumnView() {
        _ref9 = TimeColumnView.__super__.constructor.apply(this, arguments);
        return _ref9;
      }

      return TimeColumnView;

    })(ColumnView);
    TimeColumn = (function(_super) {
      __extends(TimeColumn, _super);

      function TimeColumn() {
        _ref10 = TimeColumn.__super__.constructor.apply(this, arguments);
        return _ref10;
      }

      TimeColumn.prototype.default_view = TimeColumnView;

      TimeColumn.prototype.defaults = function() {
        return _.extend({}, TimeColumn.__super__.defaults.call(this), {
          type: "TimeColumn",
          label: "Time",
          name: "",
          fields: ['count', 'unique', 'first', 'last'],
          count: 0,
          unique: 0,
          first: 0,
          last: 0
        });
      };

      return TimeColumn;

    })(HasProperties);
    DiscreteColumnView = (function(_super) {
      __extends(DiscreteColumnView, _super);

      function DiscreteColumnView() {
        _ref11 = DiscreteColumnView.__super__.constructor.apply(this, arguments);
        return _ref11;
      }

      return DiscreteColumnView;

    })(ColumnView);
    DiscreteColumn = (function(_super) {
      __extends(DiscreteColumn, _super);

      function DiscreteColumn() {
        _ref12 = DiscreteColumn.__super__.constructor.apply(this, arguments);
        return _ref12;
      }

      DiscreteColumn.prototype.default_view = DiscreteColumnView;

      DiscreteColumn.prototype.defaults = function() {
        return _.extend({}, DiscreteColumn.__super__.defaults.call(this), {
          type: "DiscreteColumn",
          label: "Factor",
          name: "",
          fields: ['count', 'unique', 'top', 'freq'],
          count: 0,
          unique: 0,
          top: 0,
          freq: 0
        });
      };

      return DiscreteColumn;

    })(HasProperties);
    ContinuousColumnView = (function(_super) {
      __extends(ContinuousColumnView, _super);

      function ContinuousColumnView() {
        _ref13 = ContinuousColumnView.__super__.constructor.apply(this, arguments);
        return _ref13;
      }

      return ContinuousColumnView;

    })(ColumnView);
    ContinuousColumn = (function(_super) {
      __extends(ContinuousColumn, _super);

      function ContinuousColumn() {
        _ref14 = ContinuousColumn.__super__.constructor.apply(this, arguments);
        return _ref14;
      }

      ContinuousColumn.prototype.default_view = ContinuousColumnView;

      ContinuousColumn.prototype.defaults = function() {
        return _.extend({}, ContinuousColumn.__super__.defaults.call(this), {
          type: "ContinuousColumn",
          label: "Continuous",
          name: "",
          fields: ['count', 'mean', 'std', 'min', 'max'],
          count: 0,
          mean: 0,
          std: 0,
          min: 0,
          max: 0
        });
      };

      return ContinuousColumn;

    })(HasProperties);
    column_types = {
      'DiscreteColumn': DiscreteColumn,
      'TimeColumn': TimeColumn,
      'ContinuousColumn': ContinuousColumn
    };
    ColumnCollection = (function(_super) {
      __extends(ColumnCollection, _super);

      function ColumnCollection() {
        _ref15 = ColumnCollection.__super__.constructor.apply(this, arguments);
        return _ref15;
      }

      ColumnCollection.prototype.model = function(attrs, options) {
        if (attrs.type in column_types) {
          return new column_types[attrs.type](attrs);
        }
        console.log("Unknown column type: '" + attrs.type + "'");
        return null;
      };

      return ColumnCollection;

    })(Collection);
    return {
      Model: CrossFilter,
      Collection: new CrossFilters(),
      View: CrossFilterView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=crossfilter.js.map
*/;
define('widget/multiselecttemplate',[],function(){
  var template = function(__obj) {
  var _safe = function(value) {
    if (typeof value === 'undefined' && value == null)
      value = '';
    var result = new String(value);
    result.ecoSafe = true;
    return result;
  };
  return (function() {
    var __out = [], __self = this, _print = function(value) {
      if (typeof value !== 'undefined' && value != null)
        __out.push(value.ecoSafe ? value : __self.escape(value));
    }, _capture = function(callback) {
      var out = __out, result;
      __out = [];
      callback.call(this);
      result = __out.join('');
      __out = out;
      return _safe(result);
    };
    (function() {
      var option, _i, _len, _ref;
    
      _print(_safe('<label for="'));
    
      _print(this.id);
    
      _print(_safe('"> '));
    
      _print(this.title);
    
      _print(_safe(' </label>\n<select multiple class="bk-widget-form-input" id="'));
    
      _print(this.id);
    
      _print(_safe('" name="'));
    
      _print(this.name);
    
      _print(_safe('">\n  '));
    
      _ref = this.options;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        option = _ref[_i];
        _print(_safe('\n  '));
        if (option.value === this.value) {
          _print(_safe('\n  <option selected="selected" value="'));
          _print(option.value);
          _print(_safe('">'));
          _print(option.name);
          _print(_safe('</option>\n  '));
        } else {
          _print(_safe('\n  <option value="'));
          _print(option.value);
          _print(_safe('">'));
          _print(option.name);
          _print(_safe('</option> \n  '));
        }
        _print(_safe('\n\n  '));
      }
    
      _print(_safe('\n</select>\n'));
    
    }).call(this);
    
    return __out.join('');
  }).call((function() {
    var obj = {
      escape: function(value) {
        return ('' + value)
          .replace(/&/g, '&amp;')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;')
          .replace(/"/g, '&quot;');
      },
      safe: _safe
    }, key;
    for (key in __obj) obj[key] = __obj[key];
    return obj;
  })());
};
  return template;
});

(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('widget/multiselect',["common/has_parent", "common/continuum_view", "common/collection", "underscore", "./multiselecttemplate"], function(HasParent, ContinuumView, Collection, _, multiselecttemplate) {
    var MultiSelect, MultiSelectView, MultiSelects, multiselectboxes, _ref, _ref1, _ref2;
    MultiSelectView = (function(_super) {
      __extends(MultiSelectView, _super);

      function MultiSelectView() {
        _ref = MultiSelectView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      MultiSelectView.prototype.events = {
        "change select": "change_input"
      };

      MultiSelectView.prototype.change_input = function() {
        this.mset('value', this.$('select').val(), {
          'silent': true
        });
        return this.model.save();
      };

      MultiSelectView.prototype.tagName = "div";

      MultiSelectView.prototype.template = multiselecttemplate;

      MultiSelectView.prototype.initialize = function(options) {
        MultiSelectView.__super__.initialize.call(this, options);
        this.render();
        this.listenTo(this.model, 'change:value', this.render_selection);
        this.listenTo(this.model, 'change:options', this.render);
        this.listenTo(this.model, 'change:name', this.render);
        return this.listenTo(this.model, 'change:title', this.render);
      };

      MultiSelectView.prototype.render = function() {
        var html;
        this.$el.empty();
        html = this.template(this.model.attributes);
        this.$el.html(html);
        this.render_selection();
        return this;
      };

      MultiSelectView.prototype.render_selection = function() {
        var values;
        values = {};
        _.map(this.mget('value'), function(x) {
          return values[x] = true;
        });
        return this.$('option').each(function(el) {
          el = $(el);
          if (values[el.attr('value')]) {
            return el.attr('selected', 'selected');
          }
        });
      };

      return MultiSelectView;

    })(ContinuumView);
    MultiSelect = (function(_super) {
      __extends(MultiSelect, _super);

      function MultiSelect() {
        _ref1 = MultiSelect.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      MultiSelect.prototype.type = "MultiSelect";

      MultiSelect.prototype.default_view = MultiSelectView;

      MultiSelect.prototype.defaults = function() {
        return _.extend({}, MultiSelect.__super__.defaults.call(this), {
          title: '',
          value: [],
          options: []
        });
      };

      return MultiSelect;

    })(HasParent);
    MultiSelects = (function(_super) {
      __extends(MultiSelects, _super);

      function MultiSelects() {
        _ref2 = MultiSelects.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      MultiSelects.prototype.model = MultiSelect;

      return MultiSelects;

    })(Collection);
    multiselectboxes = new MultiSelects();
    return {
      "Model": MultiSelect,
      "Collection": multiselectboxes,
      "View": MultiSelectView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=multiselect.js.map
*/;
/**
 * jQRangeSlider
 * A javascript slider selector that supports dates
 *
 * Copyright (C) Guillaume Gautreau 2012
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 */

define('jqrangeslider/jQRangeSlider',["jquery", "jquery_ui/core", "jquery_ui/widget", "jquery_ui/mouse", "jquery_mousewheel"], function($) {
	

	return $.widget("ui.rangeSlider", {
		options: {
			bounds: {min:0, max:100},
			defaultValues: {min:20, max:50},
			wheelMode: null,
			wheelSpeed: 4,
			arrows: true,
			valueLabels: "show",
			formatter: null,
			durationIn: 0,
			durationOut: 400,
			delayOut: 200,
			range: {min: false, max: false},
			step: false,
			scales: false,
			enabled: true,
			symmetricPositionning: false
		},

		_values: null,
		_valuesChanged: false,
		_initialized: false,

		// Created elements
		bar: null,
		leftHandle: null,
		rightHandle: null,
		innerBar: null,
		container: null,
		arrows: null,
		labels: null,
		changing: {min:false, max:false},
		changed: {min:false, max:false},
		ruler: null,

		_create: function(){
			this._setDefaultValues();

			this.labels = {left: null, right:null, leftDisplayed:true, rightDisplayed:true};
			this.arrows = {left:null, right:null};
			this.changing = {min:false, max:false};
			this.changed = {min:false, max:false};

			this._createElements();

			this._bindResize();

			setTimeout($.proxy(this.resize, this), 1);
			setTimeout($.proxy(this._initValues, this), 1);
		},

		_setDefaultValues: function(){
			this._values = {
				min: this.options.defaultValues.min,
				max: this.options.defaultValues.max
			};
		},

		_bindResize: function(){
			var that = this;

			this._resizeProxy = function(e){
				that.resize(e);
			};

			$(window).resize(this._resizeProxy);
		},

		_initWidth: function(){
			this.container.css("width", this.element.width() - this.container.outerWidth(true) + this.container.width());
			this.innerBar.css("width", this.container.width() - this.innerBar.outerWidth(true) + this.innerBar.width());
		},

		_initValues: function(){
			this._initialized = true;
			this.values(this._values.min, this._values.max);
		},

		_setOption: function(key, value) {
			this._setWheelOption(key, value);
			this._setArrowsOption(key, value);
			this._setLabelsOption(key, value);
			this._setLabelsDurations(key, value);
			this._setFormatterOption(key, value);
			this._setBoundsOption(key, value);
			this._setRangeOption(key, value);
			this._setStepOption(key, value);
			this._setScalesOption(key, value);
			this._setEnabledOption(key, value);
			this._setPositionningOption(key, value);
		},

		_validProperty: function(object, name, defaultValue){
			if (object === null || typeof object[name] === "undefined"){
				return defaultValue;
			}

			return object[name];
		},

		_setStepOption: function(key, value){
			if (key === "step"){
				this.options.step = value;
				this._leftHandle("option", "step", value);
				this._rightHandle("option", "step", value);
				this._changed(true);
			}
		},

		_setScalesOption: function(key, value){
			if (key === "scales"){
				if (value === false || value === null){
					this.options.scales = false;
					this._destroyRuler();
				}else if (value instanceof Array){
					this.options.scales = value;
					this._updateRuler();
				}
			}
		},

		_setRangeOption: function(key, value){
			if (key === "range"){
				this._bar("option", "range", value);
				this.options.range = this._bar("option", "range");
				this._changed(true);
			}
		},

		_setBoundsOption: function(key, value){
			if (key === "bounds" && typeof value.min !== "undefined" && typeof value.max !== "undefined"){
				this.bounds(value.min, value.max);
			}
		},

		_setWheelOption: function(key, value){
			if (key === "wheelMode" || key === "wheelSpeed"){
				this._bar("option", key, value);
				this.options[key] = this._bar("option", key);
			}
		},

		_setLabelsOption: function(key, value){
			if (key === "valueLabels"){
				if (value !== "hide" && value !== "show" && value !== "change"){
					return;
				}

				this.options.valueLabels = value;

				if (value !== "hide"){
					this._createLabels();
					this._leftLabel("update");
					this._rightLabel("update");
				}else{
					this._destroyLabels();
				}
			}
		},

		_setFormatterOption: function(key, value){
			if (key === "formatter" && value !== null && typeof value === "function"){
				if (this.options.valueLabels !== "hide"){
					this._leftLabel("option", "formatter", value);
					this.options.formatter = this._rightLabel("option", "formatter", value);
				}
			}
		},

		_setArrowsOption: function(key, value){
			if (key === "arrows" && (value === true || value === false) && value !== this.options.arrows){
				if (value === true){
					this.element
						.removeClass("bk-ui-rangeSlider-noArrow")
						.addClass("bk-ui-rangeSlider-withArrows");
					this.arrows.left.css("display", "block");
					this.arrows.right.css("display", "block");
					this.options.arrows = true;
				}else if (value === false){
					this.element
						.addClass("bk-ui-rangeSlider-noArrow")
						.removeClass("bk-ui-rangeSlider-withArrows");
					this.arrows.left.css("display", "none");
					this.arrows.right.css("display", "none");
					this.options.arrows = false;
				}

				this._initWidth();
			}
		},

		_setLabelsDurations: function(key, value){
			if (key === "durationIn" || key === "durationOut" || key === "delayOut"){
				if (parseInt(value, 10) !== value) return;

				if (this.labels.left !== null){
					this._leftLabel("option", key, value);
				}

				if (this.labels.right !== null){
					this._rightLabel("option", key, value);
				}

				this.options[key] = value;
			}
		},

		_setEnabledOption: function(key, value){
			if (key === "enabled"){
				this.toggle(value);
			}
		},

		_setPositionningOption: function(key, value){
			if (key === "symmetricPositionning"){
				this._rightHandle("option", key, value);
				this.options[key] = this._leftHandle("option", key, value);
			}
		},

		_createElements: function(){
			if (this.element.css("position") !== "absolute"){
				this.element.css("position", "relative");
			}

			this.element.addClass("bk-ui-rangeSlider");

			this.container = $("<div class='bk-ui-rangeSlider-container' />")
				.css("position", "absolute")
				.appendTo(this.element);

			this.innerBar = $("<div class='bk-ui-rangeSlider-innerBar' />")
				.css("position", "absolute")
				.css("top", 0)
				.css("left", 0);

			this._createHandles();
			this._createBar();
			this.container.prepend(this.innerBar);
			this._createArrows();

			if (this.options.valueLabels !== "hide"){
				this._createLabels();
			}else{
				this._destroyLabels();
			}

			this._updateRuler();

			if (!this.options.enabled) this._toggle(this.options.enabled);
		},

		_createHandle: function(options){
			return $("<div />")
				[this._handleType()](options)
				.bind("sliderDrag", $.proxy(this._changing, this))
				.bind("stop", $.proxy(this._changed, this));
		},

		_createHandles: function(){
			this.leftHandle = this._createHandle({
					isLeft: true,
					bounds: this.options.bounds,
					value: this._values.min,
					step: this.options.step,
					symmetricPositionning: this.options.symmetricPositionning
			}).appendTo(this.container);

			this.rightHandle = this._createHandle({
				isLeft: false,
				bounds: this.options.bounds,
				value: this._values.max,
				step: this.options.step,
				symmetricPositionning: this.options.symmetricPositionning
			}).appendTo(this.container);
		},

		_createBar: function(){
			this.bar = $("<div />")
				.prependTo(this.container)
				.bind("sliderDrag scroll zoom", $.proxy(this._changing, this))
				.bind("stop", $.proxy(this._changed, this));

			this._bar({
					leftHandle: this.leftHandle,
					rightHandle: this.rightHandle,
					values: {min: this._values.min, max: this._values.max},
					type: this._handleType(),
					range: this.options.range,
					wheelMode: this.options.wheelMode,
					wheelSpeed: this.options.wheelSpeed
				});

			this.options.range = this._bar("option", "range");
			this.options.wheelMode = this._bar("option", "wheelMode");
			this.options.wheelSpeed = this._bar("option", "wheelSpeed");
		},

		_createArrows: function(){
			this.arrows.left = this._createArrow("left");
			this.arrows.right = this._createArrow("right");

			if (!this.options.arrows){
				this.arrows.left.css("display", "none");
				this.arrows.right.css("display", "none");
				this.element.addClass("bk-ui-rangeSlider-noArrow");
			}else{
				this.element.addClass("bk-ui-rangeSlider-withArrows");
			}
		},

		_createArrow: function(whichOne){
			var arrow = $("<div class='bk-ui-rangeSlider-arrow' />")
				.append("<div class='bk-ui-rangeSlider-arrow-inner' />")
				.addClass("bk-ui-rangeSlider-" + whichOne + "Arrow")
				.css("position", "absolute")
				.css(whichOne, 0)
				.appendTo(this.element),
				target;

			if (whichOne === "right"){
				target = $.proxy(this._scrollRightClick, this);
			}else{
				target = $.proxy(this._scrollLeftClick, this);
			}

			arrow.bind("mousedown touchstart", target);

			return arrow;
		},

		_proxy: function(element, type, args){
			var array = Array.prototype.slice.call(args);

			if (element && element[type]){
				return element[type].apply(element, array);
			}

			return null;
		},

		_handleType: function(){
			return "rangeSliderHandle";
		},

		_barType: function(){
			return "rangeSliderBar";
		},

		_bar: function(){
			return this._proxy(this.bar, this._barType(), arguments);
		},

		_labelType: function(){
			return "rangeSliderLabel";
		},

		_leftLabel: function(){
			return this._proxy(this.labels.left, this._labelType(), arguments);
		},

		_rightLabel: function(){
			return this._proxy(this.labels.right, this._labelType(), arguments);
		},

		_leftHandle: function(){
			return this._proxy(this.leftHandle, this._handleType(), arguments);
		},

		_rightHandle: function(){
			return this._proxy(this.rightHandle, this._handleType(), arguments);
		},

		_getValue: function(position, handle){
			if (handle === this.rightHandle){
				position = position - handle.outerWidth();
			}

			return position * (this.options.bounds.max - this.options.bounds.min) / (this.container.innerWidth() - handle.outerWidth(true)) + this.options.bounds.min;
		},

		_trigger: function(eventName){
			var that = this;

			setTimeout(function(){
				that.element.trigger(eventName, {
						label: that.element,
						values: that.values()
					});
			}, 1);
		},

		_changing: function(){
			if(this._updateValues()){
				this._trigger("valuesChanging");
				this._valuesChanged = true;
			}
		},

		_deactivateLabels: function(){
			if (this.options.valueLabels === "change"){
				this._leftLabel("option", "show", "hide");
				this._rightLabel("option", "show", "hide");
			}
		},

		_reactivateLabels: function(){
			if (this.options.valueLabels === "change"){
				this._leftLabel("option", "show", "change");
				this._rightLabel("option", "show", "change");
			}
		},

		_changed: function(isAutomatic){
			if (isAutomatic === true){
				this._deactivateLabels();
			}

			if (this._updateValues() || this._valuesChanged){
				this._trigger("valuesChanged");

				if (isAutomatic !== true){
					this._trigger("userValuesChanged");
				}

				this._valuesChanged = false;
			}

			if (isAutomatic === true){
				this._reactivateLabels();
			}
		},

		_updateValues: function(){
			var left = this._leftHandle("value"),
				right = this._rightHandle("value"),
				min = this._min(left, right),
				max = this._max(left, right),
				changing = (min !== this._values.min || max !== this._values.max);

			this._values.min = this._min(left, right);
			this._values.max = this._max(left, right);

			return changing;
		},

		_min: function(value1, value2){
			return Math.min(value1, value2);
		},

		_max: function(value1, value2){
			return Math.max(value1, value2);
		},

		/*
		 * Value labels
		 */
		_createLabel: function(label, handle){
			var params;

			if (label === null){
				params = this._getLabelConstructorParameters(label, handle);
				label = $("<div />")
					.appendTo(this.element)
					[this._labelType()](params);
			}else{
				params = this._getLabelRefreshParameters(label, handle);

				label[this._labelType()](params);
			}

			return label;
		},

		_getLabelConstructorParameters: function(label, handle){
			return {
				handle: handle,
				handleType: this._handleType(),
				formatter: this._getFormatter(),
				show: this.options.valueLabels,
				durationIn: this.options.durationIn,
				durationOut: this.options.durationOut,
				delayOut: this.options.delayOut
			};
		},

		_getLabelRefreshParameters: function(){
			return {
				formatter: this._getFormatter(),
				show: this.options.valueLabels,
				durationIn: this.options.durationIn,
				durationOut: this.options.durationOut,
				delayOut: this.options.delayOut
			};
		},

		_getFormatter: function(){
			if (this.options.formatter === false || this.options.formatter === null){
				return this._defaultFormatter;
			}

			return this.options.formatter;
		},

		_defaultFormatter: function(value){
			return Math.round(value);
		},

		_destroyLabel: function(label){
			if (label !== null){
				label[this._labelType()]("destroy");
				label.remove();
				label = null;
			}

			return label;
		},

		_createLabels: function(){
			this.labels.left = this._createLabel(this.labels.left, this.leftHandle);
			this.labels.right = this._createLabel(this.labels.right, this.rightHandle);

			this._leftLabel("pair", this.labels.right);
		},

		_destroyLabels: function(){
			this.labels.left = this._destroyLabel(this.labels.left);
			this.labels.right = this._destroyLabel(this.labels.right);
		},

		/*
		 * Scrolling
		 */
		_stepRatio: function(){
			return this._leftHandle("stepRatio");
		},

		_scrollRightClick: function(e){
			if (!this.options.enabled) return false;

			e.preventDefault();
			this._bar("startScroll");
			this._bindStopScroll();

			this._continueScrolling("scrollRight", 4 * this._stepRatio(), 1);
		},

		_continueScrolling: function(action, timeout, quantity, timesBeforeSpeedingUp){
			if (!this.options.enabled) return false;

			this._bar(action, quantity);
			timesBeforeSpeedingUp = timesBeforeSpeedingUp || 5;
			timesBeforeSpeedingUp--;

			var that = this,
				minTimeout = 16,
				maxQuantity = Math.max(1, 4 / this._stepRatio());

			this._scrollTimeout = setTimeout(function(){
				if (timesBeforeSpeedingUp === 0){
					if (timeout > minTimeout){
						timeout = Math.max(minTimeout, timeout / 1.5);
					} else {
						quantity = Math.min(maxQuantity, quantity * 2);
					}

					timesBeforeSpeedingUp = 5;
				}

				that._continueScrolling(action, timeout, quantity, timesBeforeSpeedingUp);
			}, timeout);
		},

		_scrollLeftClick: function(e){
			if (!this.options.enabled) return false;

			e.preventDefault();

			this._bar("startScroll");
			this._bindStopScroll();

			this._continueScrolling("scrollLeft", 4 * this._stepRatio(), 1);
		},

		_bindStopScroll: function(){
			var that = this;
			this._stopScrollHandle = function(e){
				e.preventDefault();
				that._stopScroll();
			};

			$(document).bind("mouseup touchend", this._stopScrollHandle);
		},

		_stopScroll: function(){
			$(document).unbind("mouseup touchend", this._stopScrollHandle);
			this._stopScrollHandle = null;
			this._bar("stopScroll");
			clearTimeout(this._scrollTimeout);
		},

		/*
		 * Ruler
		 */
		_createRuler: function(){
			this.ruler = $("<div class='bk-ui-rangeSlider-ruler' />").appendTo(this.innerBar);
		},

		_setRulerParameters: function(){
			this.ruler.ruler({
				min: this.options.bounds.min,
				max: this.options.bounds.max,
				scales: this.options.scales
			});
		},

		_destroyRuler: function(){
			if (this.ruler !== null && $.fn.ruler){
				this.ruler.ruler("destroy");
				this.ruler.remove();
				this.ruler = null;
			}
		},

		_updateRuler: function(){
			this._destroyRuler();

			if (this.options.scales === false || !$.fn.ruler){
				return;
			}

			this._createRuler();
			this._setRulerParameters();
		},

		/*
		 * Public methods
		 */
		values: function(min, max){
			var val;

			if (typeof min !== "undefined" && typeof max !== "undefined"){
				if (!this._initialized){
					this._values.min = min;
					this._values.max = max;
					return this._values;
				}

				this._deactivateLabels();
				val = this._bar("values", min, max);
				this._changed(true);
				this._reactivateLabels();
			}else{
				val = this._bar("values", min, max);
			}

			return val;
		},

		min: function(min){
			this._values.min = this.values(min, this._values.max).min;

			return this._values.min;
		},

		max: function(max){
			this._values.max = this.values(this._values.min, max).max;

			return this._values.max;
		},

		bounds: function(min, max){
			if (this._isValidValue(min) && this._isValidValue(max) && min < max){

				this._setBounds(min, max);
				this._updateRuler();
				this._changed(true);
			}

			return this.options.bounds;
		},

		_isValidValue: function(value){
			return typeof value !== "undefined" && parseFloat(value) === value;
		},

		_setBounds: function(min, max){
			this.options.bounds = {min: min, max: max};
			this._leftHandle("option", "bounds", this.options.bounds);
			this._rightHandle("option", "bounds", this.options.bounds);
			this._bar("option", "bounds", this.options.bounds);
		},

		zoomIn: function(quantity){
			this._bar("zoomIn", quantity)
		},

		zoomOut: function(quantity){
			this._bar("zoomOut", quantity);
		},

		scrollLeft: function(quantity){
			this._bar("startScroll");
			this._bar("scrollLeft", quantity);
			this._bar("stopScroll");
		},

		scrollRight: function(quantity){
			this._bar("startScroll");
			this._bar("scrollRight", quantity);
			this._bar("stopScroll");
		},

		/**
		 * Resize
		 */
		resize: function(){
			this._initWidth();
			this._leftHandle("update");
			this._rightHandle("update");
			this._bar("update");
		},

		/*
		 * Enable / disable
		 */
		enable: function(){
			this.toggle(true);
		},

		disable: function(){
			this.toggle(false);
		},

		toggle: function(enabled){
			if (enabled === undefined) enabled = !this.options.enabled;

			if (this.options.enabled !== enabled){
				this._toggle(enabled);
			}
		},

		_toggle: function(enabled){
			this.options.enabled = enabled;
			this.element.toggleClass("bk-ui-rangeSlider-disabled", !enabled);

			var action = enabled ? "enable" : "disable";

			this._bar(action);
			this._leftHandle(action);
			this._rightHandle(action);
			this._leftLabel(action);
			this._rightLabel(action);
		},

		/*
		 * Destroy
		 */
		destroy: function(){
			this.element.removeClass("bk-ui-rangeSlider-withArrows bk-ui-rangeSlider-noArrow bk-ui-rangeSlider-disabled");

			this._destroyWidgets();
			this._destroyElements();

			this.element.removeClass("bk-ui-rangeSlider");
			this.options = null;

			$(window).unbind("resize", this._resizeProxy);
			this._resizeProxy = null;
			this._bindResize = null;

			$.Widget.prototype.destroy.apply(this, arguments);
		},

		_destroyWidget: function(name){
			this["_" + name]("destroy");
			this[name].remove();
			this[name] = null;
		},

		_destroyWidgets: function(){
			this._destroyWidget("bar");
			this._destroyWidget("leftHandle");
			this._destroyWidget("rightHandle");

			this._destroyRuler();
			this._destroyLabels();
		},

		_destroyElements: function(){
			this.container.remove();
			this.container = null;

			this.innerBar.remove();
			this.innerBar = null;

			this.arrows.left.remove();
			this.arrows.right.remove();
			this.arrows = null;
		}
	});
});

/**
 * jQRangeSlider
 * A javascript slider selector that supports dates
 *
 * Copyright (C) Guillaume Gautreau 2012
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 */

define('jqrangeslider/jQDateRangeSlider',["jquery", "./jQRangeSlider"], function($) {
	

	return $.widget("ui.dateRangeSlider", $.ui.rangeSlider, {
		options: {
			bounds: {min: new Date(2010,0,1).valueOf(), max: new Date(2012,0,1).valueOf()},
			defaultValues: {min: new Date(2010,1,11).valueOf(), max: new Date(2011,1,11).valueOf()}
		},

		_create: function(){
			$.ui.rangeSlider.prototype._create.apply(this);

			this.element.addClass("bk-ui-dateRangeSlider");
		},

		destroy: function(){
			this.element.removeClass("bk-ui-dateRangeSlider");
			$.ui.rangeSlider.prototype.destroy.apply(this);
		},

		_setDefaultValues: function(){
			this._values = {
				min: this.options.defaultValues.min.valueOf(),
				max: this.options.defaultValues.max.valueOf()
			};
		},

		_setRulerParameters: function(){
			this.ruler.ruler({
				min: new Date(this.options.bounds.min),
				max: new Date(this.options.bounds.max),
				scales: this.options.scales
			});
		},

		_setOption: function(key, value){
			if ((key === "defaultValues" || key === "bounds") && typeof value !== "undefined" && value !== null && this._isValidDate(value.min) && this._isValidDate(value.max)){
				$.ui.rangeSlider.prototype._setOption.apply(this, [key, {min:value.min.valueOf(), max:value.max.valueOf()}]);
			}else{
				$.ui.rangeSlider.prototype._setOption.apply(this, this._toArray(arguments));
			}
		},

		_handleType: function(){
			return "dateRangeSliderHandle";
		},

		option: function(key){
			if (key === "bounds" || key === "defaultValues"){
				var result = $.ui.rangeSlider.prototype.option.apply(this, arguments);

				return {min:new Date(result.min), max:new Date(result.max)};
			}

			return $.ui.rangeSlider.prototype.option.apply(this, this._toArray(arguments));
		},

		_defaultFormatter: function(value){
			var month = value.getMonth() + 1,
				day = value.getDate();

			return "" + value.getFullYear() + "-" + (month < 10 ? "0" + month : month) + "-" + (day < 10 ? "0" + day : day);
		},

		_getFormatter: function(){
			var formatter = this.options.formatter;

			if (this.options.formatter === false || this.options.formatter === null){
				formatter = this._defaultFormatter;
			}

			return (function(formatter){
				return function(value){
					return formatter(new Date(value));
				}
			}(formatter));
		},

		values: function(min, max){
			var values = null;

			if (this._isValidDate(min) && this._isValidDate(max))
			{
				values = $.ui.rangeSlider.prototype.values.apply(this, [min.valueOf(), max.valueOf()]);
			}else{
				values = $.ui.rangeSlider.prototype.values.apply(this, this._toArray(arguments));
			}

			return {min: new Date(values.min), max: new Date(values.max)};
		},

		min: function(min){
			if (this._isValidDate(min)){
				return new Date($.ui.rangeSlider.prototype.min.apply(this, [min.valueOf()]));
			}

			return new Date($.ui.rangeSlider.prototype.min.apply(this));
		},

		max: function(max){
			if (this._isValidDate(max)){
				return new Date($.ui.rangeSlider.prototype.max.apply(this, [max.valueOf()]));
			}

			return new Date($.ui.rangeSlider.prototype.max.apply(this));
		},

		bounds: function(min, max){
			var result;

			if (this._isValidDate(min) && this._isValidDate(max)) {
				result = $.ui.rangeSlider.prototype.bounds.apply(this, [min.valueOf(), max.valueOf()]);
			} else {
				result = $.ui.rangeSlider.prototype.bounds.apply(this, this._toArray(arguments));
			}

			return {min: new Date(result.min), max: new Date(result.max)};
		},

		_isValidDate: function(value){
			return typeof value !== "undefined" && value instanceof Date;
		},

		_toArray: function(argsObject){
			return Array.prototype.slice.call(argsObject);
		}
	});
});

(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('widget/date_range_slider',["underscore", "jquery", "jqrangeslider/jQDateRangeSlider", "common/collection", "common/continuum_view", "common/has_properties"], function(_, $, $1, Collection, ContinuumView, HasProperties) {
    var DateRangeSlider, DateRangeSliderView, DateRangeSliders, _ref, _ref1, _ref2;
    DateRangeSliderView = (function(_super) {
      __extends(DateRangeSliderView, _super);

      function DateRangeSliderView() {
        _ref = DateRangeSliderView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      DateRangeSliderView.prototype.initialize = function(options) {
        var _this = this;
        DateRangeSliderView.__super__.initialize.call(this, options);
        this.render();
        return this.listenTo(this.model, 'change', function() {
          return _this.render;
        });
      };

      DateRangeSliderView.prototype.render = function() {
        var bounds_max, bounds_min, range_max, range_min, value_max, value_min, _ref1, _ref2, _ref3,
          _this = this;
        this.$el.empty();
        _ref1 = this.mget("value"), value_min = _ref1[0], value_max = _ref1[1];
        _ref2 = this.mget("range"), range_min = _ref2[0], range_max = _ref2[1];
        _ref3 = this.mget("bounds"), bounds_min = _ref3[0], bounds_max = _ref3[1];
        this.$el.dateRangeSlider({
          defaultValues: {
            min: new Date(value_min),
            max: new Date(value_max)
          },
          bounds: {
            min: new Date(bounds_min),
            max: new Date(bounds_max)
          },
          range: {
            min: _.isObject(range_min) ? range_min : false,
            max: _.isObject(range_max) ? range_max : false
          },
          step: this.mget("step") || {},
          enabled: this.mget("enabled"),
          arrows: this.mget("arrows"),
          valueLabels: this.mget("value_labels"),
          wheelMode: this.mget("wheel_mode")
        });
        return this.$el.on("userValuesChanged", function(event, data) {
          _this.mset('value', [data.values.min, data.values.max]);
          return _this.model.save();
        });
      };

      return DateRangeSliderView;

    })(ContinuumView);
    DateRangeSlider = (function(_super) {
      __extends(DateRangeSlider, _super);

      function DateRangeSlider() {
        _ref1 = DateRangeSlider.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      DateRangeSlider.prototype.type = "DateRangeSlider";

      DateRangeSlider.prototype.default_view = DateRangeSliderView;

      DateRangeSlider.prototype.defaults = function() {
        return _.extend({}, DateRangeSlider.__super__.defaults.call(this), {
          /*
          value
          range
          bounds
          step
          formatter
          scales
          enabled
          arrows
          value_labels
          wheel_mode
          */

        });
      };

      return DateRangeSlider;

    })(HasProperties);
    DateRangeSliders = (function(_super) {
      __extends(DateRangeSliders, _super);

      function DateRangeSliders() {
        _ref2 = DateRangeSliders.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      DateRangeSliders.prototype.model = DateRangeSlider;

      return DateRangeSliders;

    })(Collection);
    return {
      Model: DateRangeSlider,
      Collection: new DateRangeSliders(),
      View: DateRangeSliderView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=date_range_slider.js.map
*/;
/*!
 * jQuery UI Datepicker 1.11.2
 * http://jqueryui.com
 *
 * Copyright 2014 jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/datepicker/
 */
(function( factory ) {
	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define('jquery_ui/datepicker',[
			"jquery",
			"./core"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
}(function( $ ) {

$.extend($.ui, { datepicker: { version: "1.11.2" } });

var datepicker_instActive;

function datepicker_getZindex( elem ) {
	var position, value;
	while ( elem.length && elem[ 0 ] !== document ) {
		// Ignore z-index if position is set to a value where z-index is ignored by the browser
		// This makes behavior of this function consistent across browsers
		// WebKit always returns auto if the element is positioned
		position = elem.css( "position" );
		if ( position === "absolute" || position === "relative" || position === "fixed" ) {
			// IE returns 0 when zIndex is not specified
			// other browsers return a string
			// we ignore the case of nested elements with an explicit value of 0
			// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
			value = parseInt( elem.css( "zIndex" ), 10 );
			if ( !isNaN( value ) && value !== 0 ) {
				return value;
			}
		}
		elem = elem.parent();
	}

	return 0;
}
/* Date picker manager.
   Use the singleton instance of this class, $.datepicker, to interact with the date picker.
   Settings for (groups of) date pickers are maintained in an instance object,
   allowing multiple different settings on the same page. */

function Datepicker() {
	this._curInst = null; // The current instance in use
	this._keyEvent = false; // If the last event was a key event
	this._disabledInputs = []; // List of date picker inputs that have been disabled
	this._datepickerShowing = false; // True if the popup picker is showing , false if not
	this._inDialog = false; // True if showing within a "dialog", false if not
	this._mainDivId = "bk-ui-datepicker-div"; // The ID of the main datepicker division
	this._inlineClass = "bk-ui-datepicker-inline"; // The name of the inline marker class
	this._appendClass = "bk-ui-datepicker-append"; // The name of the append marker class
	this._triggerClass = "bk-ui-datepicker-trigger"; // The name of the trigger marker class
	this._dialogClass = "bk-ui-datepicker-dialog"; // The name of the dialog marker class
	this._disableClass = "bk-ui-datepicker-disabled"; // The name of the disabled covering marker class
	this._unselectableClass = "bk-ui-datepicker-unselectable"; // The name of the unselectable cell marker class
	this._currentClass = "bk-ui-datepicker-current-day"; // The name of the current day marker class
	this._dayOverClass = "bk-ui-datepicker-days-cell-over"; // The name of the day hover marker class
	this.regional = []; // Available regional settings, indexed by language code
	this.regional[""] = { // Default regional settings
		closeText: "Done", // Display text for close link
		prevText: "Prev", // Display text for previous month link
		nextText: "Next", // Display text for next month link
		currentText: "Today", // Display text for current month link
		monthNames: ["January","February","March","April","May","June",
			"July","August","September","October","November","December"], // Names of months for drop-down and formatting
		monthNamesShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], // For formatting
		dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], // For formatting
		dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], // For formatting
		dayNamesMin: ["Su","Mo","Tu","We","Th","Fr","Sa"], // Column headings for days starting at Sunday
		weekHeader: "Wk", // Column header for week of the year
		dateFormat: "mm/dd/yy", // See format options on parseDate
		firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
		isRTL: false, // True if right-to-left language, false if left-to-right
		showMonthAfterYear: false, // True if the year select precedes month, false for month then year
		yearSuffix: "" // Additional text to append to the year in the month headers
	};
	this._defaults = { // Global defaults for all the date picker instances
		showOn: "focus", // "focus" for popup on focus,
			// "button" for trigger button, or "both" for either
		showAnim: "fadeIn", // Name of jQuery animation for popup
		showOptions: {}, // Options for enhanced animations
		defaultDate: null, // Used when field is blank: actual date,
			// +/-number for offset from today, null for today
		appendText: "", // Display text following the input box, e.g. showing the format
		buttonText: "...", // Text for trigger button
		buttonImage: "", // URL for trigger button image
		buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
		hideIfNoPrevNext: false, // True to hide next/previous month links
			// if not applicable, false to just disable them
		navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
		gotoCurrent: false, // True if today link goes back to current selection instead
		changeMonth: false, // True if month can be selected directly, false if only prev/next
		changeYear: false, // True if year can be selected directly, false if only prev/next
		yearRange: "c-10:c+10", // Range of years to display in drop-down,
			// either relative to today's year (-nn:+nn), relative to currently displayed year
			// (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n)
		showOtherMonths: false, // True to show dates in other months, false to leave blank
		selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable
		showWeek: false, // True to show week of the year, false to not show it
		calculateWeek: this.iso8601Week, // How to calculate the week of the year,
			// takes a Date and returns the number of the week for it
		shortYearCutoff: "+10", // Short year values < this are in the current century,
			// > this are in the previous century,
			// string value starting with "+" for current year + value
		minDate: null, // The earliest selectable date, or null for no limit
		maxDate: null, // The latest selectable date, or null for no limit
		duration: "fast", // Duration of display/closure
		beforeShowDay: null, // Function that takes a date and returns an array with
			// [0] = true if selectable, false if not, [1] = custom CSS class name(s) or "",
			// [2] = cell title (optional), e.g. $.datepicker.noWeekends
		beforeShow: null, // Function that takes an input field and
			// returns a set of custom settings for the date picker
		onSelect: null, // Define a callback function when a date is selected
		onChangeMonthYear: null, // Define a callback function when the month or year is changed
		onClose: null, // Define a callback function when the datepicker is closed
		numberOfMonths: 1, // Number of months to show at a time
		showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
		stepMonths: 1, // Number of months to step back/forward
		stepBigMonths: 12, // Number of months to step back/forward for the big links
		altField: "", // Selector for an alternate field to store selected dates into
		altFormat: "", // The date format to use for the alternate field
		constrainInput: true, // The input is constrained by the current date format
		showButtonPanel: false, // True to show button panel, false to not show it
		autoSize: false, // True to size the input for the date format, false to leave as is
		disabled: false // The initial disabled state
	};
	$.extend(this._defaults, this.regional[""]);
	this.regional.en = $.extend( true, {}, this.regional[ "" ]);
	this.regional[ "en-US" ] = $.extend( true, {}, this.regional.en );
	this.dpDiv = datepicker_bindHover($("<div id='" + this._mainDivId + "' class='bk-ui-datepicker bk-ui-widget bk-ui-widget-content bk-ui-helper-clearfix bk-ui-corner-all'></div>"));
}

$.extend(Datepicker.prototype, {
	/* Class name added to elements to indicate already configured with a date picker. */
	markerClassName: "hasDatepicker",

	//Keep track of the maximum number of rows displayed (see #7043)
	maxRows: 4,

	// TODO rename to "widget" when switching to widget factory
	_widgetDatepicker: function() {
		return this.dpDiv;
	},

	/* Override the default settings for all instances of the date picker.
	 * @param  settings  object - the new settings to use as defaults (anonymous object)
	 * @return the manager object
	 */
	setDefaults: function(settings) {
		datepicker_extendRemove(this._defaults, settings || {});
		return this;
	},

	/* Attach the date picker to a jQuery selection.
	 * @param  target	element - the target input field or division or span
	 * @param  settings  object - the new settings to use for this date picker instance (anonymous)
	 */
	_attachDatepicker: function(target, settings) {
		var nodeName, inline, inst;
		nodeName = target.nodeName.toLowerCase();
		inline = (nodeName === "div" || nodeName === "span");
		if (!target.id) {
			this.uuid += 1;
			target.id = "dp" + this.uuid;
		}
		inst = this._newInst($(target), inline);
		inst.settings = $.extend({}, settings || {});
		if (nodeName === "input") {
			this._connectDatepicker(target, inst);
		} else if (inline) {
			this._inlineDatepicker(target, inst);
		}
	},

	/* Create a new instance object. */
	_newInst: function(target, inline) {
		var id = target[0].id.replace(/([^A-Za-z0-9_\-])/g, "\\\\$1"); // escape jQuery meta chars
		return {id: id, input: target, // associated target
			selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
			drawMonth: 0, drawYear: 0, // month being drawn
			inline: inline, // is datepicker inline or not
			dpDiv: (!inline ? this.dpDiv : // presentation div
			datepicker_bindHover($("<div class='" + this._inlineClass + " bk-ui-datepicker bk-ui-widget bk-ui-widget-content bk-ui-helper-clearfix bk-ui-corner-all'></div>")))};
	},

	/* Attach the date picker to an input field. */
	_connectDatepicker: function(target, inst) {
		var input = $(target);
		inst.append = $([]);
		inst.trigger = $([]);
		if (input.hasClass(this.markerClassName)) {
			return;
		}
		this._attachments(input, inst);
		input.addClass(this.markerClassName).keydown(this._doKeyDown).
			keypress(this._doKeyPress).keyup(this._doKeyUp);
		this._autoSize(inst);
		$.data(target, "datepicker", inst);
		//If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665)
		if( inst.settings.disabled ) {
			this._disableDatepicker( target );
		}
	},

	/* Make attachments based on settings. */
	_attachments: function(input, inst) {
		var showOn, buttonText, buttonImage,
			appendText = this._get(inst, "appendText"),
			isRTL = this._get(inst, "isRTL");

		if (inst.append) {
			inst.append.remove();
		}
		if (appendText) {
			inst.append = $("<span class='" + this._appendClass + "'>" + appendText + "</span>");
			input[isRTL ? "before" : "after"](inst.append);
		}

		input.unbind("focus", this._showDatepicker);

		if (inst.trigger) {
			inst.trigger.remove();
		}

		showOn = this._get(inst, "showOn");
		if (showOn === "focus" || showOn === "both") { // pop-up date picker when in the marked field
			input.focus(this._showDatepicker);
		}
		if (showOn === "button" || showOn === "both") { // pop-up date picker when button clicked
			buttonText = this._get(inst, "buttonText");
			buttonImage = this._get(inst, "buttonImage");
			inst.trigger = $(this._get(inst, "buttonImageOnly") ?
				$("<img/>").addClass(this._triggerClass).
					attr({ src: buttonImage, alt: buttonText, title: buttonText }) :
				$("<button type='button'></button>").addClass(this._triggerClass).
					html(!buttonImage ? buttonText : $("<img/>").attr(
					{ src:buttonImage, alt:buttonText, title:buttonText })));
			input[isRTL ? "before" : "after"](inst.trigger);
			inst.trigger.click(function() {
				if ($.datepicker._datepickerShowing && $.datepicker._lastInput === input[0]) {
					$.datepicker._hideDatepicker();
				} else if ($.datepicker._datepickerShowing && $.datepicker._lastInput !== input[0]) {
					$.datepicker._hideDatepicker();
					$.datepicker._showDatepicker(input[0]);
				} else {
					$.datepicker._showDatepicker(input[0]);
				}
				return false;
			});
		}
	},

	/* Apply the maximum length for the date format. */
	_autoSize: function(inst) {
		if (this._get(inst, "autoSize") && !inst.inline) {
			var findMax, max, maxI, i,
				date = new Date(2009, 12 - 1, 20), // Ensure double digits
				dateFormat = this._get(inst, "dateFormat");

			if (dateFormat.match(/[DM]/)) {
				findMax = function(names) {
					max = 0;
					maxI = 0;
					for (i = 0; i < names.length; i++) {
						if (names[i].length > max) {
							max = names[i].length;
							maxI = i;
						}
					}
					return maxI;
				};
				date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ?
					"monthNames" : "monthNamesShort"))));
				date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ?
					"dayNames" : "dayNamesShort"))) + 20 - date.getDay());
			}
			inst.input.attr("size", this._formatDate(inst, date).length);
		}
	},

	/* Attach an inline date picker to a div. */
	_inlineDatepicker: function(target, inst) {
		var divSpan = $(target);
		if (divSpan.hasClass(this.markerClassName)) {
			return;
		}
		divSpan.addClass(this.markerClassName).append(inst.dpDiv);
		$.data(target, "datepicker", inst);
		this._setDate(inst, this._getDefaultDate(inst), true);
		this._updateDatepicker(inst);
		this._updateAlternate(inst);
		//If disabled option is true, disable the datepicker before showing it (see ticket #5665)
		if( inst.settings.disabled ) {
			this._disableDatepicker( target );
		}
		// Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements
		// http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height
		inst.dpDiv.css( "display", "block" );
	},

	/* Pop-up the date picker in a "dialog" box.
	 * @param  input element - ignored
	 * @param  date	string or Date - the initial date to display
	 * @param  onSelect  function - the function to call when a date is selected
	 * @param  settings  object - update the dialog date picker instance's settings (anonymous object)
	 * @param  pos int[2] - coordinates for the dialog's position within the screen or
	 *					event - with x/y coordinates or
	 *					leave empty for default (screen centre)
	 * @return the manager object
	 */
	_dialogDatepicker: function(input, date, onSelect, settings, pos) {
		var id, browserWidth, browserHeight, scrollX, scrollY,
			inst = this._dialogInst; // internal instance

		if (!inst) {
			this.uuid += 1;
			id = "dp" + this.uuid;
			this._dialogInput = $("<input type='text' id='" + id +
				"' style='position: absolute; top: -100px; width: 0px;'/>");
			this._dialogInput.keydown(this._doKeyDown);
			$("body").append(this._dialogInput);
			inst = this._dialogInst = this._newInst(this._dialogInput, false);
			inst.settings = {};
			$.data(this._dialogInput[0], "datepicker", inst);
		}
		datepicker_extendRemove(inst.settings, settings || {});
		date = (date && date.constructor === Date ? this._formatDate(inst, date) : date);
		this._dialogInput.val(date);

		this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null);
		if (!this._pos) {
			browserWidth = document.documentElement.clientWidth;
			browserHeight = document.documentElement.clientHeight;
			scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
			scrollY = document.documentElement.scrollTop || document.body.scrollTop;
			this._pos = // should use actual width/height below
				[(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY];
		}

		// move input on screen for focus, but hidden behind dialog
		this._dialogInput.css("left", (this._pos[0] + 20) + "px").css("top", this._pos[1] + "px");
		inst.settings.onSelect = onSelect;
		this._inDialog = true;
		this.dpDiv.addClass(this._dialogClass);
		this._showDatepicker(this._dialogInput[0]);
		if ($.blockUI) {
			$.blockUI(this.dpDiv);
		}
		$.data(this._dialogInput[0], "datepicker", inst);
		return this;
	},

	/* Detach a datepicker from its control.
	 * @param  target	element - the target input field or division or span
	 */
	_destroyDatepicker: function(target) {
		var nodeName,
			$target = $(target),
			inst = $.data(target, "datepicker");

		if (!$target.hasClass(this.markerClassName)) {
			return;
		}

		nodeName = target.nodeName.toLowerCase();
		$.removeData(target, "datepicker");
		if (nodeName === "input") {
			inst.append.remove();
			inst.trigger.remove();
			$target.removeClass(this.markerClassName).
				unbind("focus", this._showDatepicker).
				unbind("keydown", this._doKeyDown).
				unbind("keypress", this._doKeyPress).
				unbind("keyup", this._doKeyUp);
		} else if (nodeName === "div" || nodeName === "span") {
			$target.removeClass(this.markerClassName).empty();
		}
	},

	/* Enable the date picker to a jQuery selection.
	 * @param  target	element - the target input field or division or span
	 */
	_enableDatepicker: function(target) {
		var nodeName, inline,
			$target = $(target),
			inst = $.data(target, "datepicker");

		if (!$target.hasClass(this.markerClassName)) {
			return;
		}

		nodeName = target.nodeName.toLowerCase();
		if (nodeName === "input") {
			target.disabled = false;
			inst.trigger.filter("button").
				each(function() { this.disabled = false; }).end().
				filter("img").css({opacity: "1.0", cursor: ""});
		} else if (nodeName === "div" || nodeName === "span") {
			inline = $target.children("." + this._inlineClass);
			inline.children().removeClass("bk-ui-state-disabled");
			inline.find("select.bk-ui-datepicker-month, select.bk-ui-datepicker-year").
				prop("disabled", false);
		}
		this._disabledInputs = $.map(this._disabledInputs,
			function(value) { return (value === target ? null : value); }); // delete entry
	},

	/* Disable the date picker to a jQuery selection.
	 * @param  target	element - the target input field or division or span
	 */
	_disableDatepicker: function(target) {
		var nodeName, inline,
			$target = $(target),
			inst = $.data(target, "datepicker");

		if (!$target.hasClass(this.markerClassName)) {
			return;
		}

		nodeName = target.nodeName.toLowerCase();
		if (nodeName === "input") {
			target.disabled = true;
			inst.trigger.filter("button").
				each(function() { this.disabled = true; }).end().
				filter("img").css({opacity: "0.5", cursor: "default"});
		} else if (nodeName === "div" || nodeName === "span") {
			inline = $target.children("." + this._inlineClass);
			inline.children().addClass("bk-ui-state-disabled");
			inline.find("select.bk-ui-datepicker-month, select.bk-ui-datepicker-year").
				prop("disabled", true);
		}
		this._disabledInputs = $.map(this._disabledInputs,
			function(value) { return (value === target ? null : value); }); // delete entry
		this._disabledInputs[this._disabledInputs.length] = target;
	},

	/* Is the first field in a jQuery collection disabled as a datepicker?
	 * @param  target	element - the target input field or division or span
	 * @return boolean - true if disabled, false if enabled
	 */
	_isDisabledDatepicker: function(target) {
		if (!target) {
			return false;
		}
		for (var i = 0; i < this._disabledInputs.length; i++) {
			if (this._disabledInputs[i] === target) {
				return true;
			}
		}
		return false;
	},

	/* Retrieve the instance data for the target control.
	 * @param  target  element - the target input field or division or span
	 * @return  object - the associated instance data
	 * @throws  error if a jQuery problem getting data
	 */
	_getInst: function(target) {
		try {
			return $.data(target, "datepicker");
		}
		catch (err) {
			throw "Missing instance data for this datepicker";
		}
	},

	/* Update or retrieve the settings for a date picker attached to an input field or division.
	 * @param  target  element - the target input field or division or span
	 * @param  name	object - the new settings to update or
	 *				string - the name of the setting to change or retrieve,
	 *				when retrieving also "all" for all instance settings or
	 *				"defaults" for all global defaults
	 * @param  value   any - the new value for the setting
	 *				(omit if above is an object or to retrieve a value)
	 */
	_optionDatepicker: function(target, name, value) {
		var settings, date, minDate, maxDate,
			inst = this._getInst(target);

		if (arguments.length === 2 && typeof name === "string") {
			return (name === "defaults" ? $.extend({}, $.datepicker._defaults) :
				(inst ? (name === "all" ? $.extend({}, inst.settings) :
				this._get(inst, name)) : null));
		}

		settings = name || {};
		if (typeof name === "string") {
			settings = {};
			settings[name] = value;
		}

		if (inst) {
			if (this._curInst === inst) {
				this._hideDatepicker();
			}

			date = this._getDateDatepicker(target, true);
			minDate = this._getMinMaxDate(inst, "min");
			maxDate = this._getMinMaxDate(inst, "max");
			datepicker_extendRemove(inst.settings, settings);
			// reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided
			if (minDate !== null && settings.dateFormat !== undefined && settings.minDate === undefined) {
				inst.settings.minDate = this._formatDate(inst, minDate);
			}
			if (maxDate !== null && settings.dateFormat !== undefined && settings.maxDate === undefined) {
				inst.settings.maxDate = this._formatDate(inst, maxDate);
			}
			if ( "disabled" in settings ) {
				if ( settings.disabled ) {
					this._disableDatepicker(target);
				} else {
					this._enableDatepicker(target);
				}
			}
			this._attachments($(target), inst);
			this._autoSize(inst);
			this._setDate(inst, date);
			this._updateAlternate(inst);
			this._updateDatepicker(inst);
		}
	},

	// change method deprecated
	_changeDatepicker: function(target, name, value) {
		this._optionDatepicker(target, name, value);
	},

	/* Redraw the date picker attached to an input field or division.
	 * @param  target  element - the target input field or division or span
	 */
	_refreshDatepicker: function(target) {
		var inst = this._getInst(target);
		if (inst) {
			this._updateDatepicker(inst);
		}
	},

	/* Set the dates for a jQuery selection.
	 * @param  target element - the target input field or division or span
	 * @param  date	Date - the new date
	 */
	_setDateDatepicker: function(target, date) {
		var inst = this._getInst(target);
		if (inst) {
			this._setDate(inst, date);
			this._updateDatepicker(inst);
			this._updateAlternate(inst);
		}
	},

	/* Get the date(s) for the first entry in a jQuery selection.
	 * @param  target element - the target input field or division or span
	 * @param  noDefault boolean - true if no default date is to be used
	 * @return Date - the current date
	 */
	_getDateDatepicker: function(target, noDefault) {
		var inst = this._getInst(target);
		if (inst && !inst.inline) {
			this._setDateFromField(inst, noDefault);
		}
		return (inst ? this._getDate(inst) : null);
	},

	/* Handle keystrokes. */
	_doKeyDown: function(event) {
		var onSelect, dateStr, sel,
			inst = $.datepicker._getInst(event.target),
			handled = true,
			isRTL = inst.dpDiv.is(".bk-ui-datepicker-rtl");

		inst._keyEvent = true;
		if ($.datepicker._datepickerShowing) {
			switch (event.keyCode) {
				case 9: $.datepicker._hideDatepicker();
						handled = false;
						break; // hide on tab out
				case 13: sel = $("td." + $.datepicker._dayOverClass + ":not(." +
									$.datepicker._currentClass + ")", inst.dpDiv);
						if (sel[0]) {
							$.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]);
						}

						onSelect = $.datepicker._get(inst, "onSelect");
						if (onSelect) {
							dateStr = $.datepicker._formatDate(inst);

							// trigger custom callback
							onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);
						} else {
							$.datepicker._hideDatepicker();
						}

						return false; // don't submit the form
				case 27: $.datepicker._hideDatepicker();
						break; // hide on escape
				case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
							-$.datepicker._get(inst, "stepBigMonths") :
							-$.datepicker._get(inst, "stepMonths")), "M");
						break; // previous month/year on page up/+ ctrl
				case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
							+$.datepicker._get(inst, "stepBigMonths") :
							+$.datepicker._get(inst, "stepMonths")), "M");
						break; // next month/year on page down/+ ctrl
				case 35: if (event.ctrlKey || event.metaKey) {
							$.datepicker._clearDate(event.target);
						}
						handled = event.ctrlKey || event.metaKey;
						break; // clear on ctrl or command +end
				case 36: if (event.ctrlKey || event.metaKey) {
							$.datepicker._gotoToday(event.target);
						}
						handled = event.ctrlKey || event.metaKey;
						break; // current on ctrl or command +home
				case 37: if (event.ctrlKey || event.metaKey) {
							$.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), "D");
						}
						handled = event.ctrlKey || event.metaKey;
						// -1 day on ctrl or command +left
						if (event.originalEvent.altKey) {
							$.datepicker._adjustDate(event.target, (event.ctrlKey ?
								-$.datepicker._get(inst, "stepBigMonths") :
								-$.datepicker._get(inst, "stepMonths")), "M");
						}
						// next month/year on alt +left on Mac
						break;
				case 38: if (event.ctrlKey || event.metaKey) {
							$.datepicker._adjustDate(event.target, -7, "D");
						}
						handled = event.ctrlKey || event.metaKey;
						break; // -1 week on ctrl or command +up
				case 39: if (event.ctrlKey || event.metaKey) {
							$.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), "D");
						}
						handled = event.ctrlKey || event.metaKey;
						// +1 day on ctrl or command +right
						if (event.originalEvent.altKey) {
							$.datepicker._adjustDate(event.target, (event.ctrlKey ?
								+$.datepicker._get(inst, "stepBigMonths") :
								+$.datepicker._get(inst, "stepMonths")), "M");
						}
						// next month/year on alt +right
						break;
				case 40: if (event.ctrlKey || event.metaKey) {
							$.datepicker._adjustDate(event.target, +7, "D");
						}
						handled = event.ctrlKey || event.metaKey;
						break; // +1 week on ctrl or command +down
				default: handled = false;
			}
		} else if (event.keyCode === 36 && event.ctrlKey) { // display the date picker on ctrl+home
			$.datepicker._showDatepicker(this);
		} else {
			handled = false;
		}

		if (handled) {
			event.preventDefault();
			event.stopPropagation();
		}
	},

	/* Filter entered characters - based on date format. */
	_doKeyPress: function(event) {
		var chars, chr,
			inst = $.datepicker._getInst(event.target);

		if ($.datepicker._get(inst, "constrainInput")) {
			chars = $.datepicker._possibleChars($.datepicker._get(inst, "dateFormat"));
			chr = String.fromCharCode(event.charCode == null ? event.keyCode : event.charCode);
			return event.ctrlKey || event.metaKey || (chr < " " || !chars || chars.indexOf(chr) > -1);
		}
	},

	/* Synchronise manual entry and field/alternate field. */
	_doKeyUp: function(event) {
		var date,
			inst = $.datepicker._getInst(event.target);

		if (inst.input.val() !== inst.lastVal) {
			try {
				date = $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"),
					(inst.input ? inst.input.val() : null),
					$.datepicker._getFormatConfig(inst));

				if (date) { // only if valid
					$.datepicker._setDateFromField(inst);
					$.datepicker._updateAlternate(inst);
					$.datepicker._updateDatepicker(inst);
				}
			}
			catch (err) {
			}
		}
		return true;
	},

	/* Pop-up the date picker for a given input field.
	 * If false returned from beforeShow event handler do not show.
	 * @param  input  element - the input field attached to the date picker or
	 *					event - if triggered by focus
	 */
	_showDatepicker: function(input) {
		input = input.target || input;
		if (input.nodeName.toLowerCase() !== "input") { // find from button/image trigger
			input = $("input", input.parentNode)[0];
		}

		if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput === input) { // already here
			return;
		}

		var inst, beforeShow, beforeShowSettings, isFixed,
			offset, showAnim, duration;

		inst = $.datepicker._getInst(input);
		if ($.datepicker._curInst && $.datepicker._curInst !== inst) {
			$.datepicker._curInst.dpDiv.stop(true, true);
			if ( inst && $.datepicker._datepickerShowing ) {
				$.datepicker._hideDatepicker( $.datepicker._curInst.input[0] );
			}
		}

		beforeShow = $.datepicker._get(inst, "beforeShow");
		beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {};
		if(beforeShowSettings === false){
			return;
		}
		datepicker_extendRemove(inst.settings, beforeShowSettings);

		inst.lastVal = null;
		$.datepicker._lastInput = input;
		$.datepicker._setDateFromField(inst);

		if ($.datepicker._inDialog) { // hide cursor
			input.value = "";
		}
		if (!$.datepicker._pos) { // position below input
			$.datepicker._pos = $.datepicker._findPos(input);
			$.datepicker._pos[1] += input.offsetHeight; // add the height
		}

		isFixed = false;
		$(input).parents().each(function() {
			isFixed |= $(this).css("position") === "fixed";
			return !isFixed;
		});

		offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]};
		$.datepicker._pos = null;
		//to avoid flashes on Firefox
		inst.dpDiv.empty();
		// determine sizing offscreen
		inst.dpDiv.css({position: "absolute", display: "block", top: "-1000px"});
		$.datepicker._updateDatepicker(inst);
		// fix width for dynamic number of date pickers
		// and adjust position before showing
		offset = $.datepicker._checkOffset(inst, offset, isFixed);
		inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ?
			"static" : (isFixed ? "fixed" : "absolute")), display: "none",
			left: offset.left + "px", top: offset.top + "px"});

		if (!inst.inline) {
			showAnim = $.datepicker._get(inst, "showAnim");
			duration = $.datepicker._get(inst, "duration");
			inst.dpDiv.css( "z-index", datepicker_getZindex( $( input ) ) + 1 );
			$.datepicker._datepickerShowing = true;

			if ( $.effects && $.effects.effect[ showAnim ] ) {
				inst.dpDiv.show(showAnim, $.datepicker._get(inst, "showOptions"), duration);
			} else {
				inst.dpDiv[showAnim || "show"](showAnim ? duration : null);
			}

			if ( $.datepicker._shouldFocusInput( inst ) ) {
				inst.input.focus();
			}

			$.datepicker._curInst = inst;
		}
	},

	/* Generate the date picker content. */
	_updateDatepicker: function(inst) {
		this.maxRows = 4; //Reset the max number of rows being displayed (see #7043)
		datepicker_instActive = inst; // for delegate hover events
		inst.dpDiv.empty().append(this._generateHTML(inst));
		this._attachHandlers(inst);

		var origyearshtml,
			numMonths = this._getNumberOfMonths(inst),
			cols = numMonths[1],
			width = 17,
			activeCell = inst.dpDiv.find( "." + this._dayOverClass + " a" );

		if ( activeCell.length > 0 ) {
			datepicker_handleMouseover.apply( activeCell.get( 0 ) );
		}

		inst.dpDiv.removeClass("bk-ui-datepicker-multi-2 bk-ui-datepicker-multi-3 bk-ui-datepicker-multi-4").width("");
		if (cols > 1) {
			inst.dpDiv.addClass("bk-ui-datepicker-multi-" + cols).css("width", (width * cols) + "em");
		}
		inst.dpDiv[(numMonths[0] !== 1 || numMonths[1] !== 1 ? "add" : "remove") +
			"Class"]("bk-ui-datepicker-multi");
		inst.dpDiv[(this._get(inst, "isRTL") ? "add" : "remove") +
			"Class"]("bk-ui-datepicker-rtl");

		if (inst === $.datepicker._curInst && $.datepicker._datepickerShowing && $.datepicker._shouldFocusInput( inst ) ) {
			inst.input.focus();
		}

		// deffered render of the years select (to avoid flashes on Firefox)
		if( inst.yearshtml ){
			origyearshtml = inst.yearshtml;
			setTimeout(function(){
				//assure that inst.yearshtml didn't change.
				if( origyearshtml === inst.yearshtml && inst.yearshtml ){
					inst.dpDiv.find("select.bk-ui-datepicker-year:first").replaceWith(inst.yearshtml);
				}
				origyearshtml = inst.yearshtml = null;
			}, 0);
		}
	},

	// #6694 - don't focus the input if it's already focused
	// this breaks the change event in IE
	// Support: IE and jQuery <1.9
	_shouldFocusInput: function( inst ) {
		return inst.input && inst.input.is( ":visible" ) && !inst.input.is( ":disabled" ) && !inst.input.is( ":focus" );
	},

	/* Check positioning to remain on screen. */
	_checkOffset: function(inst, offset, isFixed) {
		var dpWidth = inst.dpDiv.outerWidth(),
			dpHeight = inst.dpDiv.outerHeight(),
			inputWidth = inst.input ? inst.input.outerWidth() : 0,
			inputHeight = inst.input ? inst.input.outerHeight() : 0,
			viewWidth = document.documentElement.clientWidth + (isFixed ? 0 : $(document).scrollLeft()),
			viewHeight = document.documentElement.clientHeight + (isFixed ? 0 : $(document).scrollTop());

		offset.left -= (this._get(inst, "isRTL") ? (dpWidth - inputWidth) : 0);
		offset.left -= (isFixed && offset.left === inst.input.offset().left) ? $(document).scrollLeft() : 0;
		offset.top -= (isFixed && offset.top === (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0;

		// now check if datepicker is showing outside window viewport - move to a better place if so.
		offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ?
			Math.abs(offset.left + dpWidth - viewWidth) : 0);
		offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ?
			Math.abs(dpHeight + inputHeight) : 0);

		return offset;
	},

	/* Find an object's position on the screen. */
	_findPos: function(obj) {
		var position,
			inst = this._getInst(obj),
			isRTL = this._get(inst, "isRTL");

		while (obj && (obj.type === "hidden" || obj.nodeType !== 1 || $.expr.filters.hidden(obj))) {
			obj = obj[isRTL ? "previousSibling" : "nextSibling"];
		}

		position = $(obj).offset();
		return [position.left, position.top];
	},

	/* Hide the date picker from view.
	 * @param  input  element - the input field attached to the date picker
	 */
	_hideDatepicker: function(input) {
		var showAnim, duration, postProcess, onClose,
			inst = this._curInst;

		if (!inst || (input && inst !== $.data(input, "datepicker"))) {
			return;
		}

		if (this._datepickerShowing) {
			showAnim = this._get(inst, "showAnim");
			duration = this._get(inst, "duration");
			postProcess = function() {
				$.datepicker._tidyDialog(inst);
			};

			// DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed
			if ( $.effects && ( $.effects.effect[ showAnim ] || $.effects[ showAnim ] ) ) {
				inst.dpDiv.hide(showAnim, $.datepicker._get(inst, "showOptions"), duration, postProcess);
			} else {
				inst.dpDiv[(showAnim === "slideDown" ? "slideUp" :
					(showAnim === "fadeIn" ? "fadeOut" : "hide"))]((showAnim ? duration : null), postProcess);
			}

			if (!showAnim) {
				postProcess();
			}
			this._datepickerShowing = false;

			onClose = this._get(inst, "onClose");
			if (onClose) {
				onClose.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ""), inst]);
			}

			this._lastInput = null;
			if (this._inDialog) {
				this._dialogInput.css({ position: "absolute", left: "0", top: "-100px" });
				if ($.blockUI) {
					$.unblockUI();
					$("body").append(this.dpDiv);
				}
			}
			this._inDialog = false;
		}
	},

	/* Tidy up after a dialog display. */
	_tidyDialog: function(inst) {
		inst.dpDiv.removeClass(this._dialogClass).unbind(".bk-ui-datepicker-calendar");
	},

	/* Close date picker if clicked elsewhere. */
	_checkExternalClick: function(event) {
		if (!$.datepicker._curInst) {
			return;
		}

		var $target = $(event.target),
			inst = $.datepicker._getInst($target[0]);

		if ( ( ( $target[0].id !== $.datepicker._mainDivId &&
				$target.parents("#" + $.datepicker._mainDivId).length === 0 &&
				!$target.hasClass($.datepicker.markerClassName) &&
				!$target.closest("." + $.datepicker._triggerClass).length &&
				$.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI) ) ) ||
			( $target.hasClass($.datepicker.markerClassName) && $.datepicker._curInst !== inst ) ) {
				$.datepicker._hideDatepicker();
		}
	},

	/* Adjust one of the date sub-fields. */
	_adjustDate: function(id, offset, period) {
		var target = $(id),
			inst = this._getInst(target[0]);

		if (this._isDisabledDatepicker(target[0])) {
			return;
		}
		this._adjustInstDate(inst, offset +
			(period === "M" ? this._get(inst, "showCurrentAtPos") : 0), // undo positioning
			period);
		this._updateDatepicker(inst);
	},

	/* Action for current link. */
	_gotoToday: function(id) {
		var date,
			target = $(id),
			inst = this._getInst(target[0]);

		if (this._get(inst, "gotoCurrent") && inst.currentDay) {
			inst.selectedDay = inst.currentDay;
			inst.drawMonth = inst.selectedMonth = inst.currentMonth;
			inst.drawYear = inst.selectedYear = inst.currentYear;
		} else {
			date = new Date();
			inst.selectedDay = date.getDate();
			inst.drawMonth = inst.selectedMonth = date.getMonth();
			inst.drawYear = inst.selectedYear = date.getFullYear();
		}
		this._notifyChange(inst);
		this._adjustDate(target);
	},

	/* Action for selecting a new month/year. */
	_selectMonthYear: function(id, select, period) {
		var target = $(id),
			inst = this._getInst(target[0]);

		inst["selected" + (period === "M" ? "Month" : "Year")] =
		inst["draw" + (period === "M" ? "Month" : "Year")] =
			parseInt(select.options[select.selectedIndex].value,10);

		this._notifyChange(inst);
		this._adjustDate(target);
	},

	/* Action for selecting a day. */
	_selectDay: function(id, month, year, td) {
		var inst,
			target = $(id);

		if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) {
			return;
		}

		inst = this._getInst(target[0]);
		inst.selectedDay = inst.currentDay = $("a", td).html();
		inst.selectedMonth = inst.currentMonth = month;
		inst.selectedYear = inst.currentYear = year;
		this._selectDate(id, this._formatDate(inst,
			inst.currentDay, inst.currentMonth, inst.currentYear));
	},

	/* Erase the input field and hide the date picker. */
	_clearDate: function(id) {
		var target = $(id);
		this._selectDate(target, "");
	},

	/* Update the input field with the selected date. */
	_selectDate: function(id, dateStr) {
		var onSelect,
			target = $(id),
			inst = this._getInst(target[0]);

		dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
		if (inst.input) {
			inst.input.val(dateStr);
		}
		this._updateAlternate(inst);

		onSelect = this._get(inst, "onSelect");
		if (onSelect) {
			onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);  // trigger custom callback
		} else if (inst.input) {
			inst.input.trigger("change"); // fire the change event
		}

		if (inst.inline){
			this._updateDatepicker(inst);
		} else {
			this._hideDatepicker();
			this._lastInput = inst.input[0];
			if (typeof(inst.input[0]) !== "object") {
				inst.input.focus(); // restore focus
			}
			this._lastInput = null;
		}
	},

	/* Update any alternate field to synchronise with the main field. */
	_updateAlternate: function(inst) {
		var altFormat, date, dateStr,
			altField = this._get(inst, "altField");

		if (altField) { // update alternate field too
			altFormat = this._get(inst, "altFormat") || this._get(inst, "dateFormat");
			date = this._getDate(inst);
			dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst));
			$(altField).each(function() { $(this).val(dateStr); });
		}
	},

	/* Set as beforeShowDay function to prevent selection of weekends.
	 * @param  date  Date - the date to customise
	 * @return [boolean, string] - is this date selectable?, what is its CSS class?
	 */
	noWeekends: function(date) {
		var day = date.getDay();
		return [(day > 0 && day < 6), ""];
	},

	/* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
	 * @param  date  Date - the date to get the week for
	 * @return  number - the number of the week within the year that contains this date
	 */
	iso8601Week: function(date) {
		var time,
			checkDate = new Date(date.getTime());

		// Find Thursday of this week starting on Monday
		checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));

		time = checkDate.getTime();
		checkDate.setMonth(0); // Compare with Jan 1
		checkDate.setDate(1);
		return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
	},

	/* Parse a string value into a date object.
	 * See formatDate below for the possible formats.
	 *
	 * @param  format string - the expected format of the date
	 * @param  value string - the date in the above format
	 * @param  settings Object - attributes include:
	 *					shortYearCutoff  number - the cutoff year for determining the century (optional)
	 *					dayNamesShort	string[7] - abbreviated names of the days from Sunday (optional)
	 *					dayNames		string[7] - names of the days from Sunday (optional)
	 *					monthNamesShort string[12] - abbreviated names of the months (optional)
	 *					monthNames		string[12] - names of the months (optional)
	 * @return  Date - the extracted date value or null if value is blank
	 */
	parseDate: function (format, value, settings) {
		if (format == null || value == null) {
			throw "Invalid arguments";
		}

		value = (typeof value === "object" ? value.toString() : value + "");
		if (value === "") {
			return null;
		}

		var iFormat, dim, extra,
			iValue = 0,
			shortYearCutoffTemp = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff,
			shortYearCutoff = (typeof shortYearCutoffTemp !== "string" ? shortYearCutoffTemp :
				new Date().getFullYear() % 100 + parseInt(shortYearCutoffTemp, 10)),
			dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort,
			dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames,
			monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort,
			monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames,
			year = -1,
			month = -1,
			day = -1,
			doy = -1,
			literal = false,
			date,
			// Check whether a format character is doubled
			lookAhead = function(match) {
				var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
				if (matches) {
					iFormat++;
				}
				return matches;
			},
			// Extract a number from the string value
			getNumber = function(match) {
				var isDoubled = lookAhead(match),
					size = (match === "@" ? 14 : (match === "!" ? 20 :
					(match === "y" && isDoubled ? 4 : (match === "o" ? 3 : 2)))),
					minSize = (match === "y" ? size : 1),
					digits = new RegExp("^\\d{" + minSize + "," + size + "}"),
					num = value.substring(iValue).match(digits);
				if (!num) {
					throw "Missing number at position " + iValue;
				}
				iValue += num[0].length;
				return parseInt(num[0], 10);
			},
			// Extract a name from the string value and convert to an index
			getName = function(match, shortNames, longNames) {
				var index = -1,
					names = $.map(lookAhead(match) ? longNames : shortNames, function (v, k) {
						return [ [k, v] ];
					}).sort(function (a, b) {
						return -(a[1].length - b[1].length);
					});

				$.each(names, function (i, pair) {
					var name = pair[1];
					if (value.substr(iValue, name.length).toLowerCase() === name.toLowerCase()) {
						index = pair[0];
						iValue += name.length;
						return false;
					}
				});
				if (index !== -1) {
					return index + 1;
				} else {
					throw "Unknown name at position " + iValue;
				}
			},
			// Confirm that a literal character matches the string value
			checkLiteral = function() {
				if (value.charAt(iValue) !== format.charAt(iFormat)) {
					throw "Unexpected literal at position " + iValue;
				}
				iValue++;
			};

		for (iFormat = 0; iFormat < format.length; iFormat++) {
			if (literal) {
				if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
					literal = false;
				} else {
					checkLiteral();
				}
			} else {
				switch (format.charAt(iFormat)) {
					case "d":
						day = getNumber("d");
						break;
					case "D":
						getName("D", dayNamesShort, dayNames);
						break;
					case "o":
						doy = getNumber("o");
						break;
					case "m":
						month = getNumber("m");
						break;
					case "M":
						month = getName("M", monthNamesShort, monthNames);
						break;
					case "y":
						year = getNumber("y");
						break;
					case "@":
						date = new Date(getNumber("@"));
						year = date.getFullYear();
						month = date.getMonth() + 1;
						day = date.getDate();
						break;
					case "!":
						date = new Date((getNumber("!") - this._ticksTo1970) / 10000);
						year = date.getFullYear();
						month = date.getMonth() + 1;
						day = date.getDate();
						break;
					case "'":
						if (lookAhead("'")){
							checkLiteral();
						} else {
							literal = true;
						}
						break;
					default:
						checkLiteral();
				}
			}
		}

		if (iValue < value.length){
			extra = value.substr(iValue);
			if (!/^\s+/.test(extra)) {
				throw "Extra/unparsed characters found in date: " + extra;
			}
		}

		if (year === -1) {
			year = new Date().getFullYear();
		} else if (year < 100) {
			year += new Date().getFullYear() - new Date().getFullYear() % 100 +
				(year <= shortYearCutoff ? 0 : -100);
		}

		if (doy > -1) {
			month = 1;
			day = doy;
			do {
				dim = this._getDaysInMonth(year, month - 1);
				if (day <= dim) {
					break;
				}
				month++;
				day -= dim;
			} while (true);
		}

		date = this._daylightSavingAdjust(new Date(year, month - 1, day));
		if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) {
			throw "Invalid date"; // E.g. 31/02/00
		}
		return date;
	},

	/* Standard date formats. */
	ATOM: "yy-mm-dd", // RFC 3339 (ISO 8601)
	COOKIE: "D, dd M yy",
	ISO_8601: "yy-mm-dd",
	RFC_822: "D, d M y",
	RFC_850: "DD, dd-M-y",
	RFC_1036: "D, d M y",
	RFC_1123: "D, d M yy",
	RFC_2822: "D, d M yy",
	RSS: "D, d M y", // RFC 822
	TICKS: "!",
	TIMESTAMP: "@",
	W3C: "yy-mm-dd", // ISO 8601

	_ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) +
		Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000),

	/* Format a date object into a string value.
	 * The format can be combinations of the following:
	 * d  - day of month (no leading zero)
	 * dd - day of month (two digit)
	 * o  - day of year (no leading zeros)
	 * oo - day of year (three digit)
	 * D  - day name short
	 * DD - day name long
	 * m  - month of year (no leading zero)
	 * mm - month of year (two digit)
	 * M  - month name short
	 * MM - month name long
	 * y  - year (two digit)
	 * yy - year (four digit)
	 * @ - Unix timestamp (ms since 01/01/1970)
	 * ! - Windows ticks (100ns since 01/01/0001)
	 * "..." - literal text
	 * '' - single quote
	 *
	 * @param  format string - the desired format of the date
	 * @param  date Date - the date value to format
	 * @param  settings Object - attributes include:
	 *					dayNamesShort	string[7] - abbreviated names of the days from Sunday (optional)
	 *					dayNames		string[7] - names of the days from Sunday (optional)
	 *					monthNamesShort string[12] - abbreviated names of the months (optional)
	 *					monthNames		string[12] - names of the months (optional)
	 * @return  string - the date in the above format
	 */
	formatDate: function (format, date, settings) {
		if (!date) {
			return "";
		}

		var iFormat,
			dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort,
			dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames,
			monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort,
			monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames,
			// Check whether a format character is doubled
			lookAhead = function(match) {
				var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
				if (matches) {
					iFormat++;
				}
				return matches;
			},
			// Format a number, with leading zero if necessary
			formatNumber = function(match, value, len) {
				var num = "" + value;
				if (lookAhead(match)) {
					while (num.length < len) {
						num = "0" + num;
					}
				}
				return num;
			},
			// Format a name, short or long as requested
			formatName = function(match, value, shortNames, longNames) {
				return (lookAhead(match) ? longNames[value] : shortNames[value]);
			},
			output = "",
			literal = false;

		if (date) {
			for (iFormat = 0; iFormat < format.length; iFormat++) {
				if (literal) {
					if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
						literal = false;
					} else {
						output += format.charAt(iFormat);
					}
				} else {
					switch (format.charAt(iFormat)) {
						case "d":
							output += formatNumber("d", date.getDate(), 2);
							break;
						case "D":
							output += formatName("D", date.getDay(), dayNamesShort, dayNames);
							break;
						case "o":
							output += formatNumber("o",
								Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3);
							break;
						case "m":
							output += formatNumber("m", date.getMonth() + 1, 2);
							break;
						case "M":
							output += formatName("M", date.getMonth(), monthNamesShort, monthNames);
							break;
						case "y":
							output += (lookAhead("y") ? date.getFullYear() :
								(date.getYear() % 100 < 10 ? "0" : "") + date.getYear() % 100);
							break;
						case "@":
							output += date.getTime();
							break;
						case "!":
							output += date.getTime() * 10000 + this._ticksTo1970;
							break;
						case "'":
							if (lookAhead("'")) {
								output += "'";
							} else {
								literal = true;
							}
							break;
						default:
							output += format.charAt(iFormat);
					}
				}
			}
		}
		return output;
	},

	/* Extract all possible characters from the date format. */
	_possibleChars: function (format) {
		var iFormat,
			chars = "",
			literal = false,
			// Check whether a format character is doubled
			lookAhead = function(match) {
				var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
				if (matches) {
					iFormat++;
				}
				return matches;
			};

		for (iFormat = 0; iFormat < format.length; iFormat++) {
			if (literal) {
				if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
					literal = false;
				} else {
					chars += format.charAt(iFormat);
				}
			} else {
				switch (format.charAt(iFormat)) {
					case "d": case "m": case "y": case "@":
						chars += "0123456789";
						break;
					case "D": case "M":
						return null; // Accept anything
					case "'":
						if (lookAhead("'")) {
							chars += "'";
						} else {
							literal = true;
						}
						break;
					default:
						chars += format.charAt(iFormat);
				}
			}
		}
		return chars;
	},

	/* Get a setting value, defaulting if necessary. */
	_get: function(inst, name) {
		return inst.settings[name] !== undefined ?
			inst.settings[name] : this._defaults[name];
	},

	/* Parse existing date and initialise date picker. */
	_setDateFromField: function(inst, noDefault) {
		if (inst.input.val() === inst.lastVal) {
			return;
		}

		var dateFormat = this._get(inst, "dateFormat"),
			dates = inst.lastVal = inst.input ? inst.input.val() : null,
			defaultDate = this._getDefaultDate(inst),
			date = defaultDate,
			settings = this._getFormatConfig(inst);

		try {
			date = this.parseDate(dateFormat, dates, settings) || defaultDate;
		} catch (event) {
			dates = (noDefault ? "" : dates);
		}
		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		inst.currentDay = (dates ? date.getDate() : 0);
		inst.currentMonth = (dates ? date.getMonth() : 0);
		inst.currentYear = (dates ? date.getFullYear() : 0);
		this._adjustInstDate(inst);
	},

	/* Retrieve the default date shown on opening. */
	_getDefaultDate: function(inst) {
		return this._restrictMinMax(inst,
			this._determineDate(inst, this._get(inst, "defaultDate"), new Date()));
	},

	/* A date may be specified as an exact value or a relative one. */
	_determineDate: function(inst, date, defaultDate) {
		var offsetNumeric = function(offset) {
				var date = new Date();
				date.setDate(date.getDate() + offset);
				return date;
			},
			offsetString = function(offset) {
				try {
					return $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"),
						offset, $.datepicker._getFormatConfig(inst));
				}
				catch (e) {
					// Ignore
				}

				var date = (offset.toLowerCase().match(/^c/) ?
					$.datepicker._getDate(inst) : null) || new Date(),
					year = date.getFullYear(),
					month = date.getMonth(),
					day = date.getDate(),
					pattern = /([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,
					matches = pattern.exec(offset);

				while (matches) {
					switch (matches[2] || "d") {
						case "d" : case "D" :
							day += parseInt(matches[1],10); break;
						case "w" : case "W" :
							day += parseInt(matches[1],10) * 7; break;
						case "m" : case "M" :
							month += parseInt(matches[1],10);
							day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
							break;
						case "y": case "Y" :
							year += parseInt(matches[1],10);
							day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
							break;
					}
					matches = pattern.exec(offset);
				}
				return new Date(year, month, day);
			},
			newDate = (date == null || date === "" ? defaultDate : (typeof date === "string" ? offsetString(date) :
				(typeof date === "number" ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime()))));

		newDate = (newDate && newDate.toString() === "Invalid Date" ? defaultDate : newDate);
		if (newDate) {
			newDate.setHours(0);
			newDate.setMinutes(0);
			newDate.setSeconds(0);
			newDate.setMilliseconds(0);
		}
		return this._daylightSavingAdjust(newDate);
	},

	/* Handle switch to/from daylight saving.
	 * Hours may be non-zero on daylight saving cut-over:
	 * > 12 when midnight changeover, but then cannot generate
	 * midnight datetime, so jump to 1AM, otherwise reset.
	 * @param  date  (Date) the date to check
	 * @return  (Date) the corrected date
	 */
	_daylightSavingAdjust: function(date) {
		if (!date) {
			return null;
		}
		date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
		return date;
	},

	/* Set the date(s) directly. */
	_setDate: function(inst, date, noChange) {
		var clear = !date,
			origMonth = inst.selectedMonth,
			origYear = inst.selectedYear,
			newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date()));

		inst.selectedDay = inst.currentDay = newDate.getDate();
		inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth();
		inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear();
		if ((origMonth !== inst.selectedMonth || origYear !== inst.selectedYear) && !noChange) {
			this._notifyChange(inst);
		}
		this._adjustInstDate(inst);
		if (inst.input) {
			inst.input.val(clear ? "" : this._formatDate(inst));
		}
	},

	/* Retrieve the date(s) directly. */
	_getDate: function(inst) {
		var startDate = (!inst.currentYear || (inst.input && inst.input.val() === "") ? null :
			this._daylightSavingAdjust(new Date(
			inst.currentYear, inst.currentMonth, inst.currentDay)));
			return startDate;
	},

	/* Attach the onxxx handlers.  These are declared statically so
	 * they work with static code transformers like Caja.
	 */
	_attachHandlers: function(inst) {
		var stepMonths = this._get(inst, "stepMonths"),
			id = "#" + inst.id.replace( /\\\\/g, "\\" );
		inst.dpDiv.find("[data-handler]").map(function () {
			var handler = {
				prev: function () {
					$.datepicker._adjustDate(id, -stepMonths, "M");
				},
				next: function () {
					$.datepicker._adjustDate(id, +stepMonths, "M");
				},
				hide: function () {
					$.datepicker._hideDatepicker();
				},
				today: function () {
					$.datepicker._gotoToday(id);
				},
				selectDay: function () {
					$.datepicker._selectDay(id, +this.getAttribute("data-month"), +this.getAttribute("data-year"), this);
					return false;
				},
				selectMonth: function () {
					$.datepicker._selectMonthYear(id, this, "M");
					return false;
				},
				selectYear: function () {
					$.datepicker._selectMonthYear(id, this, "Y");
					return false;
				}
			};
			$(this).bind(this.getAttribute("data-event"), handler[this.getAttribute("data-handler")]);
		});
	},

	/* Generate the HTML for the current state of the date picker. */
	_generateHTML: function(inst) {
		var maxDraw, prevText, prev, nextText, next, currentText, gotoDate,
			controls, buttonPanel, firstDay, showWeek, dayNames, dayNamesMin,
			monthNames, monthNamesShort, beforeShowDay, showOtherMonths,
			selectOtherMonths, defaultDate, html, dow, row, group, col, selectedDate,
			cornerClass, calender, thead, day, daysInMonth, leadDays, curRows, numRows,
			printDate, dRow, tbody, daySettings, otherMonth, unselectable,
			tempDate = new Date(),
			today = this._daylightSavingAdjust(
				new Date(tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate())), // clear time
			isRTL = this._get(inst, "isRTL"),
			showButtonPanel = this._get(inst, "showButtonPanel"),
			hideIfNoPrevNext = this._get(inst, "hideIfNoPrevNext"),
			navigationAsDateFormat = this._get(inst, "navigationAsDateFormat"),
			numMonths = this._getNumberOfMonths(inst),
			showCurrentAtPos = this._get(inst, "showCurrentAtPos"),
			stepMonths = this._get(inst, "stepMonths"),
			isMultiMonth = (numMonths[0] !== 1 || numMonths[1] !== 1),
			currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) :
				new Date(inst.currentYear, inst.currentMonth, inst.currentDay))),
			minDate = this._getMinMaxDate(inst, "min"),
			maxDate = this._getMinMaxDate(inst, "max"),
			drawMonth = inst.drawMonth - showCurrentAtPos,
			drawYear = inst.drawYear;

		if (drawMonth < 0) {
			drawMonth += 12;
			drawYear--;
		}
		if (maxDate) {
			maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(),
				maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate()));
			maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
			while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) {
				drawMonth--;
				if (drawMonth < 0) {
					drawMonth = 11;
					drawYear--;
				}
			}
		}
		inst.drawMonth = drawMonth;
		inst.drawYear = drawYear;

		prevText = this._get(inst, "prevText");
		prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText,
			this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)),
			this._getFormatConfig(inst)));

		prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ?
			"<a class='bk-ui-datepicker-prev bk-ui-corner-all' data-handler='prev' data-event='click'" +
			" title='" + prevText + "'><span class='bk-ui-icon bk-ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>" :
			(hideIfNoPrevNext ? "" : "<a class='bk-ui-datepicker-prev bk-ui-corner-all bk-ui-state-disabled' title='"+ prevText +"'><span class='bk-ui-icon bk-ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>"));

		nextText = this._get(inst, "nextText");
		nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
			this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)),
			this._getFormatConfig(inst)));

		next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ?
			"<a class='bk-ui-datepicker-next bk-ui-corner-all' data-handler='next' data-event='click'" +
			" title='" + nextText + "'><span class='bk-ui-icon bk-ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>" :
			(hideIfNoPrevNext ? "" : "<a class='bk-ui-datepicker-next bk-ui-corner-all bk-ui-state-disabled' title='"+ nextText + "'><span class='bk-ui-icon bk-ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>"));

		currentText = this._get(inst, "currentText");
		gotoDate = (this._get(inst, "gotoCurrent") && inst.currentDay ? currentDate : today);
		currentText = (!navigationAsDateFormat ? currentText :
			this.formatDate(currentText, gotoDate, this._getFormatConfig(inst)));

		controls = (!inst.inline ? "<button type='button' class='bk-ui-datepicker-close bk-ui-state-default bk-ui-priority-primary bk-ui-corner-all' data-handler='hide' data-event='click'>" +
			this._get(inst, "closeText") + "</button>" : "");

		buttonPanel = (showButtonPanel) ? "<div class='bk-ui-datepicker-buttonpane bk-ui-widget-content'>" + (isRTL ? controls : "") +
			(this._isInRange(inst, gotoDate) ? "<button type='button' class='bk-ui-datepicker-current bk-ui-state-default bk-ui-priority-secondary bk-ui-corner-all' data-handler='today' data-event='click'" +
			">" + currentText + "</button>" : "") + (isRTL ? "" : controls) + "</div>" : "";

		firstDay = parseInt(this._get(inst, "firstDay"),10);
		firstDay = (isNaN(firstDay) ? 0 : firstDay);

		showWeek = this._get(inst, "showWeek");
		dayNames = this._get(inst, "dayNames");
		dayNamesMin = this._get(inst, "dayNamesMin");
		monthNames = this._get(inst, "monthNames");
		monthNamesShort = this._get(inst, "monthNamesShort");
		beforeShowDay = this._get(inst, "beforeShowDay");
		showOtherMonths = this._get(inst, "showOtherMonths");
		selectOtherMonths = this._get(inst, "selectOtherMonths");
		defaultDate = this._getDefaultDate(inst);
		html = "";
		dow;
		for (row = 0; row < numMonths[0]; row++) {
			group = "";
			this.maxRows = 4;
			for (col = 0; col < numMonths[1]; col++) {
				selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay));
				cornerClass = " bk-ui-corner-all";
				calender = "";
				if (isMultiMonth) {
					calender += "<div class='bk-ui-datepicker-group";
					if (numMonths[1] > 1) {
						switch (col) {
							case 0: calender += " bk-ui-datepicker-group-first";
								cornerClass = " bk-ui-corner-" + (isRTL ? "right" : "left"); break;
							case numMonths[1]-1: calender += " bk-ui-datepicker-group-last";
								cornerClass = " bk-ui-corner-" + (isRTL ? "left" : "right"); break;
							default: calender += " bk-ui-datepicker-group-middle"; cornerClass = ""; break;
						}
					}
					calender += "'>";
				}
				calender += "<div class='bk-ui-datepicker-header bk-ui-widget-header bk-ui-helper-clearfix" + cornerClass + "'>" +
					(/all|left/.test(cornerClass) && row === 0 ? (isRTL ? next : prev) : "") +
					(/all|right/.test(cornerClass) && row === 0 ? (isRTL ? prev : next) : "") +
					this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate,
					row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers
					"</div><table class='bk-ui-datepicker-calendar'><thead>" +
					"<tr>";
				thead = (showWeek ? "<th class='bk-ui-datepicker-week-col'>" + this._get(inst, "weekHeader") + "</th>" : "");
				for (dow = 0; dow < 7; dow++) { // days of the week
					day = (dow + firstDay) % 7;
					thead += "<th scope='col'" + ((dow + firstDay + 6) % 7 >= 5 ? " class='bk-ui-datepicker-week-end'" : "") + ">" +
						"<span title='" + dayNames[day] + "'>" + dayNamesMin[day] + "</span></th>";
				}
				calender += thead + "</tr></thead><tbody>";
				daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
				if (drawYear === inst.selectedYear && drawMonth === inst.selectedMonth) {
					inst.selectedDay = Math.min(inst.selectedDay, daysInMonth);
				}
				leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
				curRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate
				numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043)
				this.maxRows = numRows;
				printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays));
				for (dRow = 0; dRow < numRows; dRow++) { // create date picker rows
					calender += "<tr>";
					tbody = (!showWeek ? "" : "<td class='bk-ui-datepicker-week-col'>" +
						this._get(inst, "calculateWeek")(printDate) + "</td>");
					for (dow = 0; dow < 7; dow++) { // create date picker days
						daySettings = (beforeShowDay ?
							beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, ""]);
						otherMonth = (printDate.getMonth() !== drawMonth);
						unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] ||
							(minDate && printDate < minDate) || (maxDate && printDate > maxDate);
						tbody += "<td class='" +
							((dow + firstDay + 6) % 7 >= 5 ? " bk-ui-datepicker-week-end" : "") + // highlight weekends
							(otherMonth ? " bk-ui-datepicker-other-month" : "") + // highlight days from other months
							((printDate.getTime() === selectedDate.getTime() && drawMonth === inst.selectedMonth && inst._keyEvent) || // user pressed key
							(defaultDate.getTime() === printDate.getTime() && defaultDate.getTime() === selectedDate.getTime()) ?
							// or defaultDate is current printedDate and defaultDate is selectedDate
							" " + this._dayOverClass : "") + // highlight selected day
							(unselectable ? " " + this._unselectableClass + " bk-ui-state-disabled": "") +  // highlight unselectable days
							(otherMonth && !showOtherMonths ? "" : " " + daySettings[1] + // highlight custom dates
							(printDate.getTime() === currentDate.getTime() ? " " + this._currentClass : "") + // highlight selected day
							(printDate.getTime() === today.getTime() ? " bk-ui-datepicker-today" : "")) + "'" + // highlight today (if different)
							((!otherMonth || showOtherMonths) && daySettings[2] ? " title='" + daySettings[2].replace(/'/g, "&#39;") + "'" : "") + // cell title
							(unselectable ? "" : " data-handler='selectDay' data-event='click' data-month='" + printDate.getMonth() + "' data-year='" + printDate.getFullYear() + "'") + ">" + // actions
							(otherMonth && !showOtherMonths ? "&#xa0;" : // display for other months
							(unselectable ? "<span class='bk-ui-state-default'>" + printDate.getDate() + "</span>" : "<a class='bk-ui-state-default" +
							(printDate.getTime() === today.getTime() ? " bk-ui-state-highlight" : "") +
							(printDate.getTime() === currentDate.getTime() ? " bk-ui-state-active" : "") + // highlight selected day
							(otherMonth ? " bk-ui-priority-secondary" : "") + // distinguish dates from other months
							"' href='#'>" + printDate.getDate() + "</a>")) + "</td>"; // display selectable date
						printDate.setDate(printDate.getDate() + 1);
						printDate = this._daylightSavingAdjust(printDate);
					}
					calender += tbody + "</tr>";
				}
				drawMonth++;
				if (drawMonth > 11) {
					drawMonth = 0;
					drawYear++;
				}
				calender += "</tbody></table>" + (isMultiMonth ? "</div>" +
							((numMonths[0] > 0 && col === numMonths[1]-1) ? "<div class='bk-ui-datepicker-row-break'></div>" : "") : "");
				group += calender;
			}
			html += group;
		}
		html += buttonPanel;
		inst._keyEvent = false;
		return html;
	},

	/* Generate the month and year header. */
	_generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate,
			secondary, monthNames, monthNamesShort) {

		var inMinYear, inMaxYear, month, years, thisYear, determineYear, year, endYear,
			changeMonth = this._get(inst, "changeMonth"),
			changeYear = this._get(inst, "changeYear"),
			showMonthAfterYear = this._get(inst, "showMonthAfterYear"),
			html = "<div class='bk-ui-datepicker-title'>",
			monthHtml = "";

		// month selection
		if (secondary || !changeMonth) {
			monthHtml += "<span class='bk-ui-datepicker-month'>" + monthNames[drawMonth] + "</span>";
		} else {
			inMinYear = (minDate && minDate.getFullYear() === drawYear);
			inMaxYear = (maxDate && maxDate.getFullYear() === drawYear);
			monthHtml += "<select class='bk-ui-datepicker-month' data-handler='selectMonth' data-event='change'>";
			for ( month = 0; month < 12; month++) {
				if ((!inMinYear || month >= minDate.getMonth()) && (!inMaxYear || month <= maxDate.getMonth())) {
					monthHtml += "<option value='" + month + "'" +
						(month === drawMonth ? " selected='selected'" : "") +
						">" + monthNamesShort[month] + "</option>";
				}
			}
			monthHtml += "</select>";
		}

		if (!showMonthAfterYear) {
			html += monthHtml + (secondary || !(changeMonth && changeYear) ? "&#xa0;" : "");
		}

		// year selection
		if ( !inst.yearshtml ) {
			inst.yearshtml = "";
			if (secondary || !changeYear) {
				html += "<span class='bk-ui-datepicker-year'>" + drawYear + "</span>";
			} else {
				// determine range of years to display
				years = this._get(inst, "yearRange").split(":");
				thisYear = new Date().getFullYear();
				determineYear = function(value) {
					var year = (value.match(/c[+\-].*/) ? drawYear + parseInt(value.substring(1), 10) :
						(value.match(/[+\-].*/) ? thisYear + parseInt(value, 10) :
						parseInt(value, 10)));
					return (isNaN(year) ? thisYear : year);
				};
				year = determineYear(years[0]);
				endYear = Math.max(year, determineYear(years[1] || ""));
				year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
				endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
				inst.yearshtml += "<select class='bk-ui-datepicker-year' data-handler='selectYear' data-event='change'>";
				for (; year <= endYear; year++) {
					inst.yearshtml += "<option value='" + year + "'" +
						(year === drawYear ? " selected='selected'" : "") +
						">" + year + "</option>";
				}
				inst.yearshtml += "</select>";

				html += inst.yearshtml;
				inst.yearshtml = null;
			}
		}

		html += this._get(inst, "yearSuffix");
		if (showMonthAfterYear) {
			html += (secondary || !(changeMonth && changeYear) ? "&#xa0;" : "") + monthHtml;
		}
		html += "</div>"; // Close datepicker_header
		return html;
	},

	/* Adjust one of the date sub-fields. */
	_adjustInstDate: function(inst, offset, period) {
		var year = inst.drawYear + (period === "Y" ? offset : 0),
			month = inst.drawMonth + (period === "M" ? offset : 0),
			day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period === "D" ? offset : 0),
			date = this._restrictMinMax(inst, this._daylightSavingAdjust(new Date(year, month, day)));

		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		if (period === "M" || period === "Y") {
			this._notifyChange(inst);
		}
	},

	/* Ensure a date is within any min/max bounds. */
	_restrictMinMax: function(inst, date) {
		var minDate = this._getMinMaxDate(inst, "min"),
			maxDate = this._getMinMaxDate(inst, "max"),
			newDate = (minDate && date < minDate ? minDate : date);
		return (maxDate && newDate > maxDate ? maxDate : newDate);
	},

	/* Notify change of month/year. */
	_notifyChange: function(inst) {
		var onChange = this._get(inst, "onChangeMonthYear");
		if (onChange) {
			onChange.apply((inst.input ? inst.input[0] : null),
				[inst.selectedYear, inst.selectedMonth + 1, inst]);
		}
	},

	/* Determine the number of months to show. */
	_getNumberOfMonths: function(inst) {
		var numMonths = this._get(inst, "numberOfMonths");
		return (numMonths == null ? [1, 1] : (typeof numMonths === "number" ? [1, numMonths] : numMonths));
	},

	/* Determine the current maximum date - ensure no time components are set. */
	_getMinMaxDate: function(inst, minMax) {
		return this._determineDate(inst, this._get(inst, minMax + "Date"), null);
	},

	/* Find the number of days in a given month. */
	_getDaysInMonth: function(year, month) {
		return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate();
	},

	/* Find the day of the week of the first of a month. */
	_getFirstDayOfMonth: function(year, month) {
		return new Date(year, month, 1).getDay();
	},

	/* Determines if we should allow a "next/prev" month display change. */
	_canAdjustMonth: function(inst, offset, curYear, curMonth) {
		var numMonths = this._getNumberOfMonths(inst),
			date = this._daylightSavingAdjust(new Date(curYear,
			curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1));

		if (offset < 0) {
			date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
		}
		return this._isInRange(inst, date);
	},

	/* Is the given date in the accepted range? */
	_isInRange: function(inst, date) {
		var yearSplit, currentYear,
			minDate = this._getMinMaxDate(inst, "min"),
			maxDate = this._getMinMaxDate(inst, "max"),
			minYear = null,
			maxYear = null,
			years = this._get(inst, "yearRange");
			if (years){
				yearSplit = years.split(":");
				currentYear = new Date().getFullYear();
				minYear = parseInt(yearSplit[0], 10);
				maxYear = parseInt(yearSplit[1], 10);
				if ( yearSplit[0].match(/[+\-].*/) ) {
					minYear += currentYear;
				}
				if ( yearSplit[1].match(/[+\-].*/) ) {
					maxYear += currentYear;
				}
			}

		return ((!minDate || date.getTime() >= minDate.getTime()) &&
			(!maxDate || date.getTime() <= maxDate.getTime()) &&
			(!minYear || date.getFullYear() >= minYear) &&
			(!maxYear || date.getFullYear() <= maxYear));
	},

	/* Provide the configuration settings for formatting/parsing. */
	_getFormatConfig: function(inst) {
		var shortYearCutoff = this._get(inst, "shortYearCutoff");
		shortYearCutoff = (typeof shortYearCutoff !== "string" ? shortYearCutoff :
			new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
		return {shortYearCutoff: shortYearCutoff,
			dayNamesShort: this._get(inst, "dayNamesShort"), dayNames: this._get(inst, "dayNames"),
			monthNamesShort: this._get(inst, "monthNamesShort"), monthNames: this._get(inst, "monthNames")};
	},

	/* Format the given date for display. */
	_formatDate: function(inst, day, month, year) {
		if (!day) {
			inst.currentDay = inst.selectedDay;
			inst.currentMonth = inst.selectedMonth;
			inst.currentYear = inst.selectedYear;
		}
		var date = (day ? (typeof day === "object" ? day :
			this._daylightSavingAdjust(new Date(year, month, day))) :
			this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
		return this.formatDate(this._get(inst, "dateFormat"), date, this._getFormatConfig(inst));
	}
});

/*
 * Bind hover events for datepicker elements.
 * Done via delegate so the binding only occurs once in the lifetime of the parent div.
 * Global datepicker_instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker.
 */
function datepicker_bindHover(dpDiv) {
	var selector = "button, .bk-ui-datepicker-prev, .bk-ui-datepicker-next, .bk-ui-datepicker-calendar td a";
	return dpDiv.delegate(selector, "mouseout", function() {
			$(this).removeClass("bk-ui-state-hover");
			if (this.className.indexOf("bk-ui-datepicker-prev") !== -1) {
				$(this).removeClass("bk-ui-datepicker-prev-hover");
			}
			if (this.className.indexOf("bk-ui-datepicker-next") !== -1) {
				$(this).removeClass("bk-ui-datepicker-next-hover");
			}
		})
		.delegate( selector, "mouseover", datepicker_handleMouseover );
}

function datepicker_handleMouseover() {
	if (!$.datepicker._isDisabledDatepicker( datepicker_instActive.inline? datepicker_instActive.dpDiv.parent()[0] : datepicker_instActive.input[0])) {
		$(this).parents(".bk-ui-datepicker-calendar").find("a").removeClass("bk-ui-state-hover");
		$(this).addClass("bk-ui-state-hover");
		if (this.className.indexOf("bk-ui-datepicker-prev") !== -1) {
			$(this).addClass("bk-ui-datepicker-prev-hover");
		}
		if (this.className.indexOf("bk-ui-datepicker-next") !== -1) {
			$(this).addClass("bk-ui-datepicker-next-hover");
		}
	}
}

/* jQuery extend now ignores nulls! */
function datepicker_extendRemove(target, props) {
	$.extend(target, props);
	for (var name in props) {
		if (props[name] == null) {
			target[name] = props[name];
		}
	}
	return target;
}

/* Invoke the datepicker functionality.
   @param  options  string - a command, optionally followed by additional parameters or
					Object - settings for attaching new datepicker functionality
   @return  jQuery object */
$.fn.datepicker = function(options){

	/* Verify an empty collection wasn't passed - Fixes #6976 */
	if ( !this.length ) {
		return this;
	}

	/* Initialise the date picker. */
	if (!$.datepicker.initialized) {
		$(document).mousedown($.datepicker._checkExternalClick);
		$.datepicker.initialized = true;
	}

	/* Append datepicker main container to body if not exist. */
	if ($("#"+$.datepicker._mainDivId).length === 0) {
		$("body").append($.datepicker.dpDiv);
	}

	var otherArgs = Array.prototype.slice.call(arguments, 1);
	if (typeof options === "string" && (options === "isDisabled" || options === "getDate" || options === "widget")) {
		return $.datepicker["_" + options + "Datepicker"].
			apply($.datepicker, [this[0]].concat(otherArgs));
	}
	if (options === "option" && arguments.length === 2 && typeof arguments[1] === "string") {
		return $.datepicker["_" + options + "Datepicker"].
			apply($.datepicker, [this[0]].concat(otherArgs));
	}
	return this.each(function() {
		typeof options === "string" ?
			$.datepicker["_" + options + "Datepicker"].
				apply($.datepicker, [this].concat(otherArgs)) :
			$.datepicker._attachDatepicker(this, options);
	});
};

$.datepicker = new Datepicker(); // singleton instance
$.datepicker.initialized = false;
$.datepicker.uuid = new Date().getTime();
$.datepicker.version = "1.11.2";

return $.datepicker;

}));

(function() {
  var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('widget/date_picker',["underscore", "jquery", "jquery_ui/datepicker", "common/collection", "common/continuum_view", "common/has_properties"], function(_, $, $1, Collection, ContinuumView, HasProperties) {
    var DatePicker, DatePickerView, DatePickers, _ref, _ref1, _ref2;
    DatePickerView = (function(_super) {
      __extends(DatePickerView, _super);

      function DatePickerView() {
        this.onSelect = __bind(this.onSelect, this);
        _ref = DatePickerView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

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

      DatePickerView.prototype.render = function() {
        var $datepicker, $label;
        this.$el.empty();
        $label = $('<label>').text(this.mget("title"));
        $datepicker = $("<div>").datepicker({
          defaultDate: new Date(this.mget('value')),
          minDate: this.mget('min_date') != null ? new Date(this.mget('min_date')) : null,
          maxDate: this.mget('max_date') != null ? new Date(this.mget('max_date')) : null,
          onSelect: this.onSelect
        });
        return this.$el.append([$label, $datepicker]);
      };

      DatePickerView.prototype.onSelect = function(dateText, ui) {
        this.mset('value', new Date(dateText));
        return this.model.save();
      };

      return DatePickerView;

    })(ContinuumView);
    DatePicker = (function(_super) {
      __extends(DatePicker, _super);

      function DatePicker() {
        _ref1 = DatePicker.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      DatePicker.prototype.type = "DatePicker";

      DatePicker.prototype.default_view = DatePickerView;

      DatePicker.prototype.defaults = function() {
        return _.extend({}, DatePicker.__super__.defaults.call(this), {
          value: Date.now()
        });
      };

      return DatePicker;

    })(HasProperties);
    DatePickers = (function(_super) {
      __extends(DatePickers, _super);

      function DatePickers() {
        _ref2 = DatePickers.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      DatePickers.prototype.model = DatePicker;

      return DatePickers;

    })(Collection);
    return {
      Model: DatePicker,
      Collection: new DatePickers(),
      View: DatePickerView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=date_picker.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('widget/panel',["underscore", "jquery", "common/collection", "common/continuum_view", "common/has_properties"], function(_, $, Collection, ContinuumView, HasProperties) {
    var Panel, PanelView, Panels, _ref, _ref1, _ref2;
    PanelView = (function(_super) {
      __extends(PanelView, _super);

      function PanelView() {
        _ref = PanelView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

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

      PanelView.prototype.render = function() {
        return this.$el.empty();
      };

      return PanelView;

    })(ContinuumView);
    Panel = (function(_super) {
      __extends(Panel, _super);

      function Panel() {
        _ref1 = Panel.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Panel.prototype.type = "Panel";

      Panel.prototype.default_view = PanelView;

      Panel.prototype.defaults = function() {
        return _.extend({}, Panel.__super__.defaults.call(this), {
          title: "",
          child: null,
          closable: false
        });
      };

      return Panel;

    })(HasProperties);
    Panels = (function(_super) {
      __extends(Panels, _super);

      function Panels() {
        _ref2 = Panels.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Panels.prototype.model = Panel;

      return Panels;

    })(Collection);
    return {
      Model: Panel,
      Collection: new Panels(),
      View: PanelView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=panel.js.map
*/;
define('bootstrap/tab',["jquery"], function(jQuery) {

/* ========================================================================
 * Bootstrap: tab.js v3.1.1
 * http://getbootstrap.com/javascript/#tabs
 * ========================================================================
 * Copyright 2011-2014 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
  

  // TAB CLASS DEFINITION
  // ====================

  var Tab = function (element) {
    this.element = $(element)
  }

  Tab.prototype.show = function () {
    var $this    = this.element
    var $ul      = $this.closest('ul:not(.bk-bs-dropdown-menu)')
    var selector = $this.data('bk-bs-target')

    if (!selector) {
      selector = $this.attr('href')
      selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
    }

    if ($this.parent('li').hasClass('bk-bs-active')) return

    var previous = $ul.find('.bk-bs-active:last a')[0]
    var e        = $.Event('show.bk-bs.tab', {
      relatedTarget: previous
    })

    $this.trigger(e)

    if (e.isDefaultPrevented()) return

    var $target = $(selector)

    this.activate($this.parent('li'), $ul)
    this.activate($target, $target.parent(), function () {
      $this.trigger({
        type: 'shown.bk-bs.tab',
        relatedTarget: previous
      })
    })
  }

  Tab.prototype.activate = function (element, container, callback) {
    var $active    = container.find('> .bk-bs-active')
    var transition = callback
      && $.support.transition
      && $active.hasClass('bk-bs-fade')

    function next() {
      $active
        .removeClass('bk-bs-active')
        .find('> .bk-bs-dropdown-menu > .bk-bs-active')
        .removeClass('bk-bs-active')

      element.addClass('bk-bs-active')

      if (transition) {
        element[0].offsetWidth // reflow for transition
        element.addClass('bk-bs-in')
      } else {
        element.removeClass('bk-bs-fade')
      }

      if (element.parent('.bk-bs-dropdown-menu')) {
        element.closest('li.bk-bs-dropdown').addClass('bk-bs-active')
      }

      callback && callback()
    }

    transition ?
      $active
        .one($.support.transition.end, next)
        .emulateTransitionEnd(150) :
      next()

    $active.removeClass('bk-bs-in')
  }


  // TAB PLUGIN DEFINITION
  // =====================

  var old = $.fn.tab

  $.fn.tab = function ( option ) {
    return this.each(function () {
      var $this = $(this)
      var data  = $this.data('bk-bs.tab')

      if (!data) $this.data('bk-bs.tab', (data = new Tab(this)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.tab.Constructor = Tab


  // TAB NO CONFLICT
  // ===============

  $.fn.tab.noConflict = function () {
    $.fn.tab = old
    return this
  }


  // TAB DATA-API
  // ============

  $(document).on('click.bk-bs.tab.data-api', '[data-bk-bs-toggle="tab"], [data-bk-bs-toggle="pill"]', function (e) {
    e.preventDefault()
    $(this).tab('show')
  })

}(jQuery);

});

define('widget/tabs_template',[],function(){
  var template = function(__obj) {
  var _safe = function(value) {
    if (typeof value === 'undefined' && value == null)
      value = '';
    var result = new String(value);
    result.ecoSafe = true;
    return result;
  };
  return (function() {
    var __out = [], __self = this, _print = function(value) {
      if (typeof value !== 'undefined' && value != null)
        __out.push(value.ecoSafe ? value : __self.escape(value));
    }, _capture = function(callback) {
      var out = __out, result;
      __out = [];
      callback.call(this);
      result = __out.join('');
      __out = out;
      return _safe(result);
    };
    (function() {
      var i, tab, _i, _j, _len, _len1, _ref, _ref1;
    
      _print(_safe('<ul class="bk-bs-nav bk-bs-nav-tabs">\n  '));
    
      _ref = this.tabs;
      for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
        tab = _ref[i];
        _print(_safe('\n    <li class="'));
        _print(this.active(i));
        _print(_safe('">\n      <a href="#tab-'));
        _print(tab.get('id'));
        _print(_safe('">'));
        _print(tab.get('title'));
        _print(_safe('</a>\n    </li>\n  '));
      }
    
      _print(_safe('\n</ul>\n<div class="bk-bs-tab-content">\n  '));
    
      _ref1 = this.tabs;
      for (i = _j = 0, _len1 = _ref1.length; _j < _len1; i = ++_j) {
        tab = _ref1[i];
        _print(_safe('\n    <div class="bk-bs-tab-pane '));
        _print(this.active(i));
        _print(_safe('" id="tab-'));
        _print(tab.get('id'));
        _print(_safe('"></div>\n  '));
      }
    
      _print(_safe('\n</div>\n'));
    
    }).call(this);
    
    return __out.join('');
  }).call((function() {
    var obj = {
      escape: function(value) {
        return ('' + value)
          .replace(/&/g, '&amp;')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;')
          .replace(/"/g, '&quot;');
      },
      safe: _safe
    }, key;
    for (key in __obj) obj[key] = __obj[key];
    return obj;
  })());
};
  return template;
});

(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('widget/tabs',["underscore", "jquery", "bootstrap/tab", "common/collection", "common/continuum_view", "common/has_properties", "common/build_views", "./tabs_template"], function(_, $, $1, Collection, ContinuumView, HasProperties, build_views, tabs_template) {
    var Tabs, TabsView, Tabses, _ref, _ref1, _ref2;
    TabsView = (function(_super) {
      __extends(TabsView, _super);

      function TabsView() {
        _ref = TabsView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

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

      TabsView.prototype.render = function() {
        var $panels, active, child, children, html, key, panel, tab, tabs, val, _i, _len, _ref1, _ref2, _ref3;
        _ref1 = this.views;
        for (key in _ref1) {
          if (!__hasProp.call(_ref1, key)) continue;
          val = _ref1[key];
          val.$el.detach();
        }
        this.$el.empty();
        tabs = this.mget('tabs');
        active = this.mget("active");
        children = (function() {
          var _i, _len, _results;
          _results = [];
          for (_i = 0, _len = tabs.length; _i < _len; _i++) {
            tab = tabs[_i];
            _results.push(tab.get("child"));
          }
          return _results;
        })();
        build_views(this.views, children);
        html = $(tabs_template({
          tabs: tabs,
          active: function(i) {
            if (i === active) {
              return 'bk-bs-active';
            } else {
              return '';
            }
          }
        }));
        html.find("> li > a").click(function(event) {
          event.preventDefault();
          return $(this).tab('show');
        });
        $panels = html.children(".bk-bs-tab-pane");
        _ref2 = _.zip(children, $panels);
        for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
          _ref3 = _ref2[_i], child = _ref3[0], panel = _ref3[1];
          $(panel).html(this.views[child.id].$el);
        }
        this.$el.append(html);
        return this.$el.tabs;
      };

      return TabsView;

    })(ContinuumView);
    Tabs = (function(_super) {
      __extends(Tabs, _super);

      function Tabs() {
        _ref1 = Tabs.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Tabs.prototype.type = "Tabs";

      Tabs.prototype.default_view = TabsView;

      Tabs.prototype.defaults = function() {
        return _.extend({}, Tabs.__super__.defaults.call(this), {
          tabs: [],
          active: 0
        });
      };

      return Tabs;

    })(HasProperties);
    Tabses = (function(_super) {
      __extends(Tabses, _super);

      function Tabses() {
        _ref2 = Tabses.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Tabses.prototype.model = Tabs;

      return Tabses;

    })(Collection);
    return {
      Model: Tabs,
      Collection: new Tabses(),
      View: TabsView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=tabs.js.map
*/;
define('widget/dialog_template',[],function(){
  var template = function(__obj) {
  var _safe = function(value) {
    if (typeof value === 'undefined' && value == null)
      value = '';
    var result = new String(value);
    result.ecoSafe = true;
    return result;
  };
  return (function() {
    var __out = [], __self = this, _print = function(value) {
      if (typeof value !== 'undefined' && value != null)
        __out.push(value.ecoSafe ? value : __self.escape(value));
    }, _capture = function(callback) {
      var out = __out, result;
      __out = [];
      callback.call(this);
      result = __out.join('');
      __out = out;
      return _safe(result);
    };
    (function() {
      var button, i, _i, _len, _ref;
    
      _print(_safe('<div class="bk-bs-modal" tabindex="-1">\n  <div class="bk-bs-modal-dialog">\n    <div class="bk-bs-modal-content">\n      <div class="bk-bs-modal-header">\n        '));
    
      if (this.closable) {
        _print(_safe('\n          <button type="button" class="bk-bs-close" data-bk-bs-dismiss="modal">&times;</button>\n        '));
      }
    
      _print(_safe('\n        <h4 class="bk-bs-modal-title">'));
    
      _print(this.title);
    
      _print(_safe('</h4>\n      </div>\n      <div class="bk-bs-modal-body">\n        '));
    
      _print(this.content);
    
      _print(_safe('\n      </div>\n      <div class="bk-bs-modal-footer">\n        '));
    
      _ref = this.buttons;
      for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
        button = _ref[i];
        _print(_safe('\n          '));
        if (i === 0) {
          _print(_safe('\n            <button type="button" class="bk-bs-btn bk-bs-btn-primary" data-bk-bs-dismiss="modal">'));
          _print(button);
          _print(_safe('</button>\n          '));
        } else {
          _print(_safe('\n            <button type="button" class="bk-bs-btn bk-bs-btn-default">'));
          _print(button);
          _print(_safe('</button>\n          '));
        }
        _print(_safe('\n        '));
      }
    
      _print(_safe('\n      </div>\n    </div>\n  </div>\n</div>\n'));
    
    }).call(this);
    
    return __out.join('');
  }).call((function() {
    var obj = {
      escape: function(value) {
        return ('' + value)
          .replace(/&/g, '&amp;')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;')
          .replace(/"/g, '&quot;');
      },
      safe: _safe
    }, key;
    for (key in __obj) obj[key] = __obj[key];
    return obj;
  })());
};
  return template;
});

(function() {
  var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('widget/dialog',["underscore", "common/collection", "jquery", "bootstrap/modal", "common/has_properties", "common/continuum_view", "./dialog_template"], function(_, Collection, $, $1, HasProperties, ContinuumView, dialog_template) {
    var Dialog, DialogView, Dialogs, _ref, _ref1, _ref2;
    DialogView = (function(_super) {
      __extends(DialogView, _super);

      function DialogView() {
        this.changeContent = __bind(this.changeContent, this);
        this.changeVisibility = __bind(this.changeVisibility, this);
        this.onHide = __bind(this.onHide, this);
        _ref = DialogView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      DialogView.prototype.initialize = function(options) {
        DialogView.__super__.initialize.call(this, options);
        this.render();
        this.listenTo(this.model, 'destroy', this.remove);
        this.listenTo(this.model, 'change:visible', this.changeVisibility);
        return this.listenTo(this.model, 'change:content', this.changeContent);
      };

      DialogView.prototype.render = function() {
        this.$modal = $(dialog_template(this.model.attributes));
        this.$modal.modal({
          show: this.mget("visible")
        });
        this.$modal.on('hidden.bk-bs.modal', this.onHide);
        return this.$el.html(this.$modal);
      };

      DialogView.prototype.onHide = function(event) {
        return this.mset("visible", false, {
          silent: true
        });
      };

      DialogView.prototype.changeVisibility = function() {
        return this.$modal.modal(this.mget("visible") ? "show" : "hide");
      };

      DialogView.prototype.changeContent = function() {
        return this.$modal.find(".bk-bs-modal-body").text(this.mget("content"));
      };

      return DialogView;

    })(ContinuumView);
    Dialog = (function(_super) {
      __extends(Dialog, _super);

      function Dialog() {
        _ref1 = Dialog.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Dialog.prototype.type = "Dialog";

      Dialog.prototype.default_view = DialogView;

      Dialog.prototype.defaults = function() {
        return _.extend({}, Dialog.__super__.defaults.call(this), {
          visible: false,
          closable: true,
          title: "",
          content: "",
          buttons: []
        });
      };

      return Dialog;

    })(HasProperties);
    Dialogs = (function(_super) {
      __extends(Dialogs, _super);

      function Dialogs() {
        _ref2 = Dialogs.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Dialogs.prototype.model = Dialog;

      return Dialogs;

    })(Collection);
    return {
      Model: Dialog,
      Collection: new Dialogs(),
      View: DialogView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=dialog.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('widget/icon',["underscore", "common/collection", "common/continuum_view", "common/has_parent", "common/logging"], function(_, Collection, ContinuumView, HasParent, Logging) {
    var Icon, IconView, Icons, logger, _ref, _ref1, _ref2;
    logger = Logging.logger;
    IconView = (function(_super) {
      __extends(IconView, _super);

      function IconView() {
        _ref = IconView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      IconView.prototype.tagName = "i";

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

      IconView.prototype.render = function() {
        var flip, size;
        this.$el.empty();
        this.$el.addClass("bk-fa");
        this.$el.addClass("bk-fa-" + this.mget("name"));
        size = this.mget("size");
        if (size != null) {
          this.$el.css({
            "font-size": size + "em"
          });
        }
        flip = this.mget("flip");
        if (flip != null) {
          this.$el.addClass("bk-fa-flip-" + flip);
        }
        if (this.mget("spin")) {
          this.$el.addClass("bk-fa-spin");
        }
        return this;
      };

      return IconView;

    })(ContinuumView);
    Icon = (function(_super) {
      __extends(Icon, _super);

      function Icon() {
        _ref1 = Icon.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Icon.prototype.type = "Icon";

      Icon.prototype.default_view = IconView;

      Icon.prototype.defaults = function() {
        return _.extend({}, Icon.__super__.defaults.call(this), {
          name: "",
          size: null,
          flip: null,
          spin: false
        });
      };

      return Icon;

    })(HasParent);
    Icons = (function(_super) {
      __extends(Icons, _super);

      function Icons() {
        _ref2 = Icons.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Icons.prototype.model = Icon;

      return Icons;

    })(Collection);
    return {
      Model: Icon,
      Collection: new Icons(),
      View: IconView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=icon.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('widget/button',["underscore", "common/collection", "common/continuum_view", "common/has_parent", "common/build_views", "common/logging"], function(_, Collection, ContinuumView, HasParent, build_views, Logging) {
    var Button, ButtonView, Buttons, logger, _ref, _ref1, _ref2;
    logger = Logging.logger;
    ButtonView = (function(_super) {
      __extends(ButtonView, _super);

      function ButtonView() {
        _ref = ButtonView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      ButtonView.prototype.tagName = "button";

      ButtonView.prototype.events = {
        "click": "change_input"
      };

      ButtonView.prototype.change_input = function() {
        this.mset('clicks', this.mget('clicks') + 1);
        return this.model.save();
      };

      ButtonView.prototype.initialize = function(options) {
        ButtonView.__super__.initialize.call(this, options);
        this.views = {};
        this.render();
        return this.listenTo(this.model, 'change', this.render);
      };

      ButtonView.prototype.render = function() {
        var icon, key, label, val, _ref1;
        icon = this.mget('icon');
        if (icon != null) {
          build_views(this.views, [icon]);
          _ref1 = this.views;
          for (key in _ref1) {
            if (!__hasProp.call(_ref1, key)) continue;
            val = _ref1[key];
            val.$el.detach();
          }
        }
        this.$el.empty();
        this.$el.addClass("bk-bs-btn");
        this.$el.addClass("bk-bs-btn-" + this.mget("type"));
        if (this.mget("disabled")) {
          this.$el.attr("disabled", "disabled");
        }
        label = this.mget("label");
        if (icon != null) {
          this.$el.append(this.views[icon.id].$el);
          label = " " + label;
        }
        this.$el.append(document.createTextNode(label));
        return this;
      };

      return ButtonView;

    })(ContinuumView);
    Button = (function(_super) {
      __extends(Button, _super);

      function Button() {
        _ref1 = Button.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Button.prototype.type = "Button";

      Button.prototype.default_view = ButtonView;

      Button.prototype.defaults = function() {
        return _.extend({}, Button.__super__.defaults.call(this), {
          clicks: 0,
          label: "Button",
          icon: null,
          type: "default",
          disabled: false
        });
      };

      return Button;

    })(HasParent);
    Buttons = (function(_super) {
      __extends(Buttons, _super);

      function Buttons() {
        _ref2 = Buttons.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Buttons.prototype.model = Button;

      return Buttons;

    })(Collection);
    return {
      Model: Button,
      Collection: new Buttons(),
      View: ButtonView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=button.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('widget/toggle',["underscore", "common/collection", "common/continuum_view", "common/has_parent", "common/logging"], function(_, Collection, ContinuumView, HasParent, Logging) {
    var Toggle, ToggleView, Toggles, logger, _ref, _ref1, _ref2;
    logger = Logging.logger;
    ToggleView = (function(_super) {
      __extends(ToggleView, _super);

      function ToggleView() {
        _ref = ToggleView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      ToggleView.prototype.tagName = "button";

      ToggleView.prototype.events = {
        "click": "change_input"
      };

      ToggleView.prototype.change_input = function() {
        this.mset('active', this.$el.hasClass("bk-bs-active"));
        return this.model.save();
      };

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

      ToggleView.prototype.render = function() {
        var icon, key, label, val, _ref1;
        icon = this.mget('icon');
        if (icon != null) {
          build_views(this.views, [icon]);
          _ref1 = this.views;
          for (key in _ref1) {
            if (!__hasProp.call(_ref1, key)) continue;
            val = _ref1[key];
            val.$el.detach();
          }
        }
        this.$el.empty();
        this.$el.addClass("bk-bs-btn");
        this.$el.addClass("bk-bs-btn-" + this.mget("type"));
        if (this.mget("disabled")) {
          this.$el.attr("disabled", "disabled");
        }
        label = this.mget("label");
        if (icon != null) {
          this.$el.append(this.views[icon.id].$el);
          label = " " + label;
        }
        this.$el.append(document.createTextNode(label));
        if (this.mget("active")) {
          this.$el.addClass("bk-bs-active");
        }
        this.$el.attr("data-bk-bs-toggle", "button");
        return this;
      };

      return ToggleView;

    })(ContinuumView);
    Toggle = (function(_super) {
      __extends(Toggle, _super);

      function Toggle() {
        _ref1 = Toggle.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Toggle.prototype.type = "Toggle";

      Toggle.prototype.default_view = ToggleView;

      Toggle.prototype.defaults = function() {
        return _.extend({}, Toggle.__super__.defaults.call(this), {
          active: false,
          label: "Toggle",
          icon: null,
          type: "default",
          disabled: false
        });
      };

      return Toggle;

    })(HasParent);
    Toggles = (function(_super) {
      __extends(Toggles, _super);

      function Toggles() {
        _ref2 = Toggles.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Toggles.prototype.model = Toggle;

      return Toggles;

    })(Collection);
    return {
      Model: Toggle,
      Collection: new Toggles(),
      View: ToggleView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=toggle.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('widget/dropdown',["underscore", "common/collection", "common/continuum_view", "common/has_parent", "common/logging"], function(_, Collection, ContinuumView, HasParent, Logging) {
    var Dropdown, DropdownView, Dropdowns, logger, _ref, _ref1, _ref2;
    logger = Logging.logger;
    DropdownView = (function(_super) {
      __extends(DropdownView, _super);

      function DropdownView() {
        _ref = DropdownView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      DropdownView.prototype.tagName = "div";

      DropdownView.prototype.change_input = function(action) {
        this.mset('action', action);
        return this.model.save();
      };

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

      DropdownView.prototype.render = function() {
        var $a, $button, $caret, $divider, $item, $menu, $toggle, action, item, label, split, _i, _len, _ref1,
          _this = this;
        this.$el.empty();
        split = this.mget("default_action") != null;
        $button = $('<button></button>');
        $button.addClass("bk-bs-btn");
        $button.addClass("bk-bs-btn-" + this.mget("type"));
        $button.text(this.mget("label"));
        $caret = $('<span class="bk-bs-caret"></span>');
        if (!split) {
          $button.addClass("bk-bs-dropdown-toggle");
          $button.attr("data-bk-bs-toggle", "dropdown");
          $button.append(document.createTextNode(" "));
          $button.append($caret);
          $toggle = $('');
        } else {
          $button.click(function() {
            return _this.change_input(_this.mget("default_action"));
          });
          $toggle = $('<button></button>');
          $toggle.addClass("bk-bs-btn");
          $toggle.addClass("bk-bs-btn-" + this.mget("type"));
          $toggle.addClass("bk-bs-dropdown-toggle");
          $toggle.attr("data-bk-bs-toggle", "dropdown");
          $toggle.append($caret);
        }
        $menu = $('<ul class="bk-bs-dropdown-menu"></ul>');
        $divider = $('<li class="bk-bs-divider"></li>');
        _ref1 = this.mget("menu");
        for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
          item = _ref1[_i];
          $item = item != null ? ((label = item[0], action = item[1], item), $a = $('<a></a>').text(label), $a.click(function() {
            return _this.change_input(action);
          }), $('<li></li>').append($a)) : $divider;
          $menu.append($item);
        }
        this.$el.addClass("bk-bs-btn-group");
        this.$el.append([$button, $toggle, $menu]);
        return this;
      };

      return DropdownView;

    })(ContinuumView);
    Dropdown = (function(_super) {
      __extends(Dropdown, _super);

      function Dropdown() {
        _ref1 = Dropdown.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Dropdown.prototype.type = "Dropdown";

      Dropdown.prototype.default_view = DropdownView;

      Dropdown.prototype.defaults = function() {
        return _.extend({}, Dropdown.__super__.defaults.call(this), {
          action: null,
          default_action: null,
          label: "Dropdown",
          icon: null,
          type: "default",
          menu: [],
          disabled: false
        });
      };

      return Dropdown;

    })(HasParent);
    Dropdowns = (function(_super) {
      __extends(Dropdowns, _super);

      function Dropdowns() {
        _ref2 = Dropdowns.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Dropdowns.prototype.model = Dropdown;

      return Dropdowns;

    })(Collection);
    return {
      Model: Dropdown,
      Collection: new Dropdowns(),
      View: DropdownView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=dropdown.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
    __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; };

  define('widget/checkbox_group',["underscore", "common/collection", "common/continuum_view", "common/has_parent", "common/logging"], function(_, Collection, ContinuumView, HasParent, Logging) {
    var CheckboxGroup, CheckboxGroupView, CheckboxGroups, logger, _ref, _ref1, _ref2;
    logger = Logging.logger;
    CheckboxGroupView = (function(_super) {
      __extends(CheckboxGroupView, _super);

      function CheckboxGroupView() {
        _ref = CheckboxGroupView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      CheckboxGroupView.prototype.tagName = "div";

      CheckboxGroupView.prototype.events = {
        "change input": "change_input"
      };

      CheckboxGroupView.prototype.change_input = function() {
        var active, checkbox, i;
        active = (function() {
          var _i, _len, _ref1, _results;
          _ref1 = this.$("input");
          _results = [];
          for (i = _i = 0, _len = _ref1.length; _i < _len; i = ++_i) {
            checkbox = _ref1[i];
            if (checkbox.checked) {
              _results.push(i);
            }
          }
          return _results;
        }).call(this);
        this.mset('active', active);
        return this.model.save();
      };

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

      CheckboxGroupView.prototype.render = function() {
        var $div, $input, $label, active, i, label, _i, _len, _ref1;
        this.$el.empty();
        active = this.mget("active");
        _ref1 = this.mget("labels");
        for (i = _i = 0, _len = _ref1.length; _i < _len; i = ++_i) {
          label = _ref1[i];
          $input = $('<input type="checkbox">').attr({
            value: "" + i
          });
          if (this.mget("disabled")) {
            $input.prop("disabled", true);
          }
          if (__indexOf.call(active, i) >= 0) {
            $input.prop("checked", true);
          }
          $label = $('<label></label>').text(label).prepend($input);
          if (this.mget("inline")) {
            $label.addClass("bk-bs-checkbox-inline");
            this.$el.append($label);
          } else {
            $div = $('<div class="bk-bs-checkbox"></div>').append($label);
            this.$el.append($div);
          }
        }
        return this;
      };

      return CheckboxGroupView;

    })(ContinuumView);
    CheckboxGroup = (function(_super) {
      __extends(CheckboxGroup, _super);

      function CheckboxGroup() {
        _ref1 = CheckboxGroup.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      CheckboxGroup.prototype.type = "CheckboxGroup";

      CheckboxGroup.prototype.default_view = CheckboxGroupView;

      CheckboxGroup.prototype.defaults = function() {
        return _.extend({}, CheckboxGroup.__super__.defaults.call(this), {
          active: [],
          labels: [],
          inline: false,
          disabled: false
        });
      };

      return CheckboxGroup;

    })(HasParent);
    CheckboxGroups = (function(_super) {
      __extends(CheckboxGroups, _super);

      function CheckboxGroups() {
        _ref2 = CheckboxGroups.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      CheckboxGroups.prototype.model = CheckboxGroup;

      return CheckboxGroups;

    })(Collection);
    return {
      Model: CheckboxGroup,
      Collection: new CheckboxGroups(),
      View: CheckboxGroupView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=checkbox_group.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('widget/radio_group',["underscore", "common/collection", "common/continuum_view", "common/has_parent", "common/logging"], function(_, Collection, ContinuumView, HasParent, Logging) {
    var RadioGroup, RadioGroupView, RadioGroups, logger, _ref, _ref1, _ref2;
    logger = Logging.logger;
    RadioGroupView = (function(_super) {
      __extends(RadioGroupView, _super);

      function RadioGroupView() {
        _ref = RadioGroupView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      RadioGroupView.prototype.tagName = "div";

      RadioGroupView.prototype.events = {
        "change input": "change_input"
      };

      RadioGroupView.prototype.change_input = function() {
        var active, i, radio;
        active = (function() {
          var _i, _len, _ref1, _results;
          _ref1 = this.$("input");
          _results = [];
          for (i = _i = 0, _len = _ref1.length; _i < _len; i = ++_i) {
            radio = _ref1[i];
            if (radio.checked) {
              _results.push(i);
            }
          }
          return _results;
        }).call(this);
        this.mset('active', active[0]);
        return this.model.save();
      };

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

      RadioGroupView.prototype.render = function() {
        var $div, $input, $label, active, i, label, name, _i, _len, _ref1;
        this.$el.empty();
        name = _.uniqueId("RadioGroup");
        active = this.mget("active");
        _ref1 = this.mget("labels");
        for (i = _i = 0, _len = _ref1.length; _i < _len; i = ++_i) {
          label = _ref1[i];
          $input = $('<input type="radio">').attr({
            name: name,
            value: "" + i
          });
          if (this.mget("disabled")) {
            $input.prop("disabled", true);
          }
          if (i === active) {
            $input.prop("checked", true);
          }
          $label = $('<label></label>').text(label).prepend($input);
          if (this.mget("inline")) {
            $label.addClass("bk-bs-radio-inline");
            this.$el.append($label);
          } else {
            $div = $('<div class="bk-bs-radio"></div>').append($label);
            this.$el.append($div);
          }
        }
        return this;
      };

      return RadioGroupView;

    })(ContinuumView);
    RadioGroup = (function(_super) {
      __extends(RadioGroup, _super);

      function RadioGroup() {
        _ref1 = RadioGroup.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      RadioGroup.prototype.type = "RadioGroup";

      RadioGroup.prototype.default_view = RadioGroupView;

      RadioGroup.prototype.defaults = function() {
        return _.extend({}, RadioGroup.__super__.defaults.call(this), {
          active: null,
          labels: [],
          inline: false,
          disabled: false
        });
      };

      return RadioGroup;

    })(HasParent);
    RadioGroups = (function(_super) {
      __extends(RadioGroups, _super);

      function RadioGroups() {
        _ref2 = RadioGroups.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      RadioGroups.prototype.model = RadioGroup;

      return RadioGroups;

    })(Collection);
    return {
      Model: RadioGroup,
      Collection: new RadioGroups(),
      View: RadioGroupView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=radio_group.js.map
*/;
define('bootstrap/button',["jquery"], function(jQuery) {

/* ========================================================================
 * Bootstrap: button.js v3.1.1
 * http://getbootstrap.com/javascript/#buttons
 * ========================================================================
 * Copyright 2011-2014 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
  

  // BUTTON PUBLIC CLASS DEFINITION
  // ==============================

  var Button = function (element, options) {
    this.$element  = $(element)
    this.options   = $.extend({}, Button.DEFAULTS, options)
    this.isLoading = false
  }

  Button.DEFAULTS = {
    loadingText: 'loading...'
  }

  Button.prototype.setState = function (state) {
    var d    = 'bk-bs-disabled'
    var $el  = this.$element
    var val  = $el.is('input') ? 'val' : 'html'
    var data = $el.data()

    state = state + 'Text'

    if (!data.resetText) $el.data('resetText', $el[val]())

    $el[val](data[state] || this.options[state])

    // push to event loop to allow forms to submit
    setTimeout($.proxy(function () {
      if (state == 'loadingText') {
        this.isLoading = true
        $el.addClass(d).attr(d, d)
      } else if (this.isLoading) {
        this.isLoading = false
        $el.removeClass(d).removeAttr(d)
      }
    }, this), 0)
  }

  Button.prototype.toggle = function () {
    var changed = true
    var $parent = this.$element.closest('[data-bk-bs-toggle="buttons"]')

    if ($parent.length) {
      var $input = this.$element.find('input')
      if ($input.prop('type') == 'radio') {
        if ($input.prop('checked') && this.$element.hasClass('bk-bs-active')) changed = false
        else $parent.find('.bk-bs-active').removeClass('bk-bs-active')
      }
      if (changed) $input.prop('checked', !this.$element.hasClass('bk-bs-active')).trigger('change')
    }

    if (changed) this.$element.toggleClass('bk-bs-active')
  }


  // BUTTON PLUGIN DEFINITION
  // ========================

  var old = $.fn.button

  $.fn.button = function (option) {
    return this.each(function () {
      var $this   = $(this)
      var data    = $this.data('bk-bs.button')
      var options = typeof option == 'object' && option

      if (!data) $this.data('bk-bs.button', (data = new Button(this, options)))

      if (option == 'toggle') data.toggle()
      else if (option) data.setState(option)
    })
  }

  $.fn.button.Constructor = Button


  // BUTTON NO CONFLICT
  // ==================

  $.fn.button.noConflict = function () {
    $.fn.button = old
    return this
  }


  // BUTTON DATA-API
  // ===============

  $(document).on('click.bk-bs.button.data-api', '[data-bk-bs-toggle^=button]', function (e) {
    var $btn = $(e.target)
    if (!$btn.hasClass('bk-bs-btn')) $btn = $btn.closest('.bk-bs-btn')
    $btn.button('toggle')
    e.preventDefault()
  })

}(jQuery);

});

(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
    __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; };

  define('widget/checkbox_button_group',["underscore", "common/collection", "jquery", "bootstrap/button", "common/continuum_view", "common/has_parent", "common/logging"], function(_, Collection, $, $1, ContinuumView, HasParent, Logging) {
    var CheckboxButtonGroup, CheckboxButtonGroupView, CheckboxButtonGroups, logger, _ref, _ref1, _ref2;
    logger = Logging.logger;
    CheckboxButtonGroupView = (function(_super) {
      __extends(CheckboxButtonGroupView, _super);

      function CheckboxButtonGroupView() {
        _ref = CheckboxButtonGroupView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      CheckboxButtonGroupView.prototype.tagName = "div";

      CheckboxButtonGroupView.prototype.events = {
        "change input": "change_input"
      };

      CheckboxButtonGroupView.prototype.change_input = function() {
        var active, checkbox, i;
        active = (function() {
          var _i, _len, _ref1, _results;
          _ref1 = this.$("input");
          _results = [];
          for (i = _i = 0, _len = _ref1.length; _i < _len; i = ++_i) {
            checkbox = _ref1[i];
            if (checkbox.checked) {
              _results.push(i);
            }
          }
          return _results;
        }).call(this);
        this.mset('active', active);
        return this.model.save();
      };

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

      CheckboxButtonGroupView.prototype.render = function() {
        this.$el.empty();
        return this;
      };

      CheckboxButtonGroupView.prototype.render = function() {
        var $input, $label, active, i, label, _i, _len, _ref1;
        this.$el.empty();
        this.$el.addClass("bk-bs-btn-group");
        this.$el.attr("data-bk-bs-toggle", "buttons");
        active = this.mget("active");
        _ref1 = this.mget("labels");
        for (i = _i = 0, _len = _ref1.length; _i < _len; i = ++_i) {
          label = _ref1[i];
          $input = $('<input type="checkbox">').attr({
            value: "" + i
          });
          if (__indexOf.call(active, i) >= 0) {
            $input.prop("checked", true);
          }
          $label = $('<label class="bk-bs-btn"></label>');
          $label.text(label).prepend($input);
          $label.addClass("bk-bs-btn-" + this.mget("type"));
          if (__indexOf.call(active, i) >= 0) {
            $label.addClass("bk-bs-active");
          }
          this.$el.append($label);
        }
        return this;
      };

      return CheckboxButtonGroupView;

    })(ContinuumView);
    CheckboxButtonGroup = (function(_super) {
      __extends(CheckboxButtonGroup, _super);

      function CheckboxButtonGroup() {
        _ref1 = CheckboxButtonGroup.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      CheckboxButtonGroup.prototype.type = "CheckboxButtonGroup";

      CheckboxButtonGroup.prototype.default_view = CheckboxButtonGroupView;

      CheckboxButtonGroup.prototype.defaults = function() {
        return _.extend({}, CheckboxButtonGroup.__super__.defaults.call(this), {
          active: [],
          labels: [],
          type: "default",
          disabled: false
        });
      };

      return CheckboxButtonGroup;

    })(HasParent);
    CheckboxButtonGroups = (function(_super) {
      __extends(CheckboxButtonGroups, _super);

      function CheckboxButtonGroups() {
        _ref2 = CheckboxButtonGroups.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      CheckboxButtonGroups.prototype.model = CheckboxButtonGroup;

      return CheckboxButtonGroups;

    })(Collection);
    return {
      Model: CheckboxButtonGroup,
      Collection: new CheckboxButtonGroups(),
      View: CheckboxButtonGroupView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=checkbox_button_group.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('widget/radio_button_group',["underscore", "common/collection", "jquery", "bootstrap/button", "common/continuum_view", "common/has_parent", "common/logging", "bootstrap/button"], function(_, Collection, $, $1, ContinuumView, HasParent, Logging) {
    var RadioButtonGroup, RadioButtonGroupView, RadioButtonGroups, logger, _ref, _ref1, _ref2;
    logger = Logging.logger;
    RadioButtonGroupView = (function(_super) {
      __extends(RadioButtonGroupView, _super);

      function RadioButtonGroupView() {
        _ref = RadioButtonGroupView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      RadioButtonGroupView.prototype.tagName = "div";

      RadioButtonGroupView.prototype.events = {
        "change input": "change_input"
      };

      RadioButtonGroupView.prototype.change_input = function() {
        var active, i, radio;
        active = (function() {
          var _i, _len, _ref1, _results;
          _ref1 = this.$("input");
          _results = [];
          for (i = _i = 0, _len = _ref1.length; _i < _len; i = ++_i) {
            radio = _ref1[i];
            if (radio.checked) {
              _results.push(i);
            }
          }
          return _results;
        }).call(this);
        this.mset('active', active[0]);
        return this.model.save();
      };

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

      RadioButtonGroupView.prototype.render = function() {
        var $input, $label, active, i, label, name, _i, _len, _ref1;
        this.$el.empty();
        this.$el.addClass("bk-bs-btn-group");
        this.$el.attr("data-bk-bs-toggle", "buttons");
        name = _.uniqueId("RadioButtonGroup");
        active = this.mget("active");
        _ref1 = this.mget("labels");
        for (i = _i = 0, _len = _ref1.length; _i < _len; i = ++_i) {
          label = _ref1[i];
          $input = $('<input type="radio">').attr({
            name: name,
            value: "" + i
          });
          if (i === active) {
            $input.prop("checked", true);
          }
          $label = $('<label class="bk-bs-btn"></label>');
          $label.text(label).prepend($input);
          $label.addClass("bk-bs-btn-" + this.mget("type"));
          if (i === active) {
            $label.addClass("bk-bs-active");
          }
          this.$el.append($label);
        }
        return this;
      };

      return RadioButtonGroupView;

    })(ContinuumView);
    RadioButtonGroup = (function(_super) {
      __extends(RadioButtonGroup, _super);

      function RadioButtonGroup() {
        _ref1 = RadioButtonGroup.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      RadioButtonGroup.prototype.type = "RadioButtonGroup";

      RadioButtonGroup.prototype.default_view = RadioButtonGroupView;

      RadioButtonGroup.prototype.defaults = function() {
        return _.extend({}, RadioButtonGroup.__super__.defaults.call(this), {
          active: null,
          labels: [],
          type: "default",
          disabled: false
        });
      };

      return RadioButtonGroup;

    })(HasParent);
    RadioButtonGroups = (function(_super) {
      __extends(RadioButtonGroups, _super);

      function RadioButtonGroups() {
        _ref2 = RadioButtonGroups.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      RadioButtonGroups.prototype.model = RadioButtonGroup;

      return RadioButtonGroups;

    })(Collection);
    return {
      Model: RadioButtonGroup,
      Collection: new RadioButtonGroups(),
      View: RadioButtonGroupView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=radio_button_group.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('transforms/transform',["common/has_properties"], function(HasProperties) {
    var Transform, _ref;
    return Transform = (function(_super) {
      __extends(Transform, _super);

      function Transform() {
        _ref = Transform.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      return Transform;

    })(HasProperties);
  });

}).call(this);

/*
//@ sourceMappingURL=transform.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('transforms/autoencode',["common/collection", "./transform"], function(Collection, Transform) {
    var AutoEncode, AutoEncodes, _ref, _ref1;
    AutoEncode = (function(_super) {
      __extends(AutoEncode, _super);

      function AutoEncode() {
        _ref = AutoEncode.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      AutoEncode.prototype.type = "AutoEncode";

      return AutoEncode;

    })(Transform);
    AutoEncodes = (function(_super) {
      __extends(AutoEncodes, _super);

      function AutoEncodes() {
        _ref1 = AutoEncodes.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      AutoEncodes.prototype.model = AutoEncode;

      return AutoEncodes;

    })(Collection);
    return {
      Model: AutoEncode,
      Collection: new AutoEncodes()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=autoencode.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('transforms/binarysegment',["common/collection", "./transform"], function(Collection, Transform) {
    var BinarySegment, BinarySegments, _ref, _ref1;
    BinarySegment = (function(_super) {
      __extends(BinarySegment, _super);

      function BinarySegment() {
        _ref = BinarySegment.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      BinarySegment.prototype.type = "BinarySegment";

      return BinarySegment;

    })(Transform);
    BinarySegments = (function(_super) {
      __extends(BinarySegments, _super);

      function BinarySegments() {
        _ref1 = BinarySegments.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      BinarySegments.prototype.model = BinarySegment;

      return BinarySegments;

    })(Collection);
    return {
      Model: BinarySegment,
      Collection: new BinarySegments()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=binarysegment.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('transforms/const',["common/collection", "./transform"], function(Collection, Transform) {
    var Const, Consts, _ref, _ref1;
    Const = (function(_super) {
      __extends(Const, _super);

      function Const() {
        _ref = Const.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      Const.prototype.type = "Const";

      return Const;

    })(Transform);
    Consts = (function(_super) {
      __extends(Consts, _super);

      function Consts() {
        _ref1 = Consts.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Consts.prototype.model = Const;

      return Consts;

    })(Collection);
    return {
      Model: Const,
      Collection: new Consts()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=const.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('transforms/contour',["common/collection", "./transform"], function(Collection, Transform) {
    var Contour, Contours, _ref, _ref1;
    Contour = (function(_super) {
      __extends(Contour, _super);

      function Contour() {
        _ref = Contour.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      Contour.prototype.type = "Contour";

      return Contour;

    })(Transform);
    Contours = (function(_super) {
      __extends(Contours, _super);

      function Contours() {
        _ref1 = Contours.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Contours.prototype.model = Contour;

      return Contours;

    })(Collection);
    return {
      Model: Contour,
      Collection: new Contours()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=contour.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('transforms/count',["common/collection", "./transform"], function(Collection, Transform) {
    var Count, Counts, _ref, _ref1;
    Count = (function(_super) {
      __extends(Count, _super);

      function Count() {
        _ref = Count.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      Count.prototype.type = "Count";

      return Count;

    })(Transform);
    Counts = (function(_super) {
      __extends(Counts, _super);

      function Counts() {
        _ref1 = Counts.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Counts.prototype.model = Count;

      return Counts;

    })(Collection);
    return {
      Model: Count,
      Collection: new Counts()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=count.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('transforms/countcategories',["common/collection", "./transform"], function(Collection, Transform) {
    var CountCategories, CountCategoriess, _ref, _ref1;
    CountCategories = (function(_super) {
      __extends(CountCategories, _super);

      function CountCategories() {
        _ref = CountCategories.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      CountCategories.prototype.type = "CountCategories";

      return CountCategories;

    })(Transform);
    CountCategoriess = (function(_super) {
      __extends(CountCategoriess, _super);

      function CountCategoriess() {
        _ref1 = CountCategoriess.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      CountCategoriess.prototype.model = CountCategories;

      return CountCategoriess;

    })(Collection);
    return {
      Model: CountCategories,
      Collection: new CountCategoriess()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=countcategories.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('transforms/encode',["common/collection", "./transform"], function(Collection, Transform) {
    var Encode, Encodes, _ref, _ref1;
    Encode = (function(_super) {
      __extends(Encode, _super);

      function Encode() {
        _ref = Encode.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      Encode.prototype.type = "Encode";

      return Encode;

    })(Transform);
    Encodes = (function(_super) {
      __extends(Encodes, _super);

      function Encodes() {
        _ref1 = Encodes.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Encodes.prototype.model = Encode;

      return Encodes;

    })(Collection);
    return {
      Model: Encode,
      Collection: new Encodes()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=encode.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('transforms/cuberoot',["common/collection", "./transform"], function(Collection, Transform) {
    var Cuberoot, Cuberoots, _ref, _ref1;
    Cuberoot = (function(_super) {
      __extends(Cuberoot, _super);

      function Cuberoot() {
        _ref = Cuberoot.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      Cuberoot.prototype.type = "Cuberoot";

      return Cuberoot;

    })(Transform);
    Cuberoots = (function(_super) {
      __extends(Cuberoots, _super);

      function Cuberoots() {
        _ref1 = Cuberoots.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Cuberoots.prototype.model = Cuberoot;

      return Cuberoots;

    })(Collection);
    return {
      Model: Cuberoot,
      Collection: new Cuberoots()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=cuberoot.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('transforms/hdalpha',["common/collection", "./transform"], function(Collection, Transform) {
    var HDAlpha, HDAlphas, _ref, _ref1;
    HDAlpha = (function(_super) {
      __extends(HDAlpha, _super);

      function HDAlpha() {
        _ref = HDAlpha.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      HDAlpha.prototype.type = "HDAlpha";

      return HDAlpha;

    })(Transform);
    HDAlphas = (function(_super) {
      __extends(HDAlphas, _super);

      function HDAlphas() {
        _ref1 = HDAlphas.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      HDAlphas.prototype.model = HDAlpha;

      return HDAlphas;

    })(Collection);
    return {
      Model: HDAlpha,
      Collection: new HDAlphas()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=hdalpha.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('transforms/id',["common/collection", "./transform"], function(Collection, Transform) {
    var Id, Ids, _ref, _ref1;
    Id = (function(_super) {
      __extends(Id, _super);

      function Id() {
        _ref = Id.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      Id.prototype.type = "Id";

      return Id;

    })(Transform);
    Ids = (function(_super) {
      __extends(Ids, _super);

      function Ids() {
        _ref1 = Ids.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Ids.prototype.model = Id;

      return Ids;

    })(Collection);
    return {
      Model: Id,
      Collection: new Ids()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=id.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('transforms/interpolate',["common/collection", "./transform"], function(Collection, Transform) {
    var Interpolate, Interpolates, _ref, _ref1;
    Interpolate = (function(_super) {
      __extends(Interpolate, _super);

      function Interpolate() {
        _ref = Interpolate.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      Interpolate.prototype.type = "Interpolate";

      return Interpolate;

    })(Transform);
    Interpolates = (function(_super) {
      __extends(Interpolates, _super);

      function Interpolates() {
        _ref1 = Interpolates.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Interpolates.prototype.model = Interpolate;

      return Interpolates;

    })(Collection);
    return {
      Model: Interpolate,
      Collection: new Interpolates()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=interpolate.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('transforms/interpolatecolor',["common/collection", "./transform"], function(Collection, Transform) {
    var InterpolateColor, InterpolateColors, _ref, _ref1;
    InterpolateColor = (function(_super) {
      __extends(InterpolateColor, _super);

      function InterpolateColor() {
        _ref = InterpolateColor.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      InterpolateColor.prototype.type = "InterpolateColor";

      return InterpolateColor;

    })(Transform);
    InterpolateColors = (function(_super) {
      __extends(InterpolateColors, _super);

      function InterpolateColors() {
        _ref1 = InterpolateColors.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      InterpolateColors.prototype.model = InterpolateColor;

      return InterpolateColors;

    })(Collection);
    return {
      Model: InterpolateColor,
      Collection: new InterpolateColors()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=interpolatecolor.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('transforms/log',["common/collection", "./transform"], function(Collection, Transform) {
    var Log, Logs, _ref, _ref1;
    Log = (function(_super) {
      __extends(Log, _super);

      function Log() {
        _ref = Log.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      Log.prototype.type = "Log";

      return Log;

    })(Transform);
    Logs = (function(_super) {
      __extends(Logs, _super);

      function Logs() {
        _ref1 = Logs.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Logs.prototype.model = Log;

      return Logs;

    })(Collection);
    return {
      Model: Log,
      Collection: new Logs()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=log.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('transforms/nonzero',["common/collection", "./transform"], function(Collection, Transform) {
    var NonZero, NonZeros, _ref, _ref1;
    NonZero = (function(_super) {
      __extends(NonZero, _super);

      function NonZero() {
        _ref = NonZero.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      NonZero.prototype.type = "NonZero";

      return NonZero;

    })(Transform);
    NonZeros = (function(_super) {
      __extends(NonZeros, _super);

      function NonZeros() {
        _ref1 = NonZeros.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      NonZeros.prototype.model = NonZero;

      return NonZeros;

    })(Collection);
    return {
      Model: NonZero,
      Collection: new NonZeros()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=nonzero.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('transforms/ratio',["common/collection", "./transform"], function(Collection, Transform) {
    var Ratio, Ratios, _ref, _ref1;
    Ratio = (function(_super) {
      __extends(Ratio, _super);

      function Ratio() {
        _ref = Ratio.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      Ratio.prototype.type = "Ratio";

      return Ratio;

    })(Transform);
    Ratios = (function(_super) {
      __extends(Ratios, _super);

      function Ratios() {
        _ref1 = Ratios.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Ratios.prototype.model = Ratio;

      return Ratios;

    })(Collection);
    return {
      Model: Ratio,
      Collection: new Ratios()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=ratio.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('transforms/seq',["common/collection", "./transform"], function(Collection, Transform) {
    var Seq, Seqs, _ref, _ref1;
    Seq = (function(_super) {
      __extends(Seq, _super);

      function Seq() {
        _ref = Seq.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      Seq.prototype.type = "Seq";

      return Seq;

    })(Transform);
    Seqs = (function(_super) {
      __extends(Seqs, _super);

      function Seqs() {
        _ref1 = Seqs.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Seqs.prototype.model = Seq;

      return Seqs;

    })(Collection);
    return {
      Model: Seq,
      Collection: new Seqs()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=seq.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('transforms/spread',["common/collection", "./transform"], function(Collection, Transform) {
    var Spread, Spreads, _ref, _ref1;
    Spread = (function(_super) {
      __extends(Spread, _super);

      function Spread() {
        _ref = Spread.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      Spread.prototype.type = "Spread";

      return Spread;

    })(Transform);
    Spreads = (function(_super) {
      __extends(Spreads, _super);

      function Spreads() {
        _ref1 = Spreads.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Spreads.prototype.model = Spread;

      return Spreads;

    })(Collection);
    return {
      Model: Spread,
      Collection: new Spreads()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=spread.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('transforms/tocounts',["common/collection", "./transform"], function(Collection, Transform) {
    var ToCounts, ToCountss, _ref, _ref1;
    ToCounts = (function(_super) {
      __extends(ToCounts, _super);

      function ToCounts() {
        _ref = ToCounts.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      ToCounts.prototype.type = "ToCounts";

      return ToCounts;

    })(Transform);
    ToCountss = (function(_super) {
      __extends(ToCountss, _super);

      function ToCountss() {
        _ref1 = ToCountss.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      ToCountss.prototype.model = ToCounts;

      return ToCountss;

    })(Collection);
    return {
      Model: ToCounts,
      Collection: new ToCountss()
    };
  });

}).call(this);

/*
//@ sourceMappingURL=tocounts.js.map
*/;
(function() {
  define('common/base',["underscore", "require", "action/open_url", "common/custom", "common/canvas", "common/cartesian_frame", "common/gmap_plot", "common/geojs_plot", "common/grid_plot", "common/layout_box", "common/plot", "common/plot_context", "common/selection_manager", "common/selector", "common/tool_events", "mapper/categorical_mapper", "mapper/linear_mapper", "mapper/log_mapper", "mapper/grid_mapper", "mapper/linear_color_mapper", "range/data_range1d", "range/factor_range", "range/range1d", "renderer/annotation/legend", "renderer/annotation/span", "renderer/annotation/tooltip", "renderer/glyph/glyph_renderer", "renderer/glyph/annular_wedge", "renderer/glyph/annulus", "renderer/glyph/arc", "renderer/glyph/bezier", "renderer/glyph/circle", "renderer/glyph/gear", "renderer/glyph/image", "renderer/glyph/image_rgba", "renderer/glyph/image_url", "renderer/glyph/line", "renderer/glyph/multi_line", "renderer/glyph/oval", "renderer/glyph/patch", "renderer/glyph/patches", "renderer/glyph/quad", "renderer/glyph/quadratic", "renderer/glyph/ray", "renderer/glyph/rect", "renderer/glyph/segment", "renderer/glyph/text", "renderer/glyph/wedge", "renderer/glyph/marker/asterisk", "renderer/glyph/marker/circle_cross", "renderer/glyph/marker/circle_x", "renderer/glyph/marker/cross", "renderer/glyph/marker/diamond", "renderer/glyph/marker/diamond_cross", "renderer/glyph/marker/inverted_triangle", "renderer/glyph/marker/square", "renderer/glyph/marker/square_cross", "renderer/glyph/marker/square_x", "renderer/glyph/marker/triangle", "renderer/glyph/marker/x", "renderer/guide/categorical_axis", "renderer/guide/datetime_axis", "renderer/guide/grid", "renderer/guide/linear_axis", "renderer/guide/log_axis", "renderer/overlay/box_selection", "renderer/overlay/poly_selection", "source/ajax_data_source", "source/blaze_data_source", "source/column_data_source", "source/server_data_source", "ticking/abstract_ticker", "ticking/adaptive_ticker", "ticking/basic_ticker", "ticking/categorical_ticker", "ticking/composite_ticker", "ticking/datetime_ticker", "ticking/days_ticker", "ticking/log_ticker", "ticking/months_ticker", "ticking/single_interval_ticker", "ticking/years_ticker", "ticking/basic_tick_formatter", "ticking/categorical_tick_formatter", "ticking/datetime_tick_formatter", "ticking/log_tick_formatter", "ticking/numeral_tick_formatter", "ticking/printf_tick_formatter", "tool/button_tool", "tool/actions/action_tool", "tool/actions/preview_save_tool", "tool/actions/reset_tool", "tool/gestures/box_select_tool", "tool/gestures/box_zoom_tool", "tool/gestures/gesture_tool", "tool/gestures/lasso_select_tool", "tool/gestures/pan_tool", "tool/gestures/resize_tool", "tool/gestures/select_tool", "tool/gestures/tap_tool", "tool/gestures/wheel_zoom_tool", "tool/inspectors/crosshair_tool", "tool/inspectors/hover_tool", "tool/inspectors/inspect_tool", "widget/cell_formatters", "widget/cell_editors", "widget/table_column", "widget/data_table", 'widget/paragraph', 'widget/hbox', 'widget/vbox', 'widget/text_input', 'widget/autocomplete_input', 'widget/vboxform', 'widget/pretext', 'widget/selectbox', 'widget/slider', 'widget/crossfilter', 'widget/multiselect', 'widget/date_range_slider', 'widget/date_picker', 'widget/panel', 'widget/tabs', 'widget/dialog', 'widget/icon', 'widget/button', 'widget/toggle', 'widget/dropdown', 'widget/checkbox_group', 'widget/radio_group', 'widget/checkbox_button_group', 'widget/radio_button_group', 'transforms/autoencode', 'transforms/binarysegment', 'transforms/const', 'transforms/contour', 'transforms/count', 'transforms/countcategories', 'transforms/encode', 'transforms/cuberoot', 'transforms/hdalpha', 'transforms/id', 'transforms/interpolate', 'transforms/interpolatecolor', 'transforms/log', 'transforms/nonzero', 'transforms/ratio', 'transforms/seq', 'transforms/spread', 'transforms/tocounts', 'transforms/transform'], function(_, require) {
    var Collections, Config, collection_overrides, index, locations, mod_cache, url;
    require("common/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 = {
      OpenURL: 'action/open_url',
      Plot: 'common/plot',
      GMapPlot: 'common/gmap_plot',
      GeoJSPlot: 'common/geojs_plot',
      GridPlot: 'common/grid_plot',
      PlotContext: 'common/plot_context',
      PlotList: 'common/plot_context',
      Canvas: 'common/canvas',
      LayoutBox: 'common/layout_box',
      CartesianFrame: 'common/cartesian_frame',
      SelectionManager: 'common/selection_manager',
      Selector: 'common/selector',
      ToolEvents: 'common/tool_events',
      LinearColorMapper: 'mapper/linear_color_mapper',
      DataRange1d: 'range/data_range1d',
      FactorRange: 'range/factor_range',
      Range1d: 'range/range1d',
      Legend: 'renderer/annotation/legend',
      Span: 'renderer/annotation/span',
      Tooltip: 'renderer/annotation/tooltip',
      GlyphRenderer: 'renderer/glyph/glyph_renderer',
      AnnularWedge: 'renderer/glyph/annular_wedge',
      Annulus: 'renderer/glyph/annulus',
      Arc: 'renderer/glyph/arc',
      Bezier: 'renderer/glyph/bezier',
      Circle: 'renderer/glyph/circle',
      Gear: 'renderer/glyph/gear',
      Image: 'renderer/glyph/image',
      ImageRGBA: 'renderer/glyph/image_rgba',
      ImageURL: 'renderer/glyph/image_url',
      Line: 'renderer/glyph/line',
      MultiLine: 'renderer/glyph/multi_line',
      Oval: 'renderer/glyph/oval',
      Patch: 'renderer/glyph/patch',
      Patches: 'renderer/glyph/patches',
      Quad: 'renderer/glyph/quad',
      Quadratic: 'renderer/glyph/quadratic',
      Ray: 'renderer/glyph/ray',
      Rect: 'renderer/glyph/rect',
      Segment: 'renderer/glyph/segment',
      Text: 'renderer/glyph/text',
      Wedge: 'renderer/glyph/wedge',
      Asterisk: 'renderer/glyph/marker/asterisk',
      CircleCross: 'renderer/glyph/marker/circle_cross',
      CircleX: 'renderer/glyph/marker/circle_x',
      Cross: 'renderer/glyph/marker/cross',
      Diamond: 'renderer/glyph/marker/diamond',
      DiamondCross: 'renderer/glyph/marker/diamond_cross',
      InvertedTriangle: 'renderer/glyph/marker/inverted_triangle',
      Square: 'renderer/glyph/marker/square',
      SquareCross: 'renderer/glyph/marker/square_cross',
      SquareX: 'renderer/glyph/marker/square_x',
      Triangle: 'renderer/glyph/marker/triangle',
      X: 'renderer/glyph/marker/x',
      LinearAxis: 'renderer/guide/linear_axis',
      LogAxis: 'renderer/guide/log_axis',
      CategoricalAxis: 'renderer/guide/categorical_axis',
      DatetimeAxis: 'renderer/guide/datetime_axis',
      Grid: 'renderer/guide/grid',
      BoxSelection: 'renderer/overlay/box_selection',
      PolySelection: 'renderer/overlay/poly_selection',
      ColumnDataSource: 'source/column_data_source',
      ServerDataSource: 'source/server_data_source',
      BlazeDataSource: 'source/blaze_data_source',
      AjaxDataSource: 'source/ajax_data_source',
      AbstractTicker: 'ticking/abstract_ticker',
      AdaptiveTicker: 'ticking/adaptive_ticker',
      BasicTicker: 'ticking/basic_ticker',
      CategoricalTicker: 'ticking/categorical_ticker',
      CompositeTicker: 'ticking/composite_ticker',
      DatetimeTicker: 'ticking/datetime_ticker',
      DaysTicker: 'ticking/days_ticker',
      LogTicker: 'ticking/log_ticker',
      MonthsTicker: 'ticking/months_ticker',
      SingleIntervalTicker: 'ticking/single_interval_ticker',
      YearsTicker: 'ticking/years_ticker',
      BasicTickFormatter: 'ticking/basic_tick_formatter',
      LogTickFormatter: 'ticking/log_tick_formatter',
      CategoricalTickFormatter: 'ticking/categorical_tick_formatter',
      DatetimeTickFormatter: 'ticking/datetime_tick_formatter',
      NumeralTickFormatter: 'ticking/numeral_tick_formatter',
      PrintfTickFormatter: 'ticking/printf_tick_formatter',
      ButtonTool: 'tool/button_tool',
      ActionTool: 'tool/actions/action_tool',
      PreviewSaveTool: 'tool/actions/preview_save_tool',
      ResetTool: 'tool/actions/reset_tool',
      BoxSelectTool: 'tool/gestures/box_select_tool',
      BoxZoomTool: 'tool/gestures/box_zoom_tool',
      GestureTool: 'tool/gestures/gesture_tool',
      LassoSelectTool: 'tool/gestures/lasso_select_tool',
      PanTool: 'tool/gestures/pan_tool',
      PolySelectTool: 'tool/gestures/poly_select_tool',
      SelectTool: 'tool/gestures/select_tool',
      ResizeTool: 'tool/gestures/resize_tool',
      TapTool: 'tool/gestures/tap_tool',
      WheelZoomTool: 'tool/gestures/wheel_zoom_tool',
      CrosshairTool: 'tool/inspectors/crosshair_tool',
      HoverTool: 'tool/inspectors/hover_tool',
      InspectTool: 'tool/inspectors/inspect_tool',
      StringFormatter: ['widget/cell_formatters', 'String'],
      NumberFormatter: ['widget/cell_formatters', 'Number'],
      BooleanFormatter: ['widget/cell_formatters', 'Boolean'],
      DateFormatter: ['widget/cell_formatters', 'Date'],
      StringEditor: ['widget/cell_editors', 'String'],
      TextEditor: ['widget/cell_editors', 'Text'],
      SelectEditor: ['widget/cell_editors', 'Select'],
      PercentEditor: ['widget/cell_editors', 'Percent'],
      CheckboxEditor: ['widget/cell_editors', 'Checkbox'],
      IntEditor: ['widget/cell_editors', 'Int'],
      NumberEditor: ['widget/cell_editors', 'Number'],
      TimeEditor: ['widget/cell_editors', 'Time'],
      DateEditor: ['widget/cell_editors', 'Date'],
      TableColumn: 'widget/table_column',
      DataTable: 'widget/data_table',
      Paragraph: 'widget/paragraph',
      HBox: 'widget/hbox',
      VBox: 'widget/vbox',
      VBoxForm: 'widget/vboxform',
      TextInput: 'widget/text_input',
      AutocompleteInput: 'widget/autocomplete_input',
      PreText: 'widget/pretext',
      Select: 'widget/selectbox',
      Slider: 'widget/slider',
      CrossFilter: 'widget/crossfilter',
      MultiSelect: 'widget/multiselect',
      DateRangeSlider: 'widget/date_range_slider',
      DatePicker: 'widget/date_picker',
      Panel: 'widget/panel',
      Tabs: 'widget/tabs',
      Dialog: 'widget/dialog',
      Icon: 'widget/icon',
      Button: 'widget/button',
      Toggle: 'widget/toggle',
      Dropdown: 'widget/dropdown',
      CheckboxGroup: 'widget/checkbox_group',
      RadioGroup: 'widget/radio_group',
      CheckboxButtonGroup: 'widget/checkbox_button_group',
      RadioButtonGroup: 'widget/radio_button_group',
      AutoEncode: 'transforms/autoencode',
      BinarySegment: 'transforms/binarysegment',
      Const: 'transforms/const',
      Contour: 'transforms/contour',
      Count: 'transforms/count',
      CountCategories: 'transforms/countcategories',
      Cuberoot: 'transforms/cuberoot',
      HDAlpha: 'transforms/hdalpha',
      Encode: 'transforms/encode',
      Id: 'transforms/id',
      Interpolate: 'transforms/interpolate',
      InterpolateColor: 'transforms/interpolatecolor',
      Log: 'transforms/log',
      NonZero: 'transforms/nonzero',
      Ratio: 'transforms/ratio',
      Seq: 'transforms/seq',
      Spread: 'transforms/spread',
      ToCounts: 'transforms/tocounts'
    };
    mod_cache = {};
    collection_overrides = {};
    Collections = function(typename) {
      var mod, modulename, submodulename, _ref;
      if (collection_overrides[typename]) {
        return collection_overrides[typename];
      }
      if (!locations[typename]) {
        throw "./base: Unknown Collection " + typename;
      }
      modulename = locations[typename];
      if (_.isArray(modulename)) {
        _ref = modulename, modulename = _ref[0], submodulename = _ref[1];
      } else {
        submodulename = null;
      }
      if (mod_cache[modulename] == null) {
        mod = require(modulename);
        if (mod != null) {
          mod_cache[modulename] = mod;
        } else {
          throw Error("improperly implemented collection: " + modulename);
        }
      }
      mod = mod_cache[modulename];
      if (submodulename != null) {
        mod = mod[submodulename];
      }
      return mod.Collection;
    };
    Collections.register = function(name, collection) {
      return collection_overrides[name] = collection;
    };
    index = {};
    return {
      "collection_overrides": collection_overrides,
      "mod_cache": mod_cache,
      "locations": locations,
      "index": index,
      "Collections": Collections,
      "Config": Config
    };
  });

}).call(this);

/*
//@ sourceMappingURL=base.js.map
*/;
(function() {
  define('common/load_models',["require", "./base", "./logging"], function(require, base, Logging) {
    var load_models, logger;
    logger = Logging.logger;
    return load_models = function(modelspecs) {
      var Collections, attrs, coll, coll_attrs, model, newspecs, oldspecs, _i, _j, _k, _l, _len, _len1, _len2, _len3, _len4, _m;
      newspecs = [];
      oldspecs = [];
      Collections = require("./base").Collections;
      logger.debug("load_models: start");
      for (_i = 0, _len = modelspecs.length; _i < _len; _i++) {
        model = modelspecs[_i];
        coll = Collections(model['type']);
        attrs = model['attributes'];
        if (coll && coll.get(attrs['id'])) {
          oldspecs.push([coll, attrs]);
        } else {
          newspecs.push([coll, attrs]);
        }
      }
      for (_j = 0, _len1 = newspecs.length; _j < _len1; _j++) {
        coll_attrs = newspecs[_j];
        coll = coll_attrs[0], attrs = coll_attrs[1];
        if (coll) {
          coll.add(attrs, {
            'silent': true,
            'defer_initialization': true
          });
        }
      }
      logger.debug("load_models: starting deferred initializations");
      for (_k = 0, _len2 = newspecs.length; _k < _len2; _k++) {
        coll_attrs = newspecs[_k];
        coll = coll_attrs[0], attrs = coll_attrs[1];
        if (coll) {
          coll.get(attrs['id']).initialize(attrs);
        }
      }
      logger.debug("load_models: finished deferred initializations");
      for (_l = 0, _len3 = newspecs.length; _l < _len3; _l++) {
        coll_attrs = newspecs[_l];
        coll = coll_attrs[0], attrs = coll_attrs[1];
        if (coll) {
          model = coll.get(attrs.id);
          model.trigger('add', model, coll, {});
        }
      }
      for (_m = 0, _len4 = oldspecs.length; _m < _len4; _m++) {
        coll_attrs = oldspecs[_m];
        coll = coll_attrs[0], attrs = coll_attrs[1];
        if (coll) {
          coll.get(attrs['id']).set(attrs);
        }
      }
      logger.debug("load_models: finish");
      return null;
    };
  });

}).call(this);

/*
//@ sourceMappingURL=load_models.js.map
*/;
(function() {
  define('common/bulk_save',["underscore", "jquery", "require", "./base", "./load_models"], function(_, $, require, base, load_models) {
    var bulk_save;
    return bulk_save = function(models) {
      var Config, doc, jsondata, m, url, xhr;
      Config = require("./base").Config;
      doc = models[0].get('doc');
      if (doc == null) {
        throw new Error("Unset 'doc' in " + models[0]);
      }
      jsondata = (function() {
        var _i, _len, _results;
        _results = [];
        for (_i = 0, _len = models.length; _i < _len; _i++) {
          m = models[_i];
          _results.push({
            type: m.type,
            attributes: _.clone(m.attributes)
          });
        }
        return _results;
      })();
      jsondata = JSON.stringify(jsondata);
      url = Config.prefix + "bokeh/bb/" + doc + "/bulkupsert";
      xhr = $.ajax({
        type: 'POST',
        url: url,
        contentType: "application/json",
        data: jsondata,
        header: {
          client: "javascript"
        }
      });
      xhr.done(function(data) {
        return load_models(data.modelspecs);
      });
      return xhr;
    };
  });

}).call(this);

/*
//@ sourceMappingURL=bulk_save.js.map
*/;
(function() {
  define('common/random',[], function() {
    var Random;
    return Random = (function() {
      function Random(seed) {
        this.seed = seed;
        this.multiplier = 1664525;
        this.modulo = 4294967296;
        this.offset = 1013904223;
        if (!((this.seed != null) && (0 <= seed && seed < 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;

    })();
  });

}).call(this);

/*
//@ sourceMappingURL=random.js.map
*/;
(function() {
  define('palettes/palettes',[], function() {
    return {
      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]
    };
  });

}).call(this);

/*
//@ sourceMappingURL=palettes.js.map
*/;
(function() {
  var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

  define('common/socket',["backbone", "underscore", "common/base", "common/load_models", "common/logging"], function(Backbone, _, base, load_models, Logging) {
    var Config, WebSocketWrapper, logger, submodels;
    Config = base.Config;
    logger = Logging.logger;
    WebSocketWrapper = (function() {
      _.extend(WebSocketWrapper.prototype, Backbone.Events);

      function WebSocketWrapper(ws_conn_string) {
        this.onmessage = __bind(this.onmessage, this);
        var error,
          _this = this;
        this.auth = {};
        this.ws_conn_string = ws_conn_string;
        this._connected = $.Deferred();
        this.connected = this._connected.promise();
        try {
          if (window.MozWebSocket) {
            this.s = new MozWebSocket(ws_conn_string);
          } else {
            this.s = new WebSocket(ws_conn_string);
          }
        } catch (_error) {
          error = _error;
          logger.error("websocket creation failed for connection string: " + ws_conn_string);
          logger.error(" - " + error);
        }
        this.s.onopen = function() {
          return _this._connected.resolve();
        };
        this.s.onmessage = this.onmessage;
      }

      WebSocketWrapper.prototype.onmessage = function(msg) {
        var data, index, topic;
        data = msg.data;
        index = data.indexOf(":");
        index = data.indexOf(":", index + 1);
        topic = data.substring(0, index);
        data = data.substring(index + 1);
        this.trigger("msg:" + topic, data);
        return null;
      };

      WebSocketWrapper.prototype.send = function(msg) {
        var _this = this;
        return $.when(this.connected).done(function() {
          return _this.s.send(msg);
        });
      };

      WebSocketWrapper.prototype.subscribe = function(topic, auth) {
        var msg;
        this.auth[topic] = auth;
        msg = JSON.stringify({
          msgtype: 'subscribe',
          topic: topic,
          auth: auth
        });
        return this.send(msg);
      };

      return WebSocketWrapper;

    })();
    submodels = function(wswrapper, topic, apikey) {
      wswrapper.subscribe(topic, apikey);
      return wswrapper.on("msg:" + topic, function(msg) {
        var clientid, model, msgobj, ref, _i, _len, _ref;
        msgobj = JSON.parse(msg);
        if (msgobj['msgtype'] === 'modelpush') {
          load_models(msgobj['modelspecs']);
        } else if (msgobj['msgtype'] === 'modeldel') {
          _ref = msgobj['modelspecs'];
          for (_i = 0, _len = _ref.length; _i < _len; _i++) {
            ref = _ref[_i];
            model = resolve_ref(ref['type'], ref['id']);
            if (model) {
              model.destroy({
                'local': true
              });
            }
          }
        } else if (msgobj['msgtype'] === 'status' && msgobj['status'][0] === 'subscribesuccess') {
          clientid = msgobj['status'][2];
          Config.clientid = clientid;
          $.ajaxSetup({
            'headers': {
              'Continuum-Clientid': clientid
            }
          });
        } else {
          log.warn("unknown msgtype '" + msgobj['msgtype'] + "' for message: " + msgobj);
        }
        return null;
      });
    };
    return {
      WebSocketWrapper: WebSocketWrapper,
      submodels: submodels
    };
  });

}).call(this);

/*
//@ sourceMappingURL=socket.js.map
*/;
(function() {
  define('server/serverutils',["jquery", "underscore", "common/base", "common/socket", "common/load_models", "common/logging", "backbone", "common/has_properties"], function($, _, base, socket, load_models, Logging, Backbone, HasProperties) {
    var Deferreds, Promises, WebSocketWrapper, configure_server, copy_on_write_mapping, exports, logger, submodels, utility;
    logger = Logging.logger;
    Deferreds = {};
    Promises = {};
    exports = {};
    WebSocketWrapper = socket.WebSocketWrapper;
    submodels = socket.submodels;
    Deferreds._doc_loaded = $.Deferred();
    Deferreds._doc_requested = $.Deferred();
    Promises.doc_loaded = Deferreds._doc_loaded.promise();
    Promises.doc_requested = Deferreds._doc_requested.promise();
    Promises.doc_promises = {};
    exports.wswrapper = null;
    exports.plotcontext = null;
    exports.plotcontextview = null;
    exports.Promises = Promises;
    copy_on_write_mapping = {};
    utility = {
      load_one_object_chain: function(docid, objid, is_public) {
        var headers, key, resp, tempdocid;
        if (is_public) {
          if (!copy_on_write_mapping[docid]) {
            copy_on_write_mapping[docid] = _.uniqueId('temporary');
          }
          tempdocid = copy_on_write_mapping[docid];
          key = "temporary-" + docid;
          headers = {};
          headers[key] = tempdocid;
          $.ajaxSetup({
            'headers': headers
          });
        }
        HasProperties.prototype.sync = Backbone.sync;
        resp = utility.make_websocket();
        resp = resp.then(function() {
          var Config, url;
          Config = require("common/base").Config;
          url = "" + Config.prefix + "bokeh/objinfo/" + docid + "/" + objid;
          logger.debug("load one object chain: " + url);
          resp = $.get(url);
          return resp;
        });
        resp.done(function(data) {
          var all_models, apikey;
          all_models = data['all_models'];
          load_models(all_models);
          apikey = data['apikey'];
          submodels(exports.wswrapper, "bokehplot:" + docid, apikey);
          if (is_public) {
            return submodels(exports.wswrapper, "bokehplot:" + tempdocid, null);
          }
        });
        return resp;
      },
      load_user: function() {
        var response;
        response = $.get('/bokeh/userinfo/', {});
        return response;
      },
      load_doc_by_title: function(title) {
        var Config, response;
        Config = require("common/base").Config;
        response = $.get(Config.prefix + "bokeh/doc", {
          title: title
        }).done(function(data) {
          var all_models, apikey, docid;
          all_models = data['all_models'];
          load_models(all_models);
          apikey = data['apikey'];
          docid = data['docid'];
          return submodels(exports.wswrapper, "bokehplot:" + docid, apikey);
        });
        return response;
      },
      load_doc_static: function(docid, data) {
        " loads data without making a websocket connection ";
        var promise;
        load_data(data['all_models']);
        promise = jQuery.Deferred();
        promise.resolve();
        return promise;
      },
      load_doc: function(docid) {
        var resp;
        resp = utility.make_websocket();
        resp = resp.then(function() {
          var Config;
          Config = require("common/base").Config;
          return $.get(Config.prefix + ("bokeh/bokehinfo/" + docid + "/"), {});
        });
        resp.done(function(data) {
          var all_models, apikey;
          all_models = data['all_models'];
          load_models(all_models);
          apikey = data['apikey'];
          return submodels(exports.wswrapper, "bokehplot:" + docid, apikey);
        });
        return resp;
      },
      make_websocket: function() {
        var Config, resp;
        if (exports.wswrapper != null) {
          return exports._wswrapper_deferred;
        } else {
          Config = require("common/base").Config;
          exports._wswrapper_deferred = $.get(Config.prefix + "bokeh/wsurl/");
          resp = exports._wswrapper_deferred;
          resp.done(function(data) {
            var wswrapper;
            Config = require("common/base").Config;
            configure_server(data, null);
            wswrapper = new WebSocketWrapper(Config.ws_conn_string);
            return exports.wswrapper = wswrapper;
          });
          return resp;
        }
      },
      render_plots: function(plot_context_ref, viewclass, viewoptions) {
        var Collections, options, plotcontext, plotcontextview;
        if (viewclass == null) {
          viewclass = null;
        }
        if (viewoptions == null) {
          viewoptions = {};
        }
        Collections = require("common/base").Collections;
        plotcontext = Collections(plot_context_ref.type).get(plot_context_ref.id);
        if (!viewclass) {
          viewclass = plotcontext.default_view;
        }
        options = _.extend(viewoptions, {
          model: plotcontext
        });
        plotcontextview = new viewclass(options);
        plotcontext = plotcontext;
        plotcontextview = plotcontextview;
        plotcontextview.render();
        exports.plotcontext = plotcontext;
        return exports.plotcontextview = plotcontextview;
      },
      bokeh_connection: function(host, docid, protocol) {
        if (_.isUndefined(protocol)) {
          protocol = "https";
        }
        if (Promises.doc_requested.state() === "pending") {
          Deferreds._doc_requested.resolve();
          return $.get("" + protocol + "://" + host + "/bokeh/publicbokehinfo/" + docid, {}, function(data) {
            logger.debug("instantiate_doc_single " + docid);
            data = JSON.parse(data);
            load_models(data['all_models']);
            return Deferreds._doc_loaded.resolve(data);
          });
        }
      }
    };
    configure_server = function(ws_conn_string, prefix) {
      var Config;
      Config = require("common/base").Config;
      if (ws_conn_string) {
        Config.ws_conn_string = ws_conn_string;
        logger.debug("setting ws_conn_string to: " + Config.ws_conn_string);
      }
      if (prefix) {
        Config.prefix = prefix;
        logger.debug("setting prefix to " + Config.prefix);
      }
      return null;
    };
    exports.utility = utility;
    exports.configure_server = configure_server;
    return exports;
  });

}).call(this);

/*
//@ sourceMappingURL=serverutils.js.map
*/;
define('server/usercontext/userdocstemplate',[],function(){
  var template = function(__obj) {
  var _safe = function(value) {
    if (typeof value === 'undefined' && value == null)
      value = '';
    var result = new String(value);
    result.ecoSafe = true;
    return result;
  };
  return (function() {
    var __out = [], __self = this, _print = function(value) {
      if (typeof value !== 'undefined' && value != null)
        __out.push(value.ecoSafe ? value : __self.escape(value));
    }, _capture = function(callback) {
      var out = __out, result;
      __out = [];
      callback.call(this);
      result = __out.join('');
      __out = out;
      return _safe(result);
    };
    (function() {
      _print(_safe('<div class="accordion">\n</div>\n'));
    
    }).call(this);
    
    return __out.join('');
  }).call((function() {
    var obj = {
      escape: function(value) {
        return ('' + value)
          .replace(/&/g, '&amp;')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;')
          .replace(/"/g, '&quot;');
      },
      safe: _safe
    }, key;
    for (key in __obj) obj[key] = __obj[key];
    return obj;
  })());
};
  return template;
});

define('server/usercontext/documentationtemplate',[],function(){
  var template = function(__obj) {
  var _safe = function(value) {
    if (typeof value === 'undefined' && value == null)
      value = '';
    var result = new String(value);
    result.ecoSafe = true;
    return result;
  };
  return (function() {
    var __out = [], __self = this, _print = function(value) {
      if (typeof value !== 'undefined' && value != null)
        __out.push(value.ecoSafe ? value : __self.escape(value));
    }, _capture = function(callback) {
      var out = __out, result;
      __out = [];
      callback.call(this);
      result = __out.join('');
      __out = out;
      return _safe(result);
    };
    (function() {
      _print(_safe('<p>\n  <b>\n    You have no Plots. Follow the instructions below to create some.\n  </b>\n</p>\n'));
    
    }).call(this);
    
    return __out.join('');
  }).call((function() {
    var obj = {
      escape: function(value) {
        return ('' + value)
          .replace(/&/g, '&amp;')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;')
          .replace(/"/g, '&quot;');
      },
      safe: _safe
    }, key;
    for (key in __obj) obj[key] = __obj[key];
    return obj;
  })());
};
  return template;
});

define('server/usercontext/wrappertemplate',[],function(){
  var template = function(__obj) {
  var _safe = function(value) {
    if (typeof value === 'undefined' && value == null)
      value = '';
    var result = new String(value);
    result.ecoSafe = true;
    return result;
  };
  return (function() {
    var __out = [], __self = this, _print = function(value) {
      if (typeof value !== 'undefined' && value != null)
        __out.push(value.ecoSafe ? value : __self.escape(value));
    }, _capture = function(callback) {
      var out = __out, result;
      __out = [];
      callback.call(this);
      result = __out.join('');
      __out = out;
      return _safe(result);
    };
    (function() {
      _print(_safe('<div class="panel panel-default">\n  <div class="panel-heading">\n    <h4 class="panel-title">\n      <a class="bokehdoclabel" href="#'));
    
      _print(this.bodyid);
    
      _print(_safe('" data-toggle="collapse">\n        Document: '));
    
      _print(this.model.get('title'));
    
      _print(_safe(' <span class="bokehdelete glyphicon glyphicon-trash"></i>\n      </a>\n    </h4>\n  </div>\n  <div id="'));
    
      _print(this.bodyid);
    
      _print(_safe('" class="panel-collapse collapse">\n    <div class="panel-body plots"></div>\n  </div>\n</div>\n'));
    
    }).call(this);
    
    return __out.join('');
  }).call((function() {
    var obj = {
      escape: function(value) {
        return ('' + value)
          .replace(/&/g, '&amp;')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;')
          .replace(/"/g, '&quot;');
      },
      safe: _safe
    }, key;
    for (key in __obj) obj[key] = __obj[key];
    return obj;
  })());
};
  return template;
});

(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('server/usercontext/usercontext',["underscore", "jquery", "common/base", "../serverutils", "common/continuum_view", "common/collection", "./userdocstemplate", "./documentationtemplate", "./wrappertemplate", "common/has_parent", "common/build_views", "common/load_models"], function(_, $, base, serverutils, ContinuumView, Collection, userdocstemplate, documentationtemplate, wrappertemplate, HasParent, build_views, load_models) {
    var Doc, DocView, UserDocs, UserDocsView, exports, utility, _ref, _ref1, _ref2, _ref3;
    exports = {};
    utility = serverutils.utility;
    DocView = (function(_super) {
      __extends(DocView, _super);

      function DocView() {
        _ref = DocView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      DocView.prototype.template = wrappertemplate;

      DocView.prototype.attributes = {
        "class": 'panel-group'
      };

      DocView.prototype.events = {
        "click .bokehdoclabel": "loaddoc",
        "click .bokehdelete": "deldoc"
      };

      DocView.prototype.deldoc = function(e) {
        e.preventDefault();
        this.model.destroy();
        return false;
      };

      DocView.prototype.loaddoc = function() {
        return this.model.load();
      };

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

      DocView.prototype.delegateEvents = function(events) {
        DocView.__super__.delegateEvents.call(this, events);
        return this.listenTo(this.model, 'loaded', this.render);
      };

      DocView.prototype.render_init = function() {
        var html;
        html = this.template({
          model: this.model,
          bodyid: _.uniqueId()
        });
        return this.$el.html(html);
      };

      DocView.prototype.render = function() {
        var plot_context;
        plot_context = this.model.get('plot_context');
        this.plot_context_view = new plot_context.default_view({
          model: plot_context
        });
        this.$el.find('.plots').append(this.plot_context_view.el);
        return true;
      };

      return DocView;

    })(ContinuumView);
    UserDocsView = (function(_super) {
      __extends(UserDocsView, _super);

      function UserDocsView() {
        _ref1 = UserDocsView.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      UserDocsView.prototype.initialize = function(options) {
        this.docs = options.docs;
        this.collection = options.collection;
        this.views = {};
        UserDocsView.__super__.initialize.call(this, options);
        return this.render();
      };

      UserDocsView.prototype.attributes = {
        "class": 'usercontext'
      };

      UserDocsView.prototype.events = {
        'click .bokehrefresh': function() {
          return this.collection.fetch({
            update: true
          });
        }
      };

      UserDocsView.prototype.delegateEvents = function(events) {
        var _this = this;
        UserDocsView.__super__.delegateEvents.call(this, events);
        this.listenTo(this.collection, 'add', this.render);
        this.listenTo(this.collection, 'remove', this.render);
        this.listenTo(this.collection, 'add', function(model, collection, options) {
          return _this.listenTo(model, 'loaded', function() {
            return _this.listenTo(model.get('plot_context'), 'change', function() {
              return _this.trigger('show');
            });
          });
        });
        return this.listenTo(this.collection, 'remove', function(model, collection, options) {
          return _this.stopListening(model);
        });
      };

      UserDocsView.prototype.render_docs = function() {
        this.$el.html(documentationtemplate());
        return this.$el.append(this.docs);
      };

      UserDocsView.prototype.render = function() {
        var html, model, models, _i, _len;
        if (this.collection.models.length === 0 && this.docs) {
          return this.render_docs();
        }
        html = userdocstemplate();
        _.map(_.values(this.views), function(view) {
          return view.$el.detach();
        });
        models = this.collection.models.slice().reverse();
        build_views(this.views, models, {});
        this.$el.html(html);
        for (_i = 0, _len = models.length; _i < _len; _i++) {
          model = models[_i];
          this.$el.find(".accordion").append(this.views[model.id].el);
        }
        return this;
      };

      return UserDocsView;

    })(ContinuumView);
    Doc = (function(_super) {
      __extends(Doc, _super);

      function Doc() {
        _ref2 = Doc.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      Doc.prototype.default_view = DocView;

      Doc.prototype.idAttribute = 'docid';

      Doc.prototype.defaults = function() {
        return _.extend({}, Doc.__super__.defaults.call(this), {
          docid: null,
          title: null,
          plot_context: null,
          apikey: null
        });
      };

      Doc.prototype.sync = function() {};

      Doc.prototype.destroy = function(options) {
        Doc.__super__.destroy.call(this, options);
        return $.ajax({
          url: "/bokeh/doc/" + (this.get('docid')) + "/",
          type: 'delete'
        });
      };

      Doc.prototype.load = function(use_title) {
        var docid, resp, title,
          _this = this;
        if (this.loaded) {
          return;
        }
        if (use_title) {
          title = this.get('title');
          resp = utility.load_doc_by_title(title);
        } else {
          docid = this.get('docid');
          resp = utility.load_doc(docid);
        }
        return resp.done(function(data) {
          _this.set('docid', data.docid);
          _this.set('apikey', data['apikey']);
          _this.set('plot_context', data['plot_context_ref']);
          _this.trigger('loaded');
          return _this.loaded = true;
        });
      };

      return Doc;

    })(HasParent);
    UserDocs = (function(_super) {
      __extends(UserDocs, _super);

      function UserDocs() {
        _ref3 = UserDocs.__super__.constructor.apply(this, arguments);
        return _ref3;
      }

      UserDocs.prototype.model = Doc;

      UserDocs.prototype.subscribe = function(wswrapper, username) {
        wswrapper.subscribe("bokehuser:" + username, null);
        return this.listenTo(wswrapper, "msg:bokehuser:" + username, function(msg) {
          msg = JSON.parse(msg);
          if (msg['msgtype'] === 'docchange') {
            return this.fetch({
              update: true
            });
          }
        });
      };

      UserDocs.prototype.fetch = function(options) {
        var resp, response, url,
          _this = this;
        if (_.isUndefined(options)) {
          options = {};
        }
        url = base.Config.prefix + "bokeh/userinfo/";
        resp = response = $.get(url, {});
        resp.done(function(data) {
          var docs;
          docs = data['docs'];
          if (options.update) {
            return _this.set(docs, options);
          } else {
            return _this.reset(docs, options);
          }
        });
        return resp;
      };

      return UserDocs;

    })(Collection);
    exports.UserDocs = UserDocs;
    exports.UserDocsView = UserDocsView;
    exports.Doc = Doc;
    exports.DocView = DocView;
    return exports;
  });

}).call(this);

/*
//@ sourceMappingURL=usercontext.js.map
*/;
(function() {
  define('server/embed',["jquery", "underscore", "./serverutils", "./usercontext/usercontext", "common/base", "common/has_properties", "common/load_models", "common/logging"], function($, _, serverutils, usercontext, base, HasProperties, load_models, Logging) {
    var add_plot_server, add_plot_static, copy_on_write_mapping, index, inject_css, inject_plot, logger, reload, server_page, _render, _render_all, _render_one;
    index = base.index;
    logger = Logging.logger;
    reload = function() {
      var Config, ping_url;
      Config = require("common/base").Config;
      ping_url = "" + Config.prefix + "bokeh/ping";
      $.get(ping_url).success(function() {
        logger.info('reloading');
        return window.location.reload();
      }).fail(_.delay((function() {
        return reload();
      }), 1000));
      return null;
    };
    inject_css = function(url) {
      var link;
      link = $("<link href='" + url + "' rel='stylesheet' type='text/css'>");
      return $('body').append(link);
    };
    add_plot_static = function(element, model_id, model_type, all_models) {
      var model, view;
      load_models(all_models);
      model = base.Collections(model_type).get(model_id);
      view = new model.default_view({
        model: model
      });
      if (!(model_id in index)) {
        index[model_id] = view;
      }
      return _.delay(function() {
        return $(element).replaceWith(view.$el);
      });
    };
    copy_on_write_mapping = {};
    add_plot_server = function(element, doc_id, model_id, is_public) {
      var resp;
      resp = serverutils.utility.load_one_object_chain(doc_id, model_id, is_public);
      return resp.done(function(data) {
        var model, view, wswrapper;
        model = base.Collections(data.type).get(model_id);
        view = new model.default_view({
          model: model
        });
        _.delay(function() {
          return $(element).replaceWith(view.$el);
        });
        if (!(model_id in index)) {
          index[model_id] = view;
        }
        wswrapper = serverutils.wswrapper;
        wswrapper.subscribe("debug:debug", "");
        return wswrapper.on('msg:debug:debug', function(msg) {
          if (msg === 'reload') {
            return reload();
          }
        });
      });
    };
    inject_plot = function(element_id, all_models) {
      var container, info, script;
      script = $("#" + element_id);
      if (script.length === 0) {
        throw "Error injecting plot: could not find script tag with id: " + element_id;
      }
      if (script.length > 1) {
        throw "Error injecting plot: found too many script tags with id: " + element_id;
      }
      if (!document.body.contains(script[0])) {
        throw "Error injecting plot: autoload script tag may only be under <body>";
      }
      info = script.data();
      Bokeh.set_log_level(info['bokehLoglevel']);
      logger.info("Injecting plot for script tag with id: #" + element_id);
      base.Config.prefix = info['bokehRootUrl'];
      container = $('<div>', {
        "class": 'bokeh-container'
      });
      container.insertBefore(script);
      if (info.bokehData === "static") {
        logger.info("  - using static data");
        return add_plot_static(container, info["bokehModelid"], info["bokehModeltype"], all_models);
      } else if (info.bokehData === "server") {
        logger.info("  - using server data");
        return add_plot_server(container, info["bokehDocid"], info["bokehModelid"], info["bokehPublic"]);
      } else {
        throw "Unknown bokehData value for inject_plot: " + info.bokehData;
      }
    };
    server_page = function(title) {
      HasProperties.prototype.sync = Backbone.sync;
      return $(function() {
        var resp;
        resp = serverutils.utility.make_websocket();
        return resp.then(function() {
          var load, userdocs, wswrapper;
          wswrapper = serverutils.wswrapper;
          userdocs = new usercontext.UserDocs();
          userdocs.subscribe(wswrapper, 'defaultuser');
          load = userdocs.fetch();
          load.done(function() {
            if (title != null) {
              return _render_one(userdocs, title);
            } else {
              return _render_all(userdocs);
            }
          });
          logger.info('subscribing to debug');
          wswrapper.subscribe("debug:debug", "");
          return wswrapper.on('msg:debug:debug', function(msg) {
            if (msg === 'reload') {
              return reload();
            }
          });
        });
      });
    };
    _render_all = function(userdocs) {
      var userdocsview;
      userdocsview = new usercontext.UserDocsView({
        collection: userdocs
      });
      return _render(userdocsview.el);
    };
    _render_one = function(userdocs, title) {
      var doc, msg;
      doc = userdocs.find(function(doc) {
        return doc.get('title') === title;
      });
      if (doc != null) {
        doc.on('loaded', function() {
          var plot_context, plot_context_view;
          plot_context = doc.get('plot_context');
          plot_context_view = new plot_context.default_view({
            model: plot_context
          });
          return _render(plot_context_view.el);
        });
        return doc.load();
      } else {
        msg = "Document '" + title + "' wasn't found on this server.";
        _render(msg);
        return logger.error(msg);
      }
    };
    _render = function(html) {
      return $('#PlotPane').append(html);
    };
    return {
      "inject_css": inject_css,
      "inject_plot": inject_plot,
      "add_plot_server": add_plot_server,
      "add_plot_static": add_plot_static,
      "server_page": server_page
    };
  });

}).call(this);

/*
//@ sourceMappingURL=embed.js.map
*/;
(function() {
  var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  define('tool/gestures/poly_select_tool',["underscore", "common/collection", "renderer/overlay/poly_selection", "tool/gestures/select_tool"], function(_, Collection, PolySelection, SelectTool) {
    var PolySelectTool, PolySelectToolView, PolySelectTools, _ref, _ref1, _ref2;
    PolySelectToolView = (function(_super) {
      __extends(PolySelectToolView, _super);

      function PolySelectToolView() {
        _ref = PolySelectToolView.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      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, _ref1;
        append = (_ref1 = e.srcEvent.shiftKey) != null ? _ref1 : 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, r, sm, _i, _len, _ref1;
        geometry = {
          type: 'poly',
          vx: vx,
          vy: vy
        };
        _ref1 = this.mget('renderers');
        for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
          r = _ref1[_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(_super) {
      __extends(PolySelectTool, _super);

      function PolySelectTool() {
        _ref1 = PolySelectTool.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      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);
    PolySelectTools = (function(_super) {
      __extends(PolySelectTools, _super);

      function PolySelectTools() {
        _ref2 = PolySelectTools.__super__.constructor.apply(this, arguments);
        return _ref2;
      }

      PolySelectTools.prototype.model = PolySelectTool;

      return PolySelectTools;

    })(Collection);
    return {
      "Model": PolySelectTool,
      "Collection": new PolySelectTools(),
      "View": PolySelectToolView
    };
  });

}).call(this);

/*
//@ sourceMappingURL=poly_select_tool.js.map
*/;
(function() {
  define('api/helpers',["underscore", "common/logging"], function(_, Logging) {
    var logger, show;
    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);
    };
    return {
      show: show
    };
  });

}).call(this);

/*
//@ sourceMappingURL=helpers.js.map
*/;
(function() {
  define('api/figure',["common/base", "common/logging", "range/factor_range", "range/range1d", "source/column_data_source", "./helpers"], function(base, Logging, FactorRange, Range1d, ColumnDataSource) {
    var Collections, add_annotations, add_glyphs, add_guides, add_tools, figure, logger, make_plot, make_sources, _get_axis_type, _get_num_minor_ticks, _get_range, _get_sources, _process_annotations, _process_glyphs, _process_guides, _process_tools;
    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) {
      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) {
            "pass";
          }
          return Collections("LinearAxis");
        }
      }
      try {
        return Collections(axis_type + "Axis");
      } catch (_error) {
        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) {
      var tool, tool_args, tool_obj, tool_objs, tool_type, _i, _len;
      tool_objs = [];
      for (_i = 0, _len = tools.length; _i < _len; _i++) {
        tool = tools[_i];
        if (_.isString(tool)) {
          tool_type = tool + "Tool";
          tool_args = {};
        } 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) {
          logger.error("unrecognized tool: " + tool);
        }
      }
      return tool_objs;
    };
    _process_glyphs = function(glyphs, sources) {
      var glyph, glyph_args, glyph_obj, glyph_type, renderer, renderer_args, renderers, source, x, x_args, x_obj, _i, _j, _len, _len1, _ref;
      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, location, range, _i, _len;
      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, loc, location, _i, _len;
      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 tool, _i, _len;
      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();
    };
    return 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;
    };
  });

}).call(this);

/*
//@ sourceMappingURL=figure.js.map
*/;
(function() {
  define('api/plugin',["underscore", "jquery", "common/logging", "./figure", "./helpers"], function(_, $, Logging, figure, helpers) {
    var logger, show, _api;
    logger = Logging.logger;
    show = helpers.show;
    _api = {
      "figure": figure
    };
    return $.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;
    };
  });

}).call(this);

/*
//@ sourceMappingURL=plugin.js.map
*/;
(function() {
  define('main',['require','exports','module','common/base','common/logging','underscore','jquery','backbone','common/base','common/base','common/cartesian_frame','common/canvas','common/gmap_plot','common/geojs_plot','common/grid_plot','common/has_parent','common/has_properties','common/layout_box','common/plot','common/selection_manager','common/selector','common/tool_events','common/build_views','common/bulk_save','common/continuum_view','common/load_models','common/plot_context','common/plot_widget','common/random','common/svg_colors','mapper/linear_mapper','mapper/log_mapper','mapper/categorical_mapper','mapper/grid_mapper','mapper/linear_color_mapper','palettes/palettes','renderer/annotation/legend','renderer/annotation/span','renderer/annotation/tooltip','renderer/guide/categorical_axis','renderer/guide/datetime_axis','renderer/guide/grid','renderer/guide/linear_axis','renderer/guide/log_axis','renderer/overlay/box_selection','renderer/overlay/poly_selection','renderer/properties','server/embed','server/serverutils','source/column_data_source','ticking/abstract_ticker','ticking/adaptive_ticker','ticking/basic_ticker','ticking/basic_tick_formatter','ticking/log_ticker','ticking/log_tick_formatter','ticking/categorical_ticker','ticking/categorical_tick_formatter','ticking/composite_ticker','ticking/datetime_ticker','ticking/datetime_tick_formatter','ticking/days_ticker','ticking/months_ticker','ticking/single_interval_ticker','ticking/years_ticker','tool/actions/action_tool','tool/actions/preview_save_tool','tool/actions/reset_tool','tool/gestures/box_select_tool','tool/gestures/box_zoom_tool','tool/gestures/lasso_select_tool','tool/gestures/pan_tool','tool/gestures/poly_select_tool','tool/gestures/resize_tool','tool/gestures/select_tool','tool/gestures/tap_tool','tool/gestures/wheel_zoom_tool','tool/inspectors/inspect_tool','tool/inspectors/hover_tool','tool/inspectors/crosshair_tool','widget/hbox','widget/vbox','widget/text_input','widget/crossfilter','api/plugin'],function(require, exports, module) {
    var Bokeh, logging, _oldJQ;
    Bokeh = {};
    Bokeh.require = require;
    Bokeh.version = '0.8.0';
    Bokeh.index = require("common/base").index;
    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._ = require("underscore");
    Bokeh.$ = require("jquery");
    Bokeh.Backbone = require("backbone");
    _oldJQ = window.$;
    window.jQuery.noConflict();
    if (typeof $ === "undefined") {
      window.$ = _oldJQ;
    }
    Bokeh.Collections = require("common/base").Collections;
    Bokeh.Config = require("common/base").Config;
    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.SelectionManager = require("common/selection_manager");
    Bokeh.Selector = require("common/selector");
    Bokeh.ToolEvents = require("common/tool_events");
    Bokeh.build_views = require("common/build_views");
    Bokeh.bulk_save = require("common/bulk_save");
    Bokeh.ContinuumView = require("common/continuum_view");
    Bokeh.load_models = require("common/load_models");
    Bokeh.PlotContext = require("common/plot_context");
    Bokeh.PlotWidget = require("common/plot_widget");
    Bokeh.Random = require("common/random");
    Bokeh.SVGColors = require("common/svg_colors");
    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.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.Properties = require("renderer/properties");
    Bokeh.embed = require("server/embed");
    Bokeh.serverutils = require("server/serverutils");
    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.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");
    Bokeh.HBox = require("widget/hbox");
    Bokeh.VBox = require("widget/vbox");
    Bokeh.TextInput = require("widget/text_input");
    Bokeh.CrossFilter = require("widget/crossfilter");
    require("api/plugin");
    exports.Bokeh = Bokeh;
    return Bokeh;
  });

}).call(this);

/*
//@ sourceMappingURL=main.js.map
*/;

  //The modules for your project will be inlined above
  //this snippet. Ask almond to synchronously require the
  //module value for 'main' here and return it as the
  //value to use for the public API for the built file.
  return require('main');
}));
