target
stringlengths
5
300
feat_repo_name
stringlengths
6
76
text
stringlengths
26
1.05M
test/components/LocationDisambiguationComponentTest.js
chimo/se-dir-frontend-react
/* eslint-env node, mocha */ /* global expect */ /* eslint no-console: 0 */ 'use strict'; import React from 'react'; import { shallow } from 'enzyme'; import { LocationDisambiguationComponent } from 'components/LocationDisambiguationComponent.js'; describe('LocationDisambiguationComponent', () => { let component; let locations = [ { 'placeName': 'Omineca and Yellowhead (Smithers)', 'latitude': '55.9964', 'longitude': '-126.8574' }, { 'placeName': 'Smiths Falls', 'latitude': '44.9001', 'longitude': '-76.0161' }]; beforeEach(() => { component = shallow(<LocationDisambiguationComponent t={key => key} locations={locations} />); }); it('should have its component name as default className', () => { expect(component.hasClass('locationdisambiguation-component')).to.equal(true); }); });
src/svg-icons/action/three-d-rotation.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionThreeDRotation = (props) => ( <SvgIcon {...props}> <path d="M7.52 21.48C4.25 19.94 1.91 16.76 1.55 13H.05C.56 19.16 5.71 24 12 24l.66-.03-3.81-3.81-1.33 1.32zm.89-6.52c-.19 0-.37-.03-.52-.08-.16-.06-.29-.13-.4-.24-.11-.1-.2-.22-.26-.37-.06-.14-.09-.3-.09-.47h-1.3c0 .36.07.68.21.95.14.27.33.5.56.69.24.18.51.32.82.41.3.1.62.15.96.15.37 0 .72-.05 1.03-.15.32-.1.6-.25.83-.44s.42-.43.55-.72c.13-.29.2-.61.2-.97 0-.19-.02-.38-.07-.56-.05-.18-.12-.35-.23-.51-.1-.16-.24-.3-.4-.43-.17-.13-.37-.23-.61-.31.2-.09.37-.2.52-.33.15-.13.27-.27.37-.42.1-.15.17-.3.22-.46.05-.16.07-.32.07-.48 0-.36-.06-.68-.18-.96-.12-.28-.29-.51-.51-.69-.2-.19-.47-.33-.77-.43C9.1 8.05 8.76 8 8.39 8c-.36 0-.69.05-1 .16-.3.11-.57.26-.79.45-.21.19-.38.41-.51.67-.12.26-.18.54-.18.85h1.3c0-.17.03-.32.09-.45s.14-.25.25-.34c.11-.09.23-.17.38-.22.15-.05.3-.08.48-.08.4 0 .7.1.89.31.19.2.29.49.29.86 0 .18-.03.34-.08.49-.05.15-.14.27-.25.37-.11.1-.25.18-.41.24-.16.06-.36.09-.58.09H7.5v1.03h.77c.22 0 .42.02.6.07s.33.13.45.23c.12.11.22.24.29.4.07.16.1.35.1.57 0 .41-.12.72-.35.93-.23.23-.55.33-.95.33zm8.55-5.92c-.32-.33-.7-.59-1.14-.77-.43-.18-.92-.27-1.46-.27H12v8h2.3c.55 0 1.06-.09 1.51-.27.45-.18.84-.43 1.16-.76.32-.33.57-.73.74-1.19.17-.47.26-.99.26-1.57v-.4c0-.58-.09-1.1-.26-1.57-.18-.47-.43-.87-.75-1.2zm-.39 3.16c0 .42-.05.79-.14 1.13-.1.33-.24.62-.43.85-.19.23-.43.41-.71.53-.29.12-.62.18-.99.18h-.91V9.12h.97c.72 0 1.27.23 1.64.69.38.46.57 1.12.57 1.99v.4zM12 0l-.66.03 3.81 3.81 1.33-1.33c3.27 1.55 5.61 4.72 5.96 8.48h1.5C23.44 4.84 18.29 0 12 0z"/> </SvgIcon> ); ActionThreeDRotation = pure(ActionThreeDRotation); ActionThreeDRotation.displayName = 'ActionThreeDRotation'; ActionThreeDRotation.muiName = 'SvgIcon'; export default ActionThreeDRotation;
docs/src/app/components/pages/components/FlatButton/ExampleComplex.js
skarnecki/material-ui
import React from 'react'; import FlatButton from 'material-ui/FlatButton'; import FontIcon from 'material-ui/FontIcon'; import ActionAndroid from 'material-ui/svg-icons/action/android'; const styles = { exampleImageInput: { cursor: 'pointer', position: 'absolute', top: 0, bottom: 0, right: 0, left: 0, width: '100%', opacity: 0, }, }; const FlatButtonExampleComplex = () => ( <div> <FlatButton label="Choose an Image" labelPosition="before"> <input type="file" style={styles.exampleImageInput} /> </FlatButton> <FlatButton label="Label before" labelPosition="before" primary={true} style={styles.button} icon={<ActionAndroid />} /> <FlatButton label="GitHub Link" linkButton={true} href="https://github.com/callemall/material-ui" secondary={true} icon={<FontIcon className="muidocs-icon-custom-github" />} /> </div> ); export default FlatButtonExampleComplex;
fields/types/number/NumberField.js
BlakeRxxk/keystone
import React from 'react'; import Field from '../Field'; import { FormInput } from 'elemental'; module.exports = Field.create({ displayName: 'NumberField', valueChanged (event) { var newValue = event.target.value.replace(/[^\d\.]/g, ''); if (newValue === this.props.value) return; this.props.onChange({ path: this.props.path, value: newValue }); }, renderField () { return <FormInput name={this.props.path} ref="focusTarget" value={this.props.value} onChange={this.valueChanged} autoComplete="off" />; } });
ajax/libs/yui/3.9.1/event-focus/event-focus-min.js
tonytomov/cdnjs
YUI.add("event-focus",function(e,t){function u(t,r,u){var a="_"+t+"Notifiers";e.Event.define(t,{_useActivate:o,_attach:function(i,s,o){return e.DOM.isWindow(i)?n._attach([t,function(e){s.fire(e)},i]):n._attach([r,this._proxy,i,this,s,o],{capture:!0})},_proxy:function(t,r,i){var s=t.target,f=t.currentTarget,l=s.getData(a),c=e.stamp(f._node),h=o||s!==f,p;r.currentTarget=i?s:f,r.container=i?f:null,l?h=!0:(l={},s.setData(a,l),h&&(p=n._attach([u,this._notify,s._node]).sub,p.once=!0)),l[c]||(l[c]=[]),l[c].push(r),h||this._notify(t)},_notify:function(t,n){var r=t.currentTarget,i=r.getData(a),o=r.ancestors(),u=r.get("ownerDocument"),f=[],l=i?e.Object.keys(i).length:0,c,h,p,d,v,m,g,y,b,w;r.clearData(a),o.push(r),u&&o.unshift(u),o._nodes.reverse(),l&&(m=l,o.some(function(t){var n=e.stamp(t),r=i[n],s,o;if(r){l--;for(s=0,o=r.length;s<o;++s)r[s].handle.sub.filter&&f.push(r[s])}return!l}),l=m);while(l&&(c=o.shift())){d=e.stamp(c),h=i[d];if(h){for(g=0,y=h.length;g<y;++g){p=h[g],b=p.handle.sub,v=!0,t.currentTarget=c,b.filter&&(v=b.filter.apply(c,[c,t].concat(b.args||[])),f.splice(s(f,p),1)),v&&(t.container=p.container,w=p.fire(t));if(w===!1||t.stopped===2)break}delete h[d],l--}if(t.stopped!==2)for(g=0,y=f.length;g<y;++g){p=f[g],b=p.handle.sub,b.filter.apply(c,[c,t].concat(b.args||[]))&&(t.container=p.container,t.currentTarget=c,w=p.fire(t));if(w===!1||t.stopped===2)break}if(t.stopped)break}},on:function(e,t,n){t.handle=this._attach(e._node,n)},detach:function(e,t){t.handle.detach()},delegate:function(t,n,r,s){i(s)&&(n.filter=function(n){return e.Selector.test(n._node,s,t===n?null:t._node)}),n.handle=this._attach(t._node,r,!0)},detachDelegate:function(e,t){t.handle.detach()}},!0)}var n=e.Event,r=e.Lang,i=r.isString,s=e.Array.indexOf,o=function(){var t=!1,n=e.config.doc,r;return n&&(r=n.createElement("p"),r.setAttribute("onbeforeactivate",";"),t=r.onbeforeactivate!==undefined),t}();o?(u("focus","beforeactivate","focusin"),u("blur","beforedeactivate","focusout")):(u("focus","focus","focus"),u("blur","blur","blur"))},"@VERSION@",{requires:["event-synthetic"]});
src/layouts/Frame.js
hiddaorear/Theory
import React, { Component } from 'react'; import Nav from './Nav'; class Frame extends Component { render() { return ( <div className="frame"> <section className="header"> <Nav /> </section> <section className="container"> {this.props.children} </section> </div> ) } } export default Frame;
ui/src/main/frontend/src/index.js
Dokuro-YH/alice-projects
import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter as Router } from 'react-router-dom'; import 'bootstrap/dist/css/bootstrap.css'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; ReactDOM.render( <Router> <App /> </Router>, document.getElementById('root') ); registerServiceWorker();
src/__tests__/utils.js
neoziro/recompact
import React from 'react' import { setDisplayName, toClass } from '..' import createHelper from '../createHelper' export const countRenders = createHelper( BaseComponent => class extends React.Component { renderCount = 0 render() { this.renderCount += 1 return <BaseComponent renderCount={this.renderCount} {...this.props} /> } }, 'countRenders', true, true, ) export const Dummy = setDisplayName('Dummy')(toClass(() => <div />))
ajax/libs/react-bootstrap-typeahead/0.7.0/react-bootstrap-typeahead.js
redmunds/cdnjs
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react"), require("react-dom")); else if(typeof define === 'function' && define.amd) define(["react", "react-dom"], factory); else if(typeof exports === 'object') exports["ReactBootstrapTypeahead"] = factory(require("react"), require("react-dom")); else root["ReactBootstrapTypeahead"] = factory(root["React"], root["ReactDOM"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_1__, __WEBPACK_EXTERNAL_MODULE_4__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var Typeahead = __webpack_require__(9); module.exports = Typeahead; /***/ }, /* 1 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_1__; /***/ }, /* 2 */ /***/ function(module, exports) { /** * KeyCode * * Map of common (non-printable) keycodes for the `keydown` and `keyup` events. * Note that `keypress` handles things differently and may not return the same * values. */ "use strict"; module.exports = { BACKSPACE: 8, TAB: 9, RETURN: 13, ESC: 27, SPACE: 32, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40 }; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ (function () { 'use strict'; var hasOwn = {}.hasOwnProperty; function classNames () { var classes = []; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (!arg) continue; var argType = typeof arg; if (argType === 'string' || argType === 'number') { classes.push(arg); } else if (Array.isArray(arg)) { classes.push(classNames.apply(null, arg)); } else if (argType === 'object') { for (var key in arg) { if (hasOwn.call(arg, key) && arg[key]) { classes.push(key); } } } } return classes.join(' '); } if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } else if (true) { // register as 'classnames', consistent with npm package name !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else { window.classNames = classNames; } }()); /***/ }, /* 4 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_4__; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(module, global) {/** * @license * lodash <https://lodash.com/> * Copyright jQuery Foundation and other contributors <https://jquery.org/> * Released under MIT license <https://lodash.com/license> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ ;(function() { /** Used as a safe reference for `undefined` in pre-ES5 environments. */ var undefined; /** Used as the semantic version number. */ var VERSION = '4.12.0'; /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** Used to compose bitmasks for wrapper metadata. */ var BIND_FLAG = 1, BIND_KEY_FLAG = 2, CURRY_BOUND_FLAG = 4, CURRY_FLAG = 8, CURRY_RIGHT_FLAG = 16, PARTIAL_FLAG = 32, PARTIAL_RIGHT_FLAG = 64, ARY_FLAG = 128, REARG_FLAG = 256, FLIP_FLAG = 512; /** Used to compose bitmasks for comparison styles. */ var UNORDERED_COMPARE_FLAG = 1, PARTIAL_COMPARE_FLAG = 2; /** Used as default options for `_.truncate`. */ var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = '...'; /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 150, HOT_SPAN = 16; /** Used to indicate the type of lazy iteratees. */ var LAZY_FILTER_FLAG = 1, LAZY_MAP_FLAG = 2, LAZY_WHILE_FLAG = 3; /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0, MAX_SAFE_INTEGER = 9007199254740991, MAX_INTEGER = 1.7976931348623157e+308, NAN = 0 / 0; /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = 4294967295, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', promiseTag = '[object Promise]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', weakMapTag = '[object WeakMap]', weakSetTag = '[object WeakSet]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to match empty string literals in compiled template source. */ var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; /** Used to match HTML entities and HTML characters. */ var reEscapedHtml = /&(?:amp|lt|gt|quot|#39|#96);/g, reUnescapedHtml = /[&<>"'`]/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source); /** Used to match template delimiters. */ var reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g; /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]/g; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/6.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar.source); /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g, reTrimStart = /^\s+/, reTrimEnd = /\s+$/; /** Used to match non-compound words composed of alphanumeric characters. */ var reBasicWord = /[a-zA-Z0-9]+/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Used to match * [ES template delimiters](http://ecma-international.org/ecma-262/6.0/#sec-template-literal-lexical-components). */ var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** Used to detect hexadecimal string values. */ var reHasHexPrefix = /^0x/i; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** Used to match latin-1 supplementary letters (excluding mathematical operators). */ var reLatin1 = /[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g; /** Used to ensure capturing order of template delimiters. */ var reNoMatch = /($^)/; /** Used to match unescaped characters in compiled string literals. */ var reUnescapedString = /['\n\r\u2028\u2029\\]/g; /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23', rsComboSymbolsRange = '\\u20d0-\\u20f0', rsDingbatRange = '\\u2700-\\u27bf', rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', rsPunctuationRange = '\\u2000-\\u206f', rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', rsVarRange = '\\ufe0e\\ufe0f', rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; /** Used to compose unicode capture groups. */ var rsApos = "['\u2019]", rsAstral = '[' + rsAstralRange + ']', rsBreak = '[' + rsBreakRange + ']', rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']', rsDigits = '\\d+', rsDingbat = '[' + rsDingbatRange + ']', rsLower = '[' + rsLowerRange + ']', rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', rsFitz = '\\ud83c[\\udffb-\\udfff]', rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', rsNonAstral = '[^' + rsAstralRange + ']', rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', rsUpper = '[' + rsUpperRange + ']', rsZWJ = '\\u200d'; /** Used to compose unicode regexes. */ var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')', rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')', rsOptLowerContr = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', rsOptUpperContr = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', reOptMod = rsModifier + '?', rsOptVar = '[' + rsVarRange + ']?', rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; /** Used to match apostrophes. */ var reApos = RegExp(rsApos, 'g'); /** * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). */ var reComboMark = RegExp(rsCombo, 'g'); /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ var reComplexSymbol = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); /** Used to match complex or compound words. */ var reComplexWord = RegExp([ rsUpper + '?' + rsLower + '+' + rsOptLowerContr + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', rsUpperMisc + '+' + rsOptUpperContr + '(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')', rsUpper + '?' + rsLowerMisc + '+' + rsOptLowerContr, rsUpper + '+' + rsOptUpperContr, rsDigits, rsEmoji ].join('|'), 'g'); /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ var reHasComplexSymbol = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']'); /** Used to detect strings that need a more robust regexp to match words. */ var reHasComplexWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; /** Used to assign default `context` object properties. */ var contextProps = [ 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', 'Promise', 'Reflect', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' ]; /** Used to make template sourceURLs easier to identify. */ var templateCounter = -1; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; /** Used to map latin-1 supplementary letters to basic latin letters. */ var deburredLetters = { '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', '\xc7': 'C', '\xe7': 'c', '\xd0': 'D', '\xf0': 'd', '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', '\xcC': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', '\xeC': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', '\xd1': 'N', '\xf1': 'n', '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', '\xc6': 'Ae', '\xe6': 'ae', '\xde': 'Th', '\xfe': 'th', '\xdf': 'ss' }; /** Used to map characters to HTML entities. */ var htmlEscapes = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;', '`': '&#96;' }; /** Used to map HTML entities to characters. */ var htmlUnescapes = { '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&#39;': "'", '&#96;': '`' }; /** Used to determine if values are of the language type `Object`. */ var objectTypes = { 'function': true, 'object': true }; /** Used to escape characters for inclusion in compiled string literals. */ var stringEscapes = { '\\': '\\', "'": "'", '\n': 'n', '\r': 'r', '\u2028': 'u2028', '\u2029': 'u2029' }; /** Built-in method references without a dependency on `root`. */ var freeParseFloat = parseFloat, freeParseInt = parseInt; /** Detect free variable `exports`. */ var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType) ? exports : undefined; /** Detect free variable `module`. */ var freeModule = (objectTypes[typeof module] && module && !module.nodeType) ? module : undefined; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = (freeModule && freeModule.exports === freeExports) ? freeExports : undefined; /** Detect free variable `global` from Node.js. */ var freeGlobal = checkGlobal(freeExports && freeModule && typeof global == 'object' && global); /** Detect free variable `self`. */ var freeSelf = checkGlobal(objectTypes[typeof self] && self); /** Detect free variable `window`. */ var freeWindow = checkGlobal(objectTypes[typeof window] && window); /** Detect `this` as the global object. */ var thisGlobal = checkGlobal(objectTypes[typeof this] && this); /** * Used as a reference to the global object. * * The `this` value is used if it's the global object to avoid Greasemonkey's * restricted `window` object, otherwise the `window` object is used. */ var root = freeGlobal || ((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) || freeSelf || thisGlobal || Function('return this')(); /*--------------------------------------------------------------------------*/ /** * Adds the key-value `pair` to `map`. * * @private * @param {Object} map The map to modify. * @param {Array} pair The key-value pair to add. * @returns {Object} Returns `map`. */ function addMapEntry(map, pair) { // Don't return `Map#set` because it doesn't return the map instance in IE 11. map.set(pair[0], pair[1]); return map; } /** * Adds `value` to `set`. * * @private * @param {Object} set The set to modify. * @param {*} value The value to add. * @returns {Object} Returns `set`. */ function addSetEntry(set, value) { set.add(value); return set; } /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { var length = args.length; switch (length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } /** * A specialized version of `baseAggregator` for arrays. * * @private * @param {Array} array The array to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function arrayAggregator(array, setter, iteratee, accumulator) { var index = -1, length = array.length; while (++index < length) { var value = array[index]; setter(accumulator, value, iteratee(value), array); } return accumulator; } /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } /** * A specialized version of `_.forEachRight` for arrays without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEachRight(array, iteratee) { var length = array.length; while (length--) { if (iteratee(array[length], length, array) === false) { break; } } return array; } /** * A specialized version of `_.every` for arrays without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. */ function arrayEvery(array, predicate) { var index = -1, length = array.length; while (++index < length) { if (!predicate(array[index], index, array)) { return false; } } return true; } /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } /** * A specialized version of `_.includes` for arrays without support for * specifying an index to search from. * * @private * @param {Array} array The array to search. * @param {*} target The value to search for. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludes(array, value) { return !!array.length && baseIndexOf(array, value, 0) > -1; } /** * This function is like `arrayIncludes` except that it accepts a comparator. * * @private * @param {Array} array The array to search. * @param {*} target The value to search for. * @param {Function} comparator The comparator invoked per element. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludesWith(array, value, comparator) { var index = -1, length = array.length; while (++index < length) { if (comparator(value, array[index])) { return true; } } return false; } /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } /** * A specialized version of `_.reduce` for arrays without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the first element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array.length; if (initAccum && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } /** * A specialized version of `_.reduceRight` for arrays without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the last element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduceRight(array, iteratee, accumulator, initAccum) { var length = array.length; if (initAccum && length) { accumulator = array[--length]; } while (length--) { accumulator = iteratee(accumulator, array[length], length, array); } return accumulator; } /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } /** * The base implementation of methods like `_.find` and `_.findKey`, without * support for iteratee shorthands, which iterates over `collection` using * `eachFunc`. * * @private * @param {Array|Object} collection The collection to search. * @param {Function} predicate The function invoked per iteration. * @param {Function} eachFunc The function to iterate over `collection`. * @param {boolean} [retKey] Specify returning the key of the found element * instead of the element itself. * @returns {*} Returns the found element or its key, else `undefined`. */ function baseFind(collection, predicate, eachFunc, retKey) { var result; eachFunc(collection, function(value, key, collection) { if (predicate(value, key, collection)) { result = retKey ? key : value; return false; } }); return result; } /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to search. * @param {Function} predicate The function invoked per iteration. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromRight) { var length = array.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to search. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { if (value !== value) { return indexOfNaN(array, fromIndex); } var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } /** * This function is like `baseIndexOf` except that it accepts a comparator. * * @private * @param {Array} array The array to search. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @param {Function} comparator The comparator invoked per element. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOfWith(array, value, fromIndex, comparator) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (comparator(array[index], value)) { return index; } } return -1; } /** * The base implementation of `_.mean` and `_.meanBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the mean. */ function baseMean(array, iteratee) { var length = array ? array.length : 0; return length ? (baseSum(array, iteratee) / length) : NAN; } /** * The base implementation of `_.reduce` and `_.reduceRight`, without support * for iteratee shorthands, which iterates over `collection` using `eachFunc`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} accumulator The initial value. * @param {boolean} initAccum Specify using the first or last element of * `collection` as the initial value. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the accumulated value. */ function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { eachFunc(collection, function(value, index, collection) { accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection); }); return accumulator; } /** * The base implementation of `_.sortBy` which uses `comparer` to define the * sort order of `array` and replaces criteria objects with their corresponding * values. * * @private * @param {Array} array The array to sort. * @param {Function} comparer The function to define sort order. * @returns {Array} Returns `array`. */ function baseSortBy(array, comparer) { var length = array.length; array.sort(comparer); while (length--) { array[length] = array[length].value; } return array; } /** * The base implementation of `_.sum` and `_.sumBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the sum. */ function baseSum(array, iteratee) { var result, index = -1, length = array.length; while (++index < length) { var current = iteratee(array[index]); if (current !== undefined) { result = result === undefined ? current : (result + current); } } return result; } /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } /** * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array * of key-value pairs for `object` corresponding to the property names of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the key-value pairs. */ function baseToPairs(object, props) { return arrayMap(props, function(key) { return [key, object[key]]; }); } /** * The base implementation of `_.unary` without support for storing wrapper metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names * of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the array of property values. */ function baseValues(object, props) { return arrayMap(props, function(key) { return object[key]; }); } /** * Checks if a cache value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } /** * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the first unmatched string symbol. */ function charsStartIndex(strSymbols, chrSymbols) { var index = -1, length = strSymbols.length; while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } /** * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the last unmatched string symbol. */ function charsEndIndex(strSymbols, chrSymbols) { var index = strSymbols.length; while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } /** * Checks if `value` is a global object. * * @private * @param {*} value The value to check. * @returns {null|Object} Returns `value` if it's a global object, else `null`. */ function checkGlobal(value) { return (value && value.Object === Object) ? value : null; } /** * Gets the number of `placeholder` occurrences in `array`. * * @private * @param {Array} array The array to inspect. * @param {*} placeholder The placeholder to search for. * @returns {number} Returns the placeholder count. */ function countHolders(array, placeholder) { var length = array.length, result = 0; while (length--) { if (array[length] === placeholder) { result++; } } return result; } /** * Used by `_.deburr` to convert latin-1 supplementary letters to basic latin letters. * * @private * @param {string} letter The matched letter to deburr. * @returns {string} Returns the deburred letter. */ function deburrLetter(letter) { return deburredLetters[letter]; } /** * Used by `_.escape` to convert characters to HTML entities. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ function escapeHtmlChar(chr) { return htmlEscapes[chr]; } /** * Used by `_.template` to escape characters for inclusion in compiled string literals. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ function escapeStringChar(chr) { return '\\' + stringEscapes[chr]; } /** * Gets the index at which the first occurrence of `NaN` is found in `array`. * * @private * @param {Array} array The array to search. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched `NaN`, else `-1`. */ function indexOfNaN(array, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 0 : -1); while ((fromRight ? index-- : ++index < length)) { var other = array[index]; if (other !== other) { return index; } } return -1; } /** * Checks if `value` is a host object in IE < 9. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a host object, else `false`. */ function isHostObject(value) { // Many host objects are `Object` objects that can coerce to strings // despite having improperly defined `toString` methods. var result = false; if (value != null && typeof value.toString != 'function') { try { result = !!(value + ''); } catch (e) {} } return result; } /** * Converts `iterator` to an array. * * @private * @param {Object} iterator The iterator to convert. * @returns {Array} Returns the converted array. */ function iteratorToArray(iterator) { var data, result = []; while (!(data = iterator.next()).done) { result.push(data.value); } return result; } /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } /** * Replaces all `placeholder` elements in `array` with an internal placeholder * and returns an array of their indexes. * * @private * @param {Array} array The array to modify. * @param {*} placeholder The placeholder to replace. * @returns {Array} Returns the new array of placeholder indexes. */ function replaceHolders(array, placeholder) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value === placeholder || value === PLACEHOLDER) { array[index] = PLACEHOLDER; result[resIndex++] = index; } } return result; } /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } /** * Converts `set` to its value-value pairs. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the value-value pairs. */ function setToPairs(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = [value, value]; }); return result; } /** * Gets the number of symbols in `string`. * * @private * @param {string} string The string to inspect. * @returns {number} Returns the string size. */ function stringSize(string) { if (!(string && reHasComplexSymbol.test(string))) { return string.length; } var result = reComplexSymbol.lastIndex = 0; while (reComplexSymbol.test(string)) { result++; } return result; } /** * Converts `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function stringToArray(string) { return string.match(reComplexSymbol); } /** * Used by `_.unescape` to convert HTML entities to characters. * * @private * @param {string} chr The matched character to unescape. * @returns {string} Returns the unescaped character. */ function unescapeHtmlChar(chr) { return htmlUnescapes[chr]; } /*--------------------------------------------------------------------------*/ /** * Create a new pristine `lodash` function using the `context` object. * * @static * @memberOf _ * @since 1.1.0 * @category Util * @param {Object} [context=root] The context object. * @returns {Function} Returns a new `lodash` function. * @example * * _.mixin({ 'foo': _.constant('foo') }); * * var lodash = _.runInContext(); * lodash.mixin({ 'bar': lodash.constant('bar') }); * * _.isFunction(_.foo); * // => true * _.isFunction(_.bar); * // => false * * lodash.isFunction(lodash.foo); * // => false * lodash.isFunction(lodash.bar); * // => true * * // Use `context` to mock `Date#getTime` use in `_.now`. * var mock = _.runInContext({ * 'Date': function() { * return { 'getTime': getTimeMock }; * } * }); * * // Create a suped-up `defer` in Node.js. * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; */ function runInContext(context) { context = context ? _.defaults({}, context, _.pick(root, contextProps)) : root; /** Built-in constructor references. */ var Date = context.Date, Error = context.Error, Math = context.Math, RegExp = context.RegExp, TypeError = context.TypeError; /** Used for built-in method references. */ var arrayProto = context.Array.prototype, objectProto = context.Object.prototype, stringProto = context.String.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = context.Function.prototype.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to generate unique IDs. */ var idCounter = 0; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** Used to restore the original `_` reference in `_.noConflict`. */ var oldDash = root._; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** Built-in value references. */ var Buffer = moduleExports ? context.Buffer : undefined, Reflect = context.Reflect, Symbol = context.Symbol, Uint8Array = context.Uint8Array, clearTimeout = context.clearTimeout, enumerate = Reflect ? Reflect.enumerate : undefined, getOwnPropertySymbols = Object.getOwnPropertySymbols, iteratorSymbol = typeof (iteratorSymbol = Symbol && Symbol.iterator) == 'symbol' ? iteratorSymbol : undefined, objectCreate = Object.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, setTimeout = context.setTimeout, splice = arrayProto.splice; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeCeil = Math.ceil, nativeFloor = Math.floor, nativeGetPrototype = Object.getPrototypeOf, nativeIsFinite = context.isFinite, nativeJoin = arrayProto.join, nativeKeys = Object.keys, nativeMax = Math.max, nativeMin = Math.min, nativeParseInt = context.parseInt, nativeRandom = Math.random, nativeReplace = stringProto.replace, nativeReverse = arrayProto.reverse, nativeSplit = stringProto.split; /* Built-in method references that are verified to be native. */ var DataView = getNative(context, 'DataView'), Map = getNative(context, 'Map'), Promise = getNative(context, 'Promise'), Set = getNative(context, 'Set'), WeakMap = getNative(context, 'WeakMap'), nativeCreate = getNative(Object, 'create'); /** Used to store function metadata. */ var metaMap = WeakMap && new WeakMap; /** Detect if properties shadowing those on `Object.prototype` are non-enumerable. */ var nonEnumShadows = !propertyIsEnumerable.call({ 'valueOf': 1 }, 'valueOf'); /** Used to lookup unminified function names. */ var realNames = {}; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /*------------------------------------------------------------------------*/ /** * Creates a `lodash` object which wraps `value` to enable implicit method * chain sequences. Methods that operate on and return arrays, collections, * and functions can be chained together. Methods that retrieve a single value * or may return a primitive value will automatically end the chain sequence * and return the unwrapped value. Otherwise, the value must be unwrapped * with `_#value`. * * Explicit chain sequences, which must be unwrapped with `_#value`, may be * enabled using `_.chain`. * * The execution of chained methods is lazy, that is, it's deferred until * `_#value` is implicitly or explicitly called. * * Lazy evaluation allows several methods to support shortcut fusion. * Shortcut fusion is an optimization to merge iteratee calls; this avoids * the creation of intermediate arrays and can greatly reduce the number of * iteratee executions. Sections of a chain sequence qualify for shortcut * fusion if the section is applied to an array of at least `200` elements * and any iteratees accept only one argument. The heuristic for whether a * section qualifies for shortcut fusion is subject to change. * * Chaining is supported in custom builds as long as the `_#value` method is * directly or indirectly included in the build. * * In addition to lodash methods, wrappers have `Array` and `String` methods. * * The wrapper `Array` methods are: * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` * * The wrapper `String` methods are: * `replace` and `split` * * The wrapper methods that support shortcut fusion are: * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` * * The chainable wrapper methods are: * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, * `zipObject`, `zipObjectDeep`, and `zipWith` * * The wrapper methods that are **not** chainable by default are: * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `deburr`, `divide`, `each`, * `eachRight`, `endsWith`, `eq`, `escape`, `escapeRegExp`, `every`, `find`, * `findIndex`, `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `first`, * `floor`, `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, * `forOwnRight`, `get`, `gt`, `gte`, `has`, `hasIn`, `head`, `identity`, * `includes`, `indexOf`, `inRange`, `invoke`, `isArguments`, `isArray`, * `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, `isBoolean`, * `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, `isEqualWith`, * `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, `isMap`, * `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, `isNumber`, * `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, `isSafeInteger`, * `isSet`, `isString`, `isUndefined`, `isTypedArray`, `isWeakMap`, `isWeakSet`, * `join`, `kebabCase`, `last`, `lastIndexOf`, `lowerCase`, `lowerFirst`, * `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, `min`, `minBy`, `multiply`, * `noConflict`, `noop`, `now`, `nth`, `pad`, `padEnd`, `padStart`, `parseInt`, * `pop`, `random`, `reduce`, `reduceRight`, `repeat`, `result`, `round`, * `runInContext`, `sample`, `shift`, `size`, `snakeCase`, `some`, `sortedIndex`, * `sortedIndexBy`, `sortedLastIndex`, `sortedLastIndexBy`, `startCase`, * `startsWith`, `subtract`, `sum`, `sumBy`, `template`, `times`, `toFinite`, * `toInteger`, `toJSON`, `toLength`, `toLower`, `toNumber`, `toSafeInteger`, * `toString`, `toUpper`, `trim`, `trimEnd`, `trimStart`, `truncate`, `unescape`, * `uniqueId`, `upperCase`, `upperFirst`, `value`, and `words` * * @name _ * @constructor * @category Seq * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2, 3]); * * // Returns an unwrapped value. * wrapped.reduce(_.add); * // => 6 * * // Returns a wrapped value. * var squares = wrapped.map(square); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { if (value instanceof LodashWrapper) { return value; } if (hasOwnProperty.call(value, '__wrapped__')) { return wrapperClone(value); } } return new LodashWrapper(value); } /** * The function whose prototype chain sequence wrappers inherit from. * * @private */ function baseLodash() { // No operation performed. } /** * The base constructor for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap. * @param {boolean} [chainAll] Enable explicit method chain sequences. */ function LodashWrapper(value, chainAll) { this.__wrapped__ = value; this.__actions__ = []; this.__chain__ = !!chainAll; this.__index__ = 0; this.__values__ = undefined; } /** * By default, the template delimiters used by lodash are like those in * embedded Ruby (ERB). Change the following template settings to use * alternative delimiters. * * @static * @memberOf _ * @type {Object} */ lodash.templateSettings = { /** * Used to detect `data` property values to be HTML-escaped. * * @memberOf _.templateSettings * @type {RegExp} */ 'escape': reEscape, /** * Used to detect code to be evaluated. * * @memberOf _.templateSettings * @type {RegExp} */ 'evaluate': reEvaluate, /** * Used to detect `data` property values to inject. * * @memberOf _.templateSettings * @type {RegExp} */ 'interpolate': reInterpolate, /** * Used to reference the data object in the template text. * * @memberOf _.templateSettings * @type {string} */ 'variable': '', /** * Used to import variables into the compiled template. * * @memberOf _.templateSettings * @type {Object} */ 'imports': { /** * A reference to the `lodash` function. * * @memberOf _.templateSettings.imports * @type {Function} */ '_': lodash } }; // Ensure wrappers are instances of `baseLodash`. lodash.prototype = baseLodash.prototype; lodash.prototype.constructor = lodash; LodashWrapper.prototype = baseCreate(baseLodash.prototype); LodashWrapper.prototype.constructor = LodashWrapper; /*------------------------------------------------------------------------*/ /** * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @private * @constructor * @param {*} value The value to wrap. */ function LazyWrapper(value) { this.__wrapped__ = value; this.__actions__ = []; this.__dir__ = 1; this.__filtered__ = false; this.__iteratees__ = []; this.__takeCount__ = MAX_ARRAY_LENGTH; this.__views__ = []; } /** * Creates a clone of the lazy wrapper object. * * @private * @name clone * @memberOf LazyWrapper * @returns {Object} Returns the cloned `LazyWrapper` object. */ function lazyClone() { var result = new LazyWrapper(this.__wrapped__); result.__actions__ = copyArray(this.__actions__); result.__dir__ = this.__dir__; result.__filtered__ = this.__filtered__; result.__iteratees__ = copyArray(this.__iteratees__); result.__takeCount__ = this.__takeCount__; result.__views__ = copyArray(this.__views__); return result; } /** * Reverses the direction of lazy iteration. * * @private * @name reverse * @memberOf LazyWrapper * @returns {Object} Returns the new reversed `LazyWrapper` object. */ function lazyReverse() { if (this.__filtered__) { var result = new LazyWrapper(this); result.__dir__ = -1; result.__filtered__ = true; } else { result = this.clone(); result.__dir__ *= -1; } return result; } /** * Extracts the unwrapped value from its lazy wrapper. * * @private * @name value * @memberOf LazyWrapper * @returns {*} Returns the unwrapped value. */ function lazyValue() { var array = this.__wrapped__.value(), dir = this.__dir__, isArr = isArray(array), isRight = dir < 0, arrLength = isArr ? array.length : 0, view = getView(0, arrLength, this.__views__), start = view.start, end = view.end, length = end - start, index = isRight ? end : (start - 1), iteratees = this.__iteratees__, iterLength = iteratees.length, resIndex = 0, takeCount = nativeMin(length, this.__takeCount__); if (!isArr || arrLength < LARGE_ARRAY_SIZE || (arrLength == length && takeCount == length)) { return baseWrapperValue(array, this.__actions__); } var result = []; outer: while (length-- && resIndex < takeCount) { index += dir; var iterIndex = -1, value = array[index]; while (++iterIndex < iterLength) { var data = iteratees[iterIndex], iteratee = data.iteratee, type = data.type, computed = iteratee(value); if (type == LAZY_MAP_FLAG) { value = computed; } else if (!computed) { if (type == LAZY_FILTER_FLAG) { continue outer; } else { break outer; } } } result[resIndex++] = value; } return result; } // Ensure `LazyWrapper` is an instance of `baseLodash`. LazyWrapper.prototype = baseCreate(baseLodash.prototype); LazyWrapper.prototype.constructor = LazyWrapper; /*------------------------------------------------------------------------*/ /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; } /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { return this.has(key) && delete this.__data__[key]; } /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); } /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; /*------------------------------------------------------------------------*/ /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; } /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } return true; } /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { data.push([key, value]); } else { data[index][1] = value; } return this; } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; /*------------------------------------------------------------------------*/ /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { return getMapData(this, key)['delete'](key); } /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { getMapData(this, key).set(key, value); return this; } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; /*------------------------------------------------------------------------*/ /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values ? values.length : 0; this.__data__ = new MapCache; while (++index < length) { this.add(values[index]); } } /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; /*------------------------------------------------------------------------*/ /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { this.__data__ = new ListCache(entries); } /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache; } /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { return this.__data__['delete'](key); } /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var cache = this.__data__; if (cache instanceof ListCache && cache.__data__.length == LARGE_ARRAY_SIZE) { cache = this.__data__ = new MapCache(cache.__data__); } cache.set(key, value); return this; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; /*------------------------------------------------------------------------*/ /** * Used by `_.defaults` to customize its `_.assignIn` use. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to assign. * @param {Object} object The parent object of `objValue`. * @returns {*} Returns the value to assign. */ function assignInDefaults(objValue, srcValue, key, object) { if (objValue === undefined || (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { return srcValue; } return objValue; } /** * This function is like `assignValue` except that it doesn't assign * `undefined` values. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignMergeValue(object, key, value) { if ((value !== undefined && !eq(object[key], value)) || (typeof key == 'number' && value === undefined && !(key in object))) { object[key] = value; } } /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || (value === undefined && !(key in object))) { object[key] = value; } } /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to search. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } /** * Aggregates elements of `collection` on `accumulator` with keys transformed * by `iteratee` and values set by `setter`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function baseAggregator(collection, setter, iteratee, accumulator) { baseEach(collection, function(value, key, collection) { setter(accumulator, value, iteratee(value), collection); }); return accumulator; } /** * The base implementation of `_.assign` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return object && copyObject(source, keys(source), object); } /** * The base implementation of `_.at` without support for individual paths. * * @private * @param {Object} object The object to iterate over. * @param {string[]} paths The property paths of elements to pick. * @returns {Array} Returns the picked elements. */ function baseAt(object, paths) { var index = -1, isNil = object == null, length = paths.length, result = Array(length); while (++index < length) { result[index] = isNil ? undefined : get(object, paths[index]); } return result; } /** * The base implementation of `_.clamp` which doesn't coerce arguments to numbers. * * @private * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. */ function baseClamp(number, lower, upper) { if (number === number) { if (upper !== undefined) { number = number <= upper ? number : upper; } if (lower !== undefined) { number = number >= lower ? number : lower; } } return number; } /** * The base implementation of `_.clone` and `_.cloneDeep` which tracks * traversed objects. * * @private * @param {*} value The value to clone. * @param {boolean} [isDeep] Specify a deep clone. * @param {boolean} [isFull] Specify a clone including symbols. * @param {Function} [customizer] The function to customize cloning. * @param {string} [key] The key of `value`. * @param {Object} [object] The parent object of `value`. * @param {Object} [stack] Tracks traversed objects and their clone counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, isDeep, isFull, customizer, key, object, stack) { var result; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject(value)) { return value; } var isArr = isArray(value); if (isArr) { result = initCloneArray(value); if (!isDeep) { return copyArray(value, result); } } else { var tag = getTag(value), isFunc = tag == funcTag || tag == genTag; if (isBuffer(value)) { return cloneBuffer(value, isDeep); } if (tag == objectTag || tag == argsTag || (isFunc && !object)) { if (isHostObject(value)) { return object ? value : {}; } result = initCloneObject(isFunc ? {} : value); if (!isDeep) { return copySymbols(value, baseAssign(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = initCloneByTag(value, tag, baseClone, isDeep); } } // Check for circular references and return its corresponding clone. stack || (stack = new Stack); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); if (!isArr) { var props = isFull ? getAllKeys(value) : keys(value); } // Recursively populate clone (susceptible to call stack limits). arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; subValue = value[key]; } assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack)); }); return result; } /** * The base implementation of `_.conforms` which doesn't clone `source`. * * @private * @param {Object} source The object of property predicates to conform to. * @returns {Function} Returns the new spec function. */ function baseConforms(source) { var props = keys(source), length = props.length; return function(object) { if (object == null) { return !length; } var index = length; while (index--) { var key = props[index], predicate = source[key], value = object[key]; if ((value === undefined && !(key in Object(object))) || !predicate(value)) { return false; } } return true; }; } /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} prototype The object to inherit from. * @returns {Object} Returns the new object. */ function baseCreate(proto) { return isObject(proto) ? objectCreate(proto) : {}; } /** * The base implementation of `_.delay` and `_.defer` which accepts an array * of `func` arguments. * * @private * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {Object} args The arguments to provide to `func`. * @returns {number} Returns the timer id. */ function baseDelay(func, wait, args) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return setTimeout(function() { func.apply(undefined, args); }, wait); } /** * The base implementation of methods like `_.difference` without support * for excluding multiple arrays or iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values, iteratee, comparator) { var index = -1, includes = arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { return result; } if (iteratee) { values = arrayMap(values, baseUnary(iteratee)); } if (comparator) { includes = arrayIncludesWith; isCommon = false; } else if (values.length >= LARGE_ARRAY_SIZE) { includes = cacheHas; isCommon = false; values = new SetCache(values); } outer: while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === computed) { continue outer; } } result.push(value); } else if (!includes(values, computed, comparator)) { result.push(value); } } return result; } /** * The base implementation of `_.forEach` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEach = createBaseEach(baseForOwn); /** * The base implementation of `_.forEachRight` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEachRight = createBaseEach(baseForOwnRight, true); /** * The base implementation of `_.every` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false` */ function baseEvery(collection, predicate) { var result = true; baseEach(collection, function(value, index, collection) { result = !!predicate(value, index, collection); return result; }); return result; } /** * The base implementation of methods like `_.max` and `_.min` which accepts a * `comparator` to determine the extremum value. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The iteratee invoked per iteration. * @param {Function} comparator The comparator used to compare values. * @returns {*} Returns the extremum value. */ function baseExtremum(array, iteratee, comparator) { var index = -1, length = array.length; while (++index < length) { var value = array[index], current = iteratee(value); if (current != null && (computed === undefined ? (current === current && !isSymbol(current)) : comparator(current, computed) )) { var computed = current, result = value; } } return result; } /** * The base implementation of `_.fill` without an iteratee call guard. * * @private * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. */ function baseFill(array, value, start, end) { var length = array.length; start = toInteger(start); if (start < 0) { start = -start > length ? 0 : (length + start); } end = (end === undefined || end > length) ? length : toInteger(end); if (end < 0) { end += length; } end = start > end ? 0 : toLength(end); while (start < end) { array[start++] = value; } return array; } /** * The base implementation of `_.filter` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function baseFilter(collection, predicate) { var result = []; baseEach(collection, function(value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; } /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); /** * This function is like `baseFor` except that it iterates over properties * in the opposite order. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseForRight = createBaseFor(true); /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return object && baseFor(object, iteratee, keys); } /** * The base implementation of `_.forOwnRight` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwnRight(object, iteratee) { return object && baseForRight(object, iteratee, keys); } /** * The base implementation of `_.functions` which creates an array of * `object` function property names filtered from `props`. * * @private * @param {Object} object The object to inspect. * @param {Array} props The property names to filter. * @returns {Array} Returns the function names. */ function baseFunctions(object, props) { return arrayFilter(props, function(key) { return isFunction(object[key]); }); } /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = isKey(path, object) ? [path] : castPath(path); var index = 0, length = path.length; while (object != null && index < length) { object = object[toKey(path[index++])]; } return (index && index == length) ? object : undefined; } /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } /** * The base implementation of `_.gt` which doesn't coerce arguments to numbers. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than `other`, * else `false`. */ function baseGt(value, other) { return value > other; } /** * The base implementation of `_.has` without support for deep paths. * * @private * @param {Object} object The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHas(object, key) { // Avoid a bug in IE 10-11 where objects with a [[Prototype]] of `null`, // that are composed entirely of index properties, return `false` for // `hasOwnProperty` checks of them. return hasOwnProperty.call(object, key) || (typeof object == 'object' && key in object && getPrototype(object) === null); } /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} object The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return key in Object(object); } /** * The base implementation of `_.inRange` which doesn't coerce arguments to numbers. * * @private * @param {number} number The number to check. * @param {number} start The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `number` is in the range, else `false`. */ function baseInRange(number, start, end) { return number >= nativeMin(start, end) && number < nativeMax(start, end); } /** * The base implementation of methods like `_.intersection`, without support * for iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of shared values. */ function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { var array = arrays[othIndex]; if (othIndex && iteratee) { array = arrayMap(array, baseUnary(iteratee)); } maxLength = nativeMin(array.length, maxLength); caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) ? new SetCache(othIndex && array) : undefined; } array = arrays[0]; var index = -1, seen = caches[0]; outer: while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (!(seen ? cacheHas(seen, computed) : includes(result, computed, comparator) )) { othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache ? cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator)) ) { continue outer; } } if (seen) { seen.push(computed); } result.push(value); } } return result; } /** * The base implementation of `_.invert` and `_.invertBy` which inverts * `object` with values transformed by `iteratee` and set by `setter`. * * @private * @param {Object} object The object to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform values. * @param {Object} accumulator The initial inverted object. * @returns {Function} Returns `accumulator`. */ function baseInverter(object, setter, iteratee, accumulator) { baseForOwn(object, function(value, key, object) { setter(accumulator, iteratee(value), key, object); }); return accumulator; } /** * The base implementation of `_.invoke` without support for individual * method arguments. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the method to invoke. * @param {Array} args The arguments to invoke the method with. * @returns {*} Returns the result of the invoked method. */ function baseInvoke(object, path, args) { if (!isKey(path, object)) { path = castPath(path); object = parent(object, path); path = last(path); } var func = object == null ? object : object[toKey(path)]; return func == null ? undefined : apply(func, object, args); } /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize comparisons. * @param {boolean} [bitmask] The bitmask of comparison flags. * The bitmask may be composed of the following flags: * 1 - Unordered comparison * 2 - Partial comparison * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, customizer, bitmask, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack); } /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} [customizer] The function to customize comparisons. * @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual` * for more details. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = arrayTag, othTag = arrayTag; if (!objIsArr) { objTag = getTag(object); objTag = objTag == argsTag ? objectTag : objTag; } if (!othIsArr) { othTag = getTag(other); othTag = othTag == argsTag ? objectTag : othTag; } var objIsObj = objTag == objectTag && !isHostObject(object), othIsObj = othTag == objectTag && !isHostObject(other), isSameTag = objTag == othTag; if (isSameTag && !objIsObj) { stack || (stack = new Stack); return (objIsArr || isTypedArray(object)) ? equalArrays(object, other, equalFunc, customizer, bitmask, stack) : equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack); } if (!(bitmask & PARTIAL_COMPARE_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack); return equalFunc(objUnwrapped, othUnwrapped, customizer, bitmask, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack); return equalObjects(object, other, equalFunc, customizer, bitmask, stack); } /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG, stack) : result )) { return false; } } } return true; } /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity; } if (typeof value == 'object') { return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); } return property(value); } /** * The base implementation of `_.keys` which doesn't skip the constructor * property of prototypes or treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { return nativeKeys(Object(object)); } /** * The base implementation of `_.keysIn` which doesn't skip the constructor * property of prototypes or treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeysIn(object) { object = object == null ? object : Object(object); var result = []; for (var key in object) { result.push(key); } return result; } // Fallback for IE < 9 with es6-shim. if (enumerate && !propertyIsEnumerable.call({ 'valueOf': 1 }, 'valueOf')) { baseKeysIn = function(object) { return iteratorToArray(enumerate(object)); }; } /** * The base implementation of `_.lt` which doesn't coerce arguments to numbers. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than `other`, * else `false`. */ function baseLt(value, other) { return value < other; } /** * The base implementation of `_.map` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || baseIsMatch(object, source, matchData); }; } /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (isKey(path) && isStrictComparable(srcValue)) { return matchesStrictComparable(toKey(path), srcValue); } return function(object) { var objValue = get(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn(object, path) : baseIsEqual(srcValue, objValue, undefined, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG); }; } /** * The base implementation of `_.merge` without support for multiple sources. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {number} srcIndex The index of `source`. * @param {Function} [customizer] The function to customize merged values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMerge(object, source, srcIndex, customizer, stack) { if (object === source) { return; } if (!(isArray(source) || isTypedArray(source))) { var props = keysIn(source); } arrayEach(props || source, function(srcValue, key) { if (props) { key = srcValue; srcValue = source[key]; } if (isObject(srcValue)) { stack || (stack = new Stack); baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); } else { var newValue = customizer ? customizer(object[key], srcValue, (key + ''), object, source, stack) : undefined; if (newValue === undefined) { newValue = srcValue; } assignMergeValue(object, key, newValue); } }); } /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {number} srcIndex The index of `source`. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize assigned values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { var objValue = object[key], srcValue = source[key], stacked = stack.get(srcValue); if (stacked) { assignMergeValue(object, key, stacked); return; } var newValue = customizer ? customizer(objValue, srcValue, (key + ''), object, source, stack) : undefined; var isCommon = newValue === undefined; if (isCommon) { newValue = srcValue; if (isArray(srcValue) || isTypedArray(srcValue)) { if (isArray(objValue)) { newValue = objValue; } else if (isArrayLikeObject(objValue)) { newValue = copyArray(objValue); } else { isCommon = false; newValue = baseClone(srcValue, true); } } else if (isPlainObject(srcValue) || isArguments(srcValue)) { if (isArguments(objValue)) { newValue = toPlainObject(objValue); } else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) { isCommon = false; newValue = baseClone(srcValue, true); } else { newValue = objValue; } } else { isCommon = false; } } stack.set(srcValue, newValue); if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). mergeFunc(newValue, srcValue, srcIndex, customizer, stack); } stack['delete'](srcValue); assignMergeValue(object, key, newValue); } /** * The base implementation of `_.nth` which doesn't coerce `n` to an integer. * * @private * @param {Array} array The array to query. * @param {number} n The index of the element to return. * @returns {*} Returns the nth element of `array`. */ function baseNth(array, n) { var length = array.length; if (!length) { return; } n += n < 0 ? length : 0; return isIndex(n, length) ? array[n] : undefined; } /** * The base implementation of `_.orderBy` without param guards. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. * @param {string[]} orders The sort orders of `iteratees`. * @returns {Array} Returns the new sorted array. */ function baseOrderBy(collection, iteratees, orders) { var index = -1; iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(getIteratee())); var result = baseMap(collection, function(value, key, collection) { var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); }); return { 'criteria': criteria, 'index': ++index, 'value': value }; }); return baseSortBy(result, function(object, other) { return compareMultiple(object, other, orders); }); } /** * The base implementation of `_.pick` without support for individual * property identifiers. * * @private * @param {Object} object The source object. * @param {string[]} props The property identifiers to pick. * @returns {Object} Returns the new object. */ function basePick(object, props) { object = Object(object); return arrayReduce(props, function(result, key) { if (key in object) { result[key] = object[key]; } return result; }, {}); } /** * The base implementation of `_.pickBy` without support for iteratee shorthands. * * @private * @param {Object} object The source object. * @param {Function} predicate The function invoked per property. * @returns {Object} Returns the new object. */ function basePickBy(object, predicate) { var index = -1, props = getAllKeysIn(object), length = props.length, result = {}; while (++index < length) { var key = props[index], value = object[key]; if (predicate(value, key)) { result[key] = value; } } return result; } /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { return function(object) { return baseGet(object, path); }; } /** * The base implementation of `_.pullAllBy` without support for iteratee * shorthands. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns `array`. */ function basePullAll(array, values, iteratee, comparator) { var indexOf = comparator ? baseIndexOfWith : baseIndexOf, index = -1, length = values.length, seen = array; if (iteratee) { seen = arrayMap(array, baseUnary(iteratee)); } while (++index < length) { var fromIndex = 0, value = values[index], computed = iteratee ? iteratee(value) : value; while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { if (seen !== array) { splice.call(seen, fromIndex, 1); } splice.call(array, fromIndex, 1); } } return array; } /** * The base implementation of `_.pullAt` without support for individual * indexes or capturing the removed elements. * * @private * @param {Array} array The array to modify. * @param {number[]} indexes The indexes of elements to remove. * @returns {Array} Returns `array`. */ function basePullAt(array, indexes) { var length = array ? indexes.length : 0, lastIndex = length - 1; while (length--) { var index = indexes[length]; if (length == lastIndex || index !== previous) { var previous = index; if (isIndex(index)) { splice.call(array, index, 1); } else if (!isKey(index, array)) { var path = castPath(index), object = parent(array, path); if (object != null) { delete object[toKey(last(path))]; } } else { delete array[toKey(index)]; } } } return array; } /** * The base implementation of `_.random` without support for returning * floating-point numbers. * * @private * @param {number} lower The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the random number. */ function baseRandom(lower, upper) { return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); } /** * The base implementation of `_.range` and `_.rangeRight` which doesn't * coerce arguments to numbers. * * @private * @param {number} start The start of the range. * @param {number} end The end of the range. * @param {number} step The value to increment or decrement by. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the range of numbers. */ function baseRange(start, end, step, fromRight) { var index = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result = Array(length); while (length--) { result[fromRight ? length : ++index] = start; start += step; } return result; } /** * The base implementation of `_.repeat` which doesn't coerce arguments. * * @private * @param {string} string The string to repeat. * @param {number} n The number of times to repeat the string. * @returns {string} Returns the repeated string. */ function baseRepeat(string, n) { var result = ''; if (!string || n < 1 || n > MAX_SAFE_INTEGER) { return result; } // Leverage the exponentiation by squaring algorithm for a faster repeat. // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. do { if (n % 2) { result += string; } n = nativeFloor(n / 2); if (n) { string += string; } } while (n); return result; } /** * The base implementation of `_.set`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseSet(object, path, value, customizer) { path = isKey(path, object) ? [path] : castPath(path); var index = -1, length = path.length, lastIndex = length - 1, nested = object; while (nested != null && ++index < length) { var key = toKey(path[index]); if (isObject(nested)) { var newValue = value; if (index != lastIndex) { var objValue = nested[key]; newValue = customizer ? customizer(objValue, key, nested) : undefined; if (newValue === undefined) { newValue = objValue == null ? (isIndex(path[index + 1]) ? [] : {}) : objValue; } } assignValue(nested, key, newValue); } nested = nested[key]; } return object; } /** * The base implementation of `setData` without support for hot loop detection. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var baseSetData = !metaMap ? identity : function(func, data) { metaMap.set(func, data); return func; }; /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : (length + start); } end = end > length ? length : end; if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } /** * The base implementation of `_.some` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function baseSome(collection, predicate) { var result; baseEach(collection, function(value, index, collection) { result = predicate(value, index, collection); return !result; }); return !!result; } /** * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which * performs a binary search of `array` to determine the index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function baseSortedIndex(array, value, retHighest) { var low = 0, high = array ? array.length : low; if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { while (low < high) { var mid = (low + high) >>> 1, computed = array[mid]; if (computed !== null && !isSymbol(computed) && (retHighest ? (computed <= value) : (computed < value))) { low = mid + 1; } else { high = mid; } } return high; } return baseSortedIndexBy(array, value, identity, retHighest); } /** * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` * which invokes `iteratee` for `value` and each element of `array` to compute * their sort ranking. The iteratee is invoked with one argument; (value). * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} iteratee The iteratee invoked per element. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function baseSortedIndexBy(array, value, iteratee, retHighest) { value = iteratee(value); var low = 0, high = array ? array.length : 0, valIsNaN = value !== value, valIsNull = value === null, valIsSymbol = isSymbol(value), valIsUndefined = value === undefined; while (low < high) { var mid = nativeFloor((low + high) / 2), computed = iteratee(array[mid]), othIsDefined = computed !== undefined, othIsNull = computed === null, othIsReflexive = computed === computed, othIsSymbol = isSymbol(computed); if (valIsNaN) { var setLow = retHighest || othIsReflexive; } else if (valIsUndefined) { setLow = othIsReflexive && (retHighest || othIsDefined); } else if (valIsNull) { setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); } else if (valIsSymbol) { setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); } else if (othIsNull || othIsSymbol) { setLow = false; } else { setLow = retHighest ? (computed <= value) : (computed < value); } if (setLow) { low = mid + 1; } else { high = mid; } } return nativeMin(high, MAX_ARRAY_INDEX); } /** * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseSortedUniq(array, iteratee) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; if (!index || !eq(computed, seen)) { var seen = computed; result[resIndex++] = value === 0 ? 0 : value; } } return result; } /** * The base implementation of `_.toNumber` which doesn't ensure correct * conversions of binary, hexadecimal, or octal string values. * * @private * @param {*} value The value to process. * @returns {number} Returns the number. */ function baseToNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } return +value; } /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * The base implementation of `_.uniqBy` without support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseUniq(array, iteratee, comparator) { var index = -1, includes = arrayIncludes, length = array.length, isCommon = true, result = [], seen = result; if (comparator) { isCommon = false; includes = arrayIncludesWith; } else if (length >= LARGE_ARRAY_SIZE) { var set = iteratee ? null : createSet(array); if (set) { return setToArray(set); } isCommon = false; includes = cacheHas; seen = new SetCache; } else { seen = iteratee ? [] : result; } outer: while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var seenIndex = seen.length; while (seenIndex--) { if (seen[seenIndex] === computed) { continue outer; } } if (iteratee) { seen.push(computed); } result.push(value); } else if (!includes(seen, computed, comparator)) { if (seen !== result) { seen.push(computed); } result.push(value); } } return result; } /** * The base implementation of `_.unset`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. */ function baseUnset(object, path) { path = isKey(path, object) ? [path] : castPath(path); object = parent(object, path); var key = toKey(last(path)); return !(object != null && baseHas(object, key)) || delete object[key]; } /** * The base implementation of `_.update`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to update. * @param {Function} updater The function to produce the updated value. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseUpdate(object, path, updater, customizer) { return baseSet(object, path, updater(baseGet(object, path)), customizer); } /** * The base implementation of methods like `_.dropWhile` and `_.takeWhile` * without support for iteratee shorthands. * * @private * @param {Array} array The array to query. * @param {Function} predicate The function invoked per iteration. * @param {boolean} [isDrop] Specify dropping elements instead of taking them. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the slice of `array`. */ function baseWhile(array, predicate, isDrop, fromRight) { var length = array.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {} return isDrop ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); } /** * The base implementation of `wrapperValue` which returns the result of * performing a sequence of actions on the unwrapped `value`, where each * successive action is supplied the return value of the previous. * * @private * @param {*} value The unwrapped value. * @param {Array} actions Actions to perform to resolve the unwrapped value. * @returns {*} Returns the resolved value. */ function baseWrapperValue(value, actions) { var result = value; if (result instanceof LazyWrapper) { result = result.value(); } return arrayReduce(actions, function(result, action) { return action.func.apply(action.thisArg, arrayPush([result], action.args)); }, result); } /** * The base implementation of methods like `_.xor`, without support for * iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of values. */ function baseXor(arrays, iteratee, comparator) { var index = -1, length = arrays.length; while (++index < length) { var result = result ? arrayPush( baseDifference(result, arrays[index], iteratee, comparator), baseDifference(arrays[index], result, iteratee, comparator) ) : arrays[index]; } return (result && result.length) ? baseUniq(result, iteratee, comparator) : []; } /** * This base implementation of `_.zipObject` which assigns values using `assignFunc`. * * @private * @param {Array} props The property identifiers. * @param {Array} values The property values. * @param {Function} assignFunc The function to assign values. * @returns {Object} Returns the new object. */ function baseZipObject(props, values, assignFunc) { var index = -1, length = props.length, valsLength = values.length, result = {}; while (++index < length) { var value = index < valsLength ? values[index] : undefined; assignFunc(result, props[index], value); } return result; } /** * Casts `value` to an empty array if it's not an array like object. * * @private * @param {*} value The value to inspect. * @returns {Array|Object} Returns the cast array-like object. */ function castArrayLikeObject(value) { return isArrayLikeObject(value) ? value : []; } /** * Casts `value` to `identity` if it's not a function. * * @private * @param {*} value The value to inspect. * @returns {Function} Returns cast function. */ function castFunction(value) { return typeof value == 'function' ? value : identity; } /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @returns {Array} Returns the cast property path array. */ function castPath(value) { return isArray(value) ? value : stringToPath(value); } /** * Casts `array` to a slice if it's needed. * * @private * @param {Array} array The array to inspect. * @param {number} start The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the cast slice. */ function castSlice(array, start, end) { var length = array.length; end = end === undefined ? length : end; return (!start && end >= length) ? array : baseSlice(array, start, end); } /** * Creates a clone of `buffer`. * * @private * @param {Buffer} buffer The buffer to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Buffer} Returns the cloned buffer. */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var result = new buffer.constructor(buffer.length); buffer.copy(result); return result; } /** * Creates a clone of `arrayBuffer`. * * @private * @param {ArrayBuffer} arrayBuffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new Uint8Array(result).set(new Uint8Array(arrayBuffer)); return result; } /** * Creates a clone of `dataView`. * * @private * @param {Object} dataView The data view to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned data view. */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } /** * Creates a clone of `map`. * * @private * @param {Object} map The map to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned map. */ function cloneMap(map, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map); return arrayReduce(array, addMapEntry, new map.constructor); } /** * Creates a clone of `regexp`. * * @private * @param {Object} regexp The regexp to clone. * @returns {Object} Returns the cloned regexp. */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } /** * Creates a clone of `set`. * * @private * @param {Object} set The set to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned set. */ function cloneSet(set, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set); return arrayReduce(array, addSetEntry, new set.constructor); } /** * Creates a clone of the `symbol` object. * * @private * @param {Object} symbol The symbol object to clone. * @returns {Object} Returns the cloned symbol object. */ function cloneSymbol(symbol) { return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; } /** * Creates a clone of `typedArray`. * * @private * @param {Object} typedArray The typed array to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned typed array. */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } /** * Compares values to sort them in ascending order. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {number} Returns the sort order indicator for `value`. */ function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol(value); var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol(other); if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || (valIsNull && othIsDefined && othIsReflexive) || (!valIsDefined && othIsReflexive) || !valIsReflexive) { return 1; } if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || (othIsNull && valIsDefined && valIsReflexive) || (!othIsDefined && valIsReflexive) || !othIsReflexive) { return -1; } } return 0; } /** * Used by `_.orderBy` to compare multiple properties of a value to another * and stable sort them. * * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, * specify an order of "desc" for descending or "asc" for ascending sort order * of corresponding values. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {boolean[]|string[]} orders The order to sort by for each property. * @returns {number} Returns the sort order indicator for `object`. */ function compareMultiple(object, other, orders) { var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; while (++index < length) { var result = compareAscending(objCriteria[index], othCriteria[index]); if (result) { if (index >= ordersLength) { return result; } var order = orders[index]; return result * (order == 'desc' ? -1 : 1); } } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to provide the same value for // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 // for more details. // // This also ensures a stable sort in V8 and other engines. // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. return object.index - other.index; } /** * Creates an array that is the composition of partially applied arguments, * placeholders, and provided arguments into a single array of arguments. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to prepend to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgs(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(leftLength + rangeLength), isUncurried = !isCurried; while (++leftIndex < leftLength) { result[leftIndex] = partials[leftIndex]; } while (++argsIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[holders[argsIndex]] = args[argsIndex]; } } while (rangeLength--) { result[leftIndex++] = args[argsIndex++]; } return result; } /** * This function is like `composeArgs` except that the arguments composition * is tailored for `_.partialRight`. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to append to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgsRight(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(rangeLength + rightLength), isUncurried = !isCurried; while (++argsIndex < rangeLength) { result[argsIndex] = args[argsIndex]; } var offset = argsIndex; while (++rightIndex < rightLength) { result[offset + rightIndex] = partials[rightIndex]; } while (++holdersIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[offset + holders[holdersIndex]] = args[argsIndex++]; } } return result; } /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : source[key]; assignValue(object, key, newValue); } return object; } /** * Copies own symbol properties of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return copyObject(source, getSymbols(source), object); } /** * Creates a function like `_.groupBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} [initializer] The accumulator object initializer. * @returns {Function} Returns the new aggregator function. */ function createAggregator(setter, initializer) { return function(collection, iteratee) { var func = isArray(collection) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {}; return func(collection, setter, getIteratee(iteratee), accumulator); }; } /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return rest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = (assigner.length > 3 && typeof customizer == 'function') ? (length--, customizer) : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); } } return object; }); } /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } /** * Creates a function that wraps `func` to invoke it with the optional `this` * binding of `thisArg`. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask of wrapper flags. See `createWrapper` * for more details. * @param {*} [thisArg] The `this` binding of `func`. * @returns {Function} Returns the new wrapped function. */ function createBaseWrapper(func, bitmask, thisArg) { var isBind = bitmask & BIND_FLAG, Ctor = createCtorWrapper(func); function wrapper() { var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return fn.apply(isBind ? thisArg : this, arguments); } return wrapper; } /** * Creates a function like `_.lowerFirst`. * * @private * @param {string} methodName The name of the `String` case method to use. * @returns {Function} Returns the new case function. */ function createCaseFirst(methodName) { return function(string) { string = toString(string); var strSymbols = reHasComplexSymbol.test(string) ? stringToArray(string) : undefined; var chr = strSymbols ? strSymbols[0] : string.charAt(0); var trailing = strSymbols ? castSlice(strSymbols, 1).join('') : string.slice(1); return chr[methodName]() + trailing; }; } /** * Creates a function like `_.camelCase`. * * @private * @param {Function} callback The function to combine each word. * @returns {Function} Returns the new compounder function. */ function createCompounder(callback) { return function(string) { return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); }; } /** * Creates a function that produces an instance of `Ctor` regardless of * whether it was invoked as part of a `new` expression or by `call` or `apply`. * * @private * @param {Function} Ctor The constructor to wrap. * @returns {Function} Returns the new wrapped function. */ function createCtorWrapper(Ctor) { return function() { // Use a `switch` statement to work with class constructors. See // http://ecma-international.org/ecma-262/6.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist // for more details. var args = arguments; switch (args.length) { case 0: return new Ctor; case 1: return new Ctor(args[0]); case 2: return new Ctor(args[0], args[1]); case 3: return new Ctor(args[0], args[1], args[2]); case 4: return new Ctor(args[0], args[1], args[2], args[3]); case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); } var thisBinding = baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args); // Mimic the constructor's `return` behavior. // See https://es5.github.io/#x13.2.2 for more details. return isObject(result) ? result : thisBinding; }; } /** * Creates a function that wraps `func` to enable currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask of wrapper flags. See `createWrapper` * for more details. * @param {number} arity The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createCurryWrapper(func, bitmask, arity) { var Ctor = createCtorWrapper(func); function wrapper() { var length = arguments.length, args = Array(length), index = length, placeholder = getHolder(wrapper); while (index--) { args[index] = arguments[index]; } var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) ? [] : replaceHolders(args, placeholder); length -= holders.length; if (length < arity) { return createRecurryWrapper( func, bitmask, createHybridWrapper, wrapper.placeholder, undefined, args, holders, undefined, undefined, arity - length); } var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return apply(fn, this, args); } return wrapper; } /** * Creates a `_.flow` or `_.flowRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new flow function. */ function createFlow(fromRight) { return rest(function(funcs) { funcs = baseFlatten(funcs, 1); var length = funcs.length, index = length, prereq = LodashWrapper.prototype.thru; if (fromRight) { funcs.reverse(); } while (index--) { var func = funcs[index]; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (prereq && !wrapper && getFuncName(func) == 'wrapper') { var wrapper = new LodashWrapper([], true); } } index = wrapper ? index : length; while (++index < length) { func = funcs[index]; var funcName = getFuncName(func), data = funcName == 'wrapper' ? getData(func) : undefined; if (data && isLaziable(data[0]) && data[1] == (ARY_FLAG | CURRY_FLAG | PARTIAL_FLAG | REARG_FLAG) && !data[4].length && data[9] == 1 ) { wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); } else { wrapper = (func.length == 1 && isLaziable(func)) ? wrapper[funcName]() : wrapper.thru(func); } } return function() { var args = arguments, value = args[0]; if (wrapper && args.length == 1 && isArray(value) && value.length >= LARGE_ARRAY_SIZE) { return wrapper.plant(value).value(); } var index = 0, result = length ? funcs[index].apply(this, args) : value; while (++index < length) { result = funcs[index].call(this, result); } return result; }; }); } /** * Creates a function that wraps `func` to invoke it with optional `this` * binding of `thisArg`, partial application, and currying. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask of wrapper flags. See `createWrapper` * for more details. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [partialsRight] The arguments to append to those provided * to the new function. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createHybridWrapper(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { var isAry = bitmask & ARY_FLAG, isBind = bitmask & BIND_FLAG, isBindKey = bitmask & BIND_KEY_FLAG, isCurried = bitmask & (CURRY_FLAG | CURRY_RIGHT_FLAG), isFlip = bitmask & FLIP_FLAG, Ctor = isBindKey ? undefined : createCtorWrapper(func); function wrapper() { var length = arguments.length, args = Array(length), index = length; while (index--) { args[index] = arguments[index]; } if (isCurried) { var placeholder = getHolder(wrapper), holdersCount = countHolders(args, placeholder); } if (partials) { args = composeArgs(args, partials, holders, isCurried); } if (partialsRight) { args = composeArgsRight(args, partialsRight, holdersRight, isCurried); } length -= holdersCount; if (isCurried && length < arity) { var newHolders = replaceHolders(args, placeholder); return createRecurryWrapper( func, bitmask, createHybridWrapper, wrapper.placeholder, thisArg, args, newHolders, argPos, ary, arity - length ); } var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; length = args.length; if (argPos) { args = reorder(args, argPos); } else if (isFlip && length > 1) { args.reverse(); } if (isAry && ary < length) { args.length = ary; } if (this && this !== root && this instanceof wrapper) { fn = Ctor || createCtorWrapper(fn); } return fn.apply(thisBinding, args); } return wrapper; } /** * Creates a function like `_.invertBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} toIteratee The function to resolve iteratees. * @returns {Function} Returns the new inverter function. */ function createInverter(setter, toIteratee) { return function(object, iteratee) { return baseInverter(object, setter, toIteratee(iteratee), {}); }; } /** * Creates a function that performs a mathematical operation on two values. * * @private * @param {Function} operator The function to perform the operation. * @returns {Function} Returns the new mathematical operation function. */ function createMathOperation(operator) { return function(value, other) { var result; if (value === undefined && other === undefined) { return 0; } if (value !== undefined) { result = value; } if (other !== undefined) { if (result === undefined) { return other; } if (typeof value == 'string' || typeof other == 'string') { value = baseToString(value); other = baseToString(other); } else { value = baseToNumber(value); other = baseToNumber(other); } result = operator(value, other); } return result; }; } /** * Creates a function like `_.over`. * * @private * @param {Function} arrayFunc The function to iterate over iteratees. * @returns {Function} Returns the new over function. */ function createOver(arrayFunc) { return rest(function(iteratees) { iteratees = (iteratees.length == 1 && isArray(iteratees[0])) ? arrayMap(iteratees[0], baseUnary(getIteratee())) : arrayMap(baseFlatten(iteratees, 1, isFlattenableIteratee), baseUnary(getIteratee())); return rest(function(args) { var thisArg = this; return arrayFunc(iteratees, function(iteratee) { return apply(iteratee, thisArg, args); }); }); }); } /** * Creates the padding for `string` based on `length`. The `chars` string * is truncated if the number of characters exceeds `length`. * * @private * @param {number} length The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padding for `string`. */ function createPadding(length, chars) { chars = chars === undefined ? ' ' : baseToString(chars); var charsLength = chars.length; if (charsLength < 2) { return charsLength ? baseRepeat(chars, length) : chars; } var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); return reHasComplexSymbol.test(chars) ? castSlice(stringToArray(result), 0, length).join('') : result.slice(0, length); } /** * Creates a function that wraps `func` to invoke it with the `this` binding * of `thisArg` and `partials` prepended to the arguments it receives. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask of wrapper flags. See `createWrapper` * for more details. * @param {*} thisArg The `this` binding of `func`. * @param {Array} partials The arguments to prepend to those provided to * the new function. * @returns {Function} Returns the new wrapped function. */ function createPartialWrapper(func, bitmask, thisArg, partials) { var isBind = bitmask & BIND_FLAG, Ctor = createCtorWrapper(func); function wrapper() { var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength), fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex]; } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex]; } return apply(fn, isBind ? thisArg : this, args); } return wrapper; } /** * Creates a `_.range` or `_.rangeRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new range function. */ function createRange(fromRight) { return function(start, end, step) { if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { end = step = undefined; } // Ensure the sign of `-0` is preserved. start = toNumber(start); start = start === start ? start : 0; if (end === undefined) { end = start; start = 0; } else { end = toNumber(end) || 0; } step = step === undefined ? (start < end ? 1 : -1) : (toNumber(step) || 0); return baseRange(start, end, step, fromRight); }; } /** * Creates a function that performs a relational operation on two values. * * @private * @param {Function} operator The function to perform the operation. * @returns {Function} Returns the new relational operation function. */ function createRelationalOperation(operator) { return function(value, other) { if (!(typeof value == 'string' && typeof other == 'string')) { value = toNumber(value); other = toNumber(other); } return operator(value, other); }; } /** * Creates a function that wraps `func` to continue currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask of wrapper flags. See `createWrapper` * for more details. * @param {Function} wrapFunc The function to create the `func` wrapper. * @param {*} placeholder The placeholder value. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createRecurryWrapper(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & CURRY_FLAG, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? undefined : partials; bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG); bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG); if (!(bitmask & CURRY_BOUND_FLAG)) { bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG); } var newData = [ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity ]; var result = wrapFunc.apply(undefined, newData); if (isLaziable(func)) { setData(result, newData); } result.placeholder = placeholder; return result; } /** * Creates a function like `_.round`. * * @private * @param {string} methodName The name of the `Math` method to use when rounding. * @returns {Function} Returns the new round function. */ function createRound(methodName) { var func = Math[methodName]; return function(number, precision) { number = toNumber(number); precision = toInteger(precision); if (precision) { // Shift with exponential notation to avoid floating-point issues. // See [MDN](https://mdn.io/round#Examples) for more details. var pair = (toString(number) + 'e').split('e'), value = func(pair[0] + 'e' + (+pair[1] + precision)); pair = (toString(value) + 'e').split('e'); return +(pair[0] + 'e' + (+pair[1] - precision)); } return func(number); }; } /** * Creates a set of `values`. * * @private * @param {Array} values The values to add to the set. * @returns {Object} Returns the new set. */ var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { return new Set(values); }; /** * Creates a `_.toPairs` or `_.toPairsIn` function. * * @private * @param {Function} keysFunc The function to get the keys of a given object. * @returns {Function} Returns the new pairs function. */ function createToPairs(keysFunc) { return function(object) { var tag = getTag(object); if (tag == mapTag) { return mapToArray(object); } if (tag == setTag) { return setToPairs(object); } return baseToPairs(object, keysFunc(object)); }; } /** * Creates a function that either curries or invokes `func` with optional * `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask of wrapper flags. * The bitmask may be composed of the following flags: * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` or `_.curryRight` of a bound function * 8 - `_.curry` * 16 - `_.curryRight` * 32 - `_.partial` * 64 - `_.partialRight` * 128 - `_.rearg` * 256 - `_.ary` * 512 - `_.flip` * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to be partially applied. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createWrapper(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & BIND_KEY_FLAG; if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG); partials = holders = undefined; } ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); arity = arity === undefined ? arity : toInteger(arity); length -= holders ? holders.length : 0; if (bitmask & PARTIAL_RIGHT_FLAG) { var partialsRight = partials, holdersRight = holders; partials = holders = undefined; } var data = isBindKey ? undefined : getData(func); var newData = [ func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity ]; if (data) { mergeData(newData, data); } func = newData[0]; bitmask = newData[1]; thisArg = newData[2]; partials = newData[3]; holders = newData[4]; arity = newData[9] = newData[9] == null ? (isBindKey ? 0 : func.length) : nativeMax(newData[9] - length, 0); if (!arity && bitmask & (CURRY_FLAG | CURRY_RIGHT_FLAG)) { bitmask &= ~(CURRY_FLAG | CURRY_RIGHT_FLAG); } if (!bitmask || bitmask == BIND_FLAG) { var result = createBaseWrapper(func, bitmask, thisArg); } else if (bitmask == CURRY_FLAG || bitmask == CURRY_RIGHT_FLAG) { result = createCurryWrapper(func, bitmask, arity); } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !holders.length) { result = createPartialWrapper(func, bitmask, thisArg, partials); } else { result = createHybridWrapper.apply(undefined, newData); } var setter = data ? baseSetData : setData; return setter(result, newData); } /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} customizer The function to customize comparisons. * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` * for more details. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, equalFunc, customizer, bitmask, stack) { var isPartial = bitmask & PARTIAL_COMPARE_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Assume cyclic values are equal. var stacked = stack.get(array); if (stacked) { return stacked == other; } var index = -1, result = true, seen = (bitmask & UNORDERED_COMPARE_FLAG) ? new SetCache : undefined; stack.set(array, other); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!arraySome(other, function(othValue, othIndex) { if (!seen.has(othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) { return seen.add(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack) )) { result = false; break; } } stack['delete'](array); return result; } /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} customizer The function to customize comparisons. * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` * for more details. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, equalFunc, customizer, bitmask, stack) { switch (tag) { case dataViewTag: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if ((object.byteLength != other.byteLength) || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: // Coerce dates and booleans to numbers, dates to milliseconds and // booleans to `1` or `0` treating invalid dates coerced to `NaN` as // not equal. return +object == +other; case errorTag: return object.name == other.name && object.message == other.message; case numberTag: // Treat `NaN` vs. `NaN` as equal. return (object != +object) ? other != +other : object == +other; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/6.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & PARTIAL_COMPARE_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= UNORDERED_COMPARE_FLAG; stack.set(object, other); // Recursively compare objects (susceptible to call stack limits). return equalArrays(convert(object), convert(other), equalFunc, customizer, bitmask, stack); case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} customizer The function to customize comparisons. * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` * for more details. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, equalFunc, customizer, bitmask, stack) { var isPartial = bitmask & PARTIAL_COMPARE_FLAG, objProps = keys(object), objLength = objProps.length, othProps = keys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : baseHas(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } var result = true; stack.set(object, other); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); return result; } /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } /** * Creates an array of own and inherited enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeysIn(object) { return baseGetAllKeys(object, keysIn, getSymbolsIn); } /** * Gets metadata for `func`. * * @private * @param {Function} func The function to query. * @returns {*} Returns the metadata for `func`. */ var getData = !metaMap ? noop : function(func) { return metaMap.get(func); }; /** * Gets the name of `func`. * * @private * @param {Function} func The function to query. * @returns {string} Returns the function name. */ function getFuncName(func) { var result = (func.name + ''), array = realNames[result], length = hasOwnProperty.call(realNames, result) ? array.length : 0; while (length--) { var data = array[length], otherFunc = data.func; if (otherFunc == null || otherFunc == func) { return data.name; } } return result; } /** * Gets the argument placeholder value for `func`. * * @private * @param {Function} func The function to inspect. * @returns {*} Returns the placeholder value. */ function getHolder(func) { var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; return object.placeholder; } /** * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, * this function returns the custom method, otherwise it returns `baseIteratee`. * If arguments are provided, the chosen function is invoked with them and * its result is returned. * * @private * @param {*} [value] The value to convert to an iteratee. * @param {number} [arity] The arity of the created iteratee. * @returns {Function} Returns the chosen function or its result. */ function getIteratee() { var result = lodash.iteratee || iteratee; result = result === iteratee ? baseIteratee : result; return arguments.length ? result(arguments[0], arguments[1]) : result; } /** * Gets the "length" property value of `object`. * * **Note:** This function is used to avoid a * [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) that affects * Safari on at least iOS 8.1-8.3 ARM64. * * @private * @param {Object} object The object to query. * @returns {*} Returns the "length" value. */ var getLength = baseProperty('length'); /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = toPairs(object), length = result.length; while (length--) { result[length][2] = isStrictComparable(result[length][1]); } return result; } /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = object[key]; return isNative(value) ? value : undefined; } /** * Gets the `[[Prototype]]` of `value`. * * @private * @param {*} value The value to query. * @returns {null|Object} Returns the `[[Prototype]]`. */ function getPrototype(value) { return nativeGetPrototype(Object(value)); } /** * Creates an array of the own enumerable symbol properties of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ function getSymbols(object) { // Coerce `object` to an object to avoid non-object errors in V8. // See https://bugs.chromium.org/p/v8/issues/detail?id=3443 for more details. return getOwnPropertySymbols(Object(object)); } // Fallback for IE < 11. if (!getOwnPropertySymbols) { getSymbols = function() { return []; }; } /** * Creates an array of the own and inherited enumerable symbol properties * of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbolsIn = !getOwnPropertySymbols ? getSymbols : function(object) { var result = []; while (object) { arrayPush(result, getSymbols(object)); object = getPrototype(object); } return result; }; /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function getTag(value) { return objectToString.call(value); } // Fallback for data views, maps, sets, and weak maps in IE 11, // for data views in Edge, and promises in Node.js. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || (Map && getTag(new Map) != mapTag) || (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = objectToString.call(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : undefined; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } /** * Gets the view, applying any `transforms` to the `start` and `end` positions. * * @private * @param {number} start The start of the view. * @param {number} end The end of the view. * @param {Array} transforms The transformations to apply to the view. * @returns {Object} Returns an object containing the `start` and `end` * positions of the view. */ function getView(start, end, transforms) { var index = -1, length = transforms.length; while (++index < length) { var data = transforms[index], size = data.size; switch (data.type) { case 'drop': start += size; break; case 'dropRight': end -= size; break; case 'take': end = nativeMin(end, start + size); break; case 'takeRight': start = nativeMax(start, end - size); break; } } return { 'start': start, 'end': end }; } /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = isKey(path, object) ? [path] : castPath(path); var result, index = -1, length = path.length; while (++index < length) { var key = toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result) { return result; } var length = object ? object.length : 0; return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isString(object) || isArguments(object)); } /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { return (typeof object.constructor == 'function' && !isPrototype(object)) ? baseCreate(getPrototype(object)) : {}; } /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, cloneFunc, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag: return cloneArrayBuffer(object); case boolTag: case dateTag: return new Ctor(+object); case dataViewTag: return cloneDataView(object, isDeep); case float32Tag: case float64Tag: case int8Tag: case int16Tag: case int32Tag: case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: return cloneTypedArray(object, isDeep); case mapTag: return cloneMap(object, isDeep, cloneFunc); case numberTag: case stringTag: return new Ctor(object); case regexpTag: return cloneRegExp(object); case setTag: return cloneSet(object, isDeep, cloneFunc); case symbolTag: return cloneSymbol(object); } } /** * Creates an array of index keys for `object` values of arrays, * `arguments` objects, and strings, otherwise `null` is returned. * * @private * @param {Object} object The object to query. * @returns {Array|null} Returns index keys, else `null`. */ function indexKeys(object) { var length = object ? object.length : undefined; if (isLength(length) && (isArray(object) || isString(object) || isArguments(object))) { return baseTimes(length, String); } return null; } /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArray(value) || isArguments(value); } /** * Checks if `value` is a flattenable array and not a `_.matchesProperty` * iteratee shorthand. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenableIteratee(value) { return isArray(value) && !(value.length == 2 && !isFunction(value[0])); } /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (typeof value == 'number' || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike(object) && isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq(object[index], value); } return false; } /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } /** * Checks if `func` has a lazy counterpart. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` has a lazy counterpart, * else `false`. */ function isLaziable(func) { var funcName = getFuncName(func), other = lodash[funcName]; if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { return false; } if (func === other) { return true; } var data = getData(other); return !!data && func === data[0]; } /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject(value); } /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== undefined || (key in Object(object))); }; } /** * Merges the function metadata of `source` into `data`. * * Merging metadata reduces the number of wrappers used to invoke a function. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` * may be applied regardless of execution order. Methods like `_.ary` and * `_.rearg` modify function arguments, making the order in which they are * executed important, preventing the merging of metadata. However, we make * an exception for a safe combined case where curried functions have `_.ary` * and or `_.rearg` applied. * * @private * @param {Array} data The destination metadata. * @param {Array} source The source metadata. * @returns {Array} Returns `data`. */ function mergeData(data, source) { var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (BIND_FLAG | BIND_KEY_FLAG | ARY_FLAG); var isCombo = ((srcBitmask == ARY_FLAG) && (bitmask == CURRY_FLAG)) || ((srcBitmask == ARY_FLAG) && (bitmask == REARG_FLAG) && (data[7].length <= source[8])) || ((srcBitmask == (ARY_FLAG | REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == CURRY_FLAG)); // Exit early if metadata can't be merged. if (!(isCommon || isCombo)) { return data; } // Use source `thisArg` if available. if (srcBitmask & BIND_FLAG) { data[2] = source[2]; // Set when currying a bound function. newBitmask |= bitmask & BIND_FLAG ? 0 : CURRY_BOUND_FLAG; } // Compose partial arguments. var value = source[3]; if (value) { var partials = data[3]; data[3] = partials ? composeArgs(partials, value, source[4]) : value; data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; } // Compose partial right arguments. value = source[5]; if (value) { partials = data[5]; data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; } // Use source `argPos` if available. value = source[7]; if (value) { data[7] = value; } // Use source `ary` if it's smaller. if (srcBitmask & ARY_FLAG) { data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); } // Use source `arity` if one is not provided. if (data[9] == null) { data[9] = source[9]; } // Use source `func` and merge bitmasks. data[0] = source[0]; data[1] = newBitmask; return data; } /** * Used by `_.defaultsDeep` to customize its `_.merge` use. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to merge. * @param {Object} object The parent object of `objValue`. * @param {Object} source The parent object of `srcValue`. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. * @returns {*} Returns the value to assign. */ function mergeDefaults(objValue, srcValue, key, object, source, stack) { if (isObject(objValue) && isObject(srcValue)) { baseMerge(objValue, srcValue, undefined, mergeDefaults, stack.set(srcValue, objValue)); } return objValue; } /** * Gets the parent value at `path` of `object`. * * @private * @param {Object} object The object to query. * @param {Array} path The path to get the parent value of. * @returns {*} Returns the parent value. */ function parent(object, path) { return path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); } /** * Reorder `array` according to the specified indexes where the element at * the first index is assigned as the first element, the element at * the second index is assigned as the second element, and so on. * * @private * @param {Array} array The array to reorder. * @param {Array} indexes The arranged array indexes. * @returns {Array} Returns `array`. */ function reorder(array, indexes) { var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = copyArray(array); while (length--) { var index = indexes[length]; array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; } return array; } /** * Sets metadata for `func`. * * **Note:** If this function becomes hot, i.e. is invoked a lot in a short * period of time, it will trip its breaker and transition to an identity * function to avoid garbage collection pauses in V8. See * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) * for more details. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var setData = (function() { var count = 0, lastCalled = 0; return function(key, value) { var stamp = now(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return key; } } else { count = 0; } return baseSetData(key, value); }; }()); /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = memoize(function(string) { var result = []; toString(string).replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * Converts `func` to its source code. * * @private * @param {Function} func The function to process. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } /** * Creates a clone of `wrapper`. * * @private * @param {Object} wrapper The wrapper to clone. * @returns {Object} Returns the cloned wrapper. */ function wrapperClone(wrapper) { if (wrapper instanceof LazyWrapper) { return wrapper.clone(); } var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); result.__actions__ = copyArray(wrapper.__actions__); result.__index__ = wrapper.__index__; result.__values__ = wrapper.__values__; return result; } /*------------------------------------------------------------------------*/ /** * Creates an array of elements split into groups the length of `size`. * If `array` can't be split evenly, the final chunk will be the remaining * elements. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to process. * @param {number} [size=1] The length of each chunk * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the new array of chunks. * @example * * _.chunk(['a', 'b', 'c', 'd'], 2); * // => [['a', 'b'], ['c', 'd']] * * _.chunk(['a', 'b', 'c', 'd'], 3); * // => [['a', 'b', 'c'], ['d']] */ function chunk(array, size, guard) { if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { size = 1; } else { size = nativeMax(toInteger(size), 0); } var length = array ? array.length : 0; if (!length || size < 1) { return []; } var index = 0, resIndex = 0, result = Array(nativeCeil(length / size)); while (index < length) { result[resIndex++] = baseSlice(array, index, (index += size)); } return result; } /** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are falsey. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to compact. * @returns {Array} Returns the new array of filtered values. * @example * * _.compact([0, 1, false, 2, '', 3]); * // => [1, 2, 3] */ function compact(array) { var index = -1, length = array ? array.length : 0, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value) { result[resIndex++] = value; } } return result; } /** * Creates a new array concatenating `array` with any additional arrays * and/or values. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to concatenate. * @param {...*} [values] The values to concatenate. * @returns {Array} Returns the new concatenated array. * @example * * var array = [1]; * var other = _.concat(array, 2, [3], [[4]]); * * console.log(other); * // => [1, 2, 3, [4]] * * console.log(array); * // => [1] */ function concat() { var length = arguments.length, args = Array(length ? length - 1 : 0), array = arguments[0], index = length; while (index--) { args[index - 1] = arguments[index]; } return length ? arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)) : []; } /** * Creates an array of unique `array` values not included in the other given * arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) * for equality comparisons. The order of result values is determined by the * order they occur in the first array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.without, _.xor * @example * * _.difference([3, 2, 1], [4, 2]); * // => [3, 1] */ var difference = rest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) : []; }); /** * This method is like `_.difference` except that it accepts `iteratee` which * is invoked for each element of `array` and `values` to generate the criterion * by which they're compared. Result values are chosen from the first array. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @param {Array|Function|Object|string} [iteratee=_.identity] * The iteratee invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * _.differenceBy([3.1, 2.2, 1.3], [4.4, 2.5], Math.floor); * // => [3.1, 1.3] * * // The `_.property` iteratee shorthand. * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); * // => [{ 'x': 2 }] */ var differenceBy = rest(function(array, values) { var iteratee = last(values); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee)) : []; }); /** * This method is like `_.difference` except that it accepts `comparator` * which is invoked to compare elements of `array` to `values`. Result values * are chosen from the first array. The comparator is invoked with two arguments: * (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); * // => [{ 'x': 2, 'y': 1 }] */ var differenceWith = rest(function(array, values) { var comparator = last(values); if (isArrayLikeObject(comparator)) { comparator = undefined; } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) : []; }); /** * Creates a slice of `array` with `n` elements dropped from the beginning. * * @static * @memberOf _ * @since 0.5.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.drop([1, 2, 3]); * // => [2, 3] * * _.drop([1, 2, 3], 2); * // => [3] * * _.drop([1, 2, 3], 5); * // => [] * * _.drop([1, 2, 3], 0); * // => [1, 2, 3] */ function drop(array, n, guard) { var length = array ? array.length : 0; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); return baseSlice(array, n < 0 ? 0 : n, length); } /** * Creates a slice of `array` with `n` elements dropped from the end. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.dropRight([1, 2, 3]); * // => [1, 2] * * _.dropRight([1, 2, 3], 2); * // => [1] * * _.dropRight([1, 2, 3], 5); * // => [] * * _.dropRight([1, 2, 3], 0); * // => [1, 2, 3] */ function dropRight(array, n, guard) { var length = array ? array.length : 0; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); n = length - n; return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` excluding elements dropped from the end. * Elements are dropped until `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Array|Function|Object|string} [predicate=_.identity] * The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.dropRightWhile(users, function(o) { return !o.active; }); * // => objects for ['barney'] * * // The `_.matches` iteratee shorthand. * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); * // => objects for ['barney', 'fred'] * * // The `_.matchesProperty` iteratee shorthand. * _.dropRightWhile(users, ['active', false]); * // => objects for ['barney'] * * // The `_.property` iteratee shorthand. * _.dropRightWhile(users, 'active'); * // => objects for ['barney', 'fred', 'pebbles'] */ function dropRightWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), true, true) : []; } /** * Creates a slice of `array` excluding elements dropped from the beginning. * Elements are dropped until `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Array|Function|Object|string} [predicate=_.identity] * The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.dropWhile(users, function(o) { return !o.active; }); * // => objects for ['pebbles'] * * // The `_.matches` iteratee shorthand. * _.dropWhile(users, { 'user': 'barney', 'active': false }); * // => objects for ['fred', 'pebbles'] * * // The `_.matchesProperty` iteratee shorthand. * _.dropWhile(users, ['active', false]); * // => objects for ['pebbles'] * * // The `_.property` iteratee shorthand. * _.dropWhile(users, 'active'); * // => objects for ['barney', 'fred', 'pebbles'] */ function dropWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), true) : []; } /** * Fills elements of `array` with `value` from `start` up to, but not * including, `end`. * * **Note:** This method mutates `array`. * * @static * @memberOf _ * @since 3.2.0 * @category Array * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.fill(array, 'a'); * console.log(array); * // => ['a', 'a', 'a'] * * _.fill(Array(3), 2); * // => [2, 2, 2] * * _.fill([4, 6, 8, 10], '*', 1, 3); * // => [4, '*', '*', 10] */ function fill(array, value, start, end) { var length = array ? array.length : 0; if (!length) { return []; } if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { start = 0; end = length; } return baseFill(array, value, start, end); } /** * This method is like `_.find` except that it returns the index of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Array * @param {Array} array The array to search. * @param {Array|Function|Object|string} [predicate=_.identity] * The function invoked per iteration. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.findIndex(users, function(o) { return o.user == 'barney'; }); * // => 0 * * // The `_.matches` iteratee shorthand. * _.findIndex(users, { 'user': 'fred', 'active': false }); * // => 1 * * // The `_.matchesProperty` iteratee shorthand. * _.findIndex(users, ['active', false]); * // => 0 * * // The `_.property` iteratee shorthand. * _.findIndex(users, 'active'); * // => 2 */ function findIndex(array, predicate) { return (array && array.length) ? baseFindIndex(array, getIteratee(predicate, 3)) : -1; } /** * This method is like `_.findIndex` except that it iterates over elements * of `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to search. * @param {Array|Function|Object|string} [predicate=_.identity] * The function invoked per iteration. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); * // => 2 * * // The `_.matches` iteratee shorthand. * _.findLastIndex(users, { 'user': 'barney', 'active': true }); * // => 0 * * // The `_.matchesProperty` iteratee shorthand. * _.findLastIndex(users, ['active', false]); * // => 2 * * // The `_.property` iteratee shorthand. * _.findLastIndex(users, 'active'); * // => 0 */ function findLastIndex(array, predicate) { return (array && array.length) ? baseFindIndex(array, getIteratee(predicate, 3), true) : -1; } /** * Flattens `array` a single level deep. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flatten([1, [2, [3, [4]], 5]]); * // => [1, 2, [3, [4]], 5] */ function flatten(array) { var length = array ? array.length : 0; return length ? baseFlatten(array, 1) : []; } /** * Recursively flattens `array`. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flattenDeep([1, [2, [3, [4]], 5]]); * // => [1, 2, 3, 4, 5] */ function flattenDeep(array) { var length = array ? array.length : 0; return length ? baseFlatten(array, INFINITY) : []; } /** * Recursively flatten `array` up to `depth` times. * * @static * @memberOf _ * @since 4.4.0 * @category Array * @param {Array} array The array to flatten. * @param {number} [depth=1] The maximum recursion depth. * @returns {Array} Returns the new flattened array. * @example * * var array = [1, [2, [3, [4]], 5]]; * * _.flattenDepth(array, 1); * // => [1, 2, [3, [4]], 5] * * _.flattenDepth(array, 2); * // => [1, 2, 3, [4], 5] */ function flattenDepth(array, depth) { var length = array ? array.length : 0; if (!length) { return []; } depth = depth === undefined ? 1 : toInteger(depth); return baseFlatten(array, depth); } /** * The inverse of `_.toPairs`; this method returns an object composed * from key-value `pairs`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} pairs The key-value pairs. * @returns {Object} Returns the new object. * @example * * _.fromPairs([['fred', 30], ['barney', 40]]); * // => { 'fred': 30, 'barney': 40 } */ function fromPairs(pairs) { var index = -1, length = pairs ? pairs.length : 0, result = {}; while (++index < length) { var pair = pairs[index]; result[pair[0]] = pair[1]; } return result; } /** * Gets the first element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @alias first * @category Array * @param {Array} array The array to query. * @returns {*} Returns the first element of `array`. * @example * * _.head([1, 2, 3]); * // => 1 * * _.head([]); * // => undefined */ function head(array) { return (array && array.length) ? array[0] : undefined; } /** * Gets the index at which the first occurrence of `value` is found in `array` * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) * for equality comparisons. If `fromIndex` is negative, it's used as the * offset from the end of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to search. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.indexOf([1, 2, 1, 2], 2); * // => 1 * * // Search from the `fromIndex`. * _.indexOf([1, 2, 1, 2], 2, 2); * // => 3 */ function indexOf(array, value, fromIndex) { var length = array ? array.length : 0; if (!length) { return -1; } fromIndex = toInteger(fromIndex); if (fromIndex < 0) { fromIndex = nativeMax(length + fromIndex, 0); } return baseIndexOf(array, value, fromIndex); } /** * Gets all but the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.initial([1, 2, 3]); * // => [1, 2] */ function initial(array) { return dropRight(array, 1); } /** * Creates an array of unique values that are included in all given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) * for equality comparisons. The order of result values is determined by the * order they occur in the first array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersection([2, 1], [4, 2], [1, 2]); * // => [2] */ var intersection = rest(function(arrays) { var mapped = arrayMap(arrays, castArrayLikeObject); return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped) : []; }); /** * This method is like `_.intersection` except that it accepts `iteratee` * which is invoked for each element of each `arrays` to generate the criterion * by which they're compared. Result values are chosen from the first array. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Array|Function|Object|string} [iteratee=_.identity] * The iteratee invoked per element. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersectionBy([2.1, 1.2], [4.3, 2.4], Math.floor); * // => [2.1] * * // The `_.property` iteratee shorthand. * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }] */ var intersectionBy = rest(function(arrays) { var iteratee = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); if (iteratee === last(mapped)) { iteratee = undefined; } else { mapped.pop(); } return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped, getIteratee(iteratee)) : []; }); /** * This method is like `_.intersection` except that it accepts `comparator` * which is invoked to compare elements of `arrays`. Result values are chosen * from the first array. The comparator is invoked with two arguments: * (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of intersecting values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.intersectionWith(objects, others, _.isEqual); * // => [{ 'x': 1, 'y': 2 }] */ var intersectionWith = rest(function(arrays) { var comparator = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); if (comparator === last(mapped)) { comparator = undefined; } else { mapped.pop(); } return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped, undefined, comparator) : []; }); /** * Converts all elements in `array` into a string separated by `separator`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to convert. * @param {string} [separator=','] The element separator. * @returns {string} Returns the joined string. * @example * * _.join(['a', 'b', 'c'], '~'); * // => 'a~b~c' */ function join(array, separator) { return array ? nativeJoin.call(array, separator) : ''; } /** * Gets the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array ? array.length : 0; return length ? array[length - 1] : undefined; } /** * This method is like `_.indexOf` except that it iterates over elements of * `array` from right to left. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to search. * @param {*} value The value to search for. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.lastIndexOf([1, 2, 1, 2], 2); * // => 3 * * // Search from the `fromIndex`. * _.lastIndexOf([1, 2, 1, 2], 2, 2); * // => 1 */ function lastIndexOf(array, value, fromIndex) { var length = array ? array.length : 0; if (!length) { return -1; } var index = length; if (fromIndex !== undefined) { index = toInteger(fromIndex); index = ( index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1) ) + 1; } if (value !== value) { return indexOfNaN(array, index, true); } while (index--) { if (array[index] === value) { return index; } } return -1; } /** * Gets the element at `n` index of `array`. If `n` is negative, the nth * element from the end is returned. * * @static * @memberOf _ * @since 4.11.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=0] The index of the element to return. * @returns {*} Returns the nth element of `array`. * @example * * var array = ['a', 'b', 'c', 'd']; * * _.nth(array, 1); * // => 'b' * * _.nth(array, -2); * // => 'c'; */ function nth(array, n) { return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; } /** * Removes all given values from `array` using * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) * for equality comparisons. * * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` * to remove elements from an array by predicate. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to modify. * @param {...*} [values] The values to remove. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3, 1, 2, 3]; * * _.pull(array, 2, 3); * console.log(array); * // => [1, 1] */ var pull = rest(pullAll); /** * This method is like `_.pull` except that it accepts an array of values to remove. * * **Note:** Unlike `_.difference`, this method mutates `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3, 1, 2, 3]; * * _.pullAll(array, [2, 3]); * console.log(array); * // => [1, 1] */ function pullAll(array, values) { return (array && array.length && values && values.length) ? basePullAll(array, values) : array; } /** * This method is like `_.pullAll` except that it accepts `iteratee` which is * invoked for each element of `array` and `values` to generate the criterion * by which they're compared. The iteratee is invoked with one argument: (value). * * **Note:** Unlike `_.differenceBy`, this method mutates `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Array|Function|Object|string} [iteratee=_.identity] * The iteratee invoked per element. * @returns {Array} Returns `array`. * @example * * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; * * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); * console.log(array); * // => [{ 'x': 2 }] */ function pullAllBy(array, values, iteratee) { return (array && array.length && values && values.length) ? basePullAll(array, values, getIteratee(iteratee)) : array; } /** * This method is like `_.pullAll` except that it accepts `comparator` which * is invoked to compare elements of `array` to `values`. The comparator is * invoked with two arguments: (arrVal, othVal). * * **Note:** Unlike `_.differenceWith`, this method mutates `array`. * * @static * @memberOf _ * @since 4.6.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns `array`. * @example * * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; * * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); * console.log(array); * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] */ function pullAllWith(array, values, comparator) { return (array && array.length && values && values.length) ? basePullAll(array, values, undefined, comparator) : array; } /** * Removes elements from `array` corresponding to `indexes` and returns an * array of removed elements. * * **Note:** Unlike `_.at`, this method mutates `array`. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to modify. * @param {...(number|number[])} [indexes] The indexes of elements to remove. * @returns {Array} Returns the new array of removed elements. * @example * * var array = [5, 10, 15, 20]; * var evens = _.pullAt(array, 1, 3); * * console.log(array); * // => [5, 15] * * console.log(evens); * // => [10, 20] */ var pullAt = rest(function(array, indexes) { indexes = baseFlatten(indexes, 1); var length = array ? array.length : 0, result = baseAt(array, indexes); basePullAt(array, arrayMap(indexes, function(index) { return isIndex(index, length) ? +index : index; }).sort(compareAscending)); return result; }); /** * Removes all elements from `array` that `predicate` returns truthy for * and returns an array of the removed elements. The predicate is invoked * with three arguments: (value, index, array). * * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` * to pull elements from an array by value. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to modify. * @param {Array|Function|Object|string} [predicate=_.identity] * The function invoked per iteration. * @returns {Array} Returns the new array of removed elements. * @example * * var array = [1, 2, 3, 4]; * var evens = _.remove(array, function(n) { * return n % 2 == 0; * }); * * console.log(array); * // => [1, 3] * * console.log(evens); * // => [2, 4] */ function remove(array, predicate) { var result = []; if (!(array && array.length)) { return result; } var index = -1, indexes = [], length = array.length; predicate = getIteratee(predicate, 3); while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result.push(value); indexes.push(index); } } basePullAt(array, indexes); return result; } /** * Reverses `array` so that the first element becomes the last, the second * element becomes the second to last, and so on. * * **Note:** This method mutates `array` and is based on * [`Array#reverse`](https://mdn.io/Array/reverse). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.reverse(array); * // => [3, 2, 1] * * console.log(array); * // => [3, 2, 1] */ function reverse(array) { return array ? nativeReverse.call(array) : array; } /** * Creates a slice of `array` from `start` up to, but not including, `end`. * * **Note:** This method is used instead of * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are * returned. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function slice(array, start, end) { var length = array ? array.length : 0; if (!length) { return []; } if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { start = 0; end = length; } else { start = start == null ? 0 : toInteger(start); end = end === undefined ? length : toInteger(end); } return baseSlice(array, start, end); } /** * Uses a binary search to determine the lowest index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedIndex([30, 50], 40); * // => 1 * * _.sortedIndex([4, 5], 4); * // => 0 */ function sortedIndex(array, value) { return baseSortedIndex(array, value); } /** * This method is like `_.sortedIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Array|Function|Object|string} [iteratee=_.identity] * The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * var dict = { 'thirty': 30, 'forty': 40, 'fifty': 50 }; * * _.sortedIndexBy(['thirty', 'fifty'], 'forty', _.propertyOf(dict)); * // => 1 * * // The `_.property` iteratee shorthand. * _.sortedIndexBy([{ 'x': 4 }, { 'x': 5 }], { 'x': 4 }, 'x'); * // => 0 */ function sortedIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee)); } /** * This method is like `_.indexOf` except that it performs a binary * search on a sorted `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to search. * @param {*} value The value to search for. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.sortedIndexOf([1, 1, 2, 2], 2); * // => 2 */ function sortedIndexOf(array, value) { var length = array ? array.length : 0; if (length) { var index = baseSortedIndex(array, value); if (index < length && eq(array[index], value)) { return index; } } return -1; } /** * This method is like `_.sortedIndex` except that it returns the highest * index at which `value` should be inserted into `array` in order to * maintain its sort order. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedLastIndex([4, 5], 4); * // => 1 */ function sortedLastIndex(array, value) { return baseSortedIndex(array, value, true); } /** * This method is like `_.sortedLastIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Array|Function|Object|string} [iteratee=_.identity] * The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * // The `_.property` iteratee shorthand. * _.sortedLastIndexBy([{ 'x': 4 }, { 'x': 5 }], { 'x': 4 }, 'x'); * // => 1 */ function sortedLastIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee), true); } /** * This method is like `_.lastIndexOf` except that it performs a binary * search on a sorted `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to search. * @param {*} value The value to search for. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.sortedLastIndexOf([1, 1, 2, 2], 2); * // => 3 */ function sortedLastIndexOf(array, value) { var length = array ? array.length : 0; if (length) { var index = baseSortedIndex(array, value, true) - 1; if (eq(array[index], value)) { return index; } } return -1; } /** * This method is like `_.uniq` except that it's designed and optimized * for sorted arrays. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @returns {Array} Returns the new duplicate free array. * @example * * _.sortedUniq([1, 1, 2]); * // => [1, 2] */ function sortedUniq(array) { return (array && array.length) ? baseSortedUniq(array) : []; } /** * This method is like `_.uniqBy` except that it's designed and optimized * for sorted arrays. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); * // => [1.1, 2.3] */ function sortedUniqBy(array, iteratee) { return (array && array.length) ? baseSortedUniq(array, getIteratee(iteratee)) : []; } /** * Gets all but the first element of `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.tail([1, 2, 3]); * // => [2, 3] */ function tail(array) { return drop(array, 1); } /** * Creates a slice of `array` with `n` elements taken from the beginning. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.take([1, 2, 3]); * // => [1] * * _.take([1, 2, 3], 2); * // => [1, 2] * * _.take([1, 2, 3], 5); * // => [1, 2, 3] * * _.take([1, 2, 3], 0); * // => [] */ function take(array, n, guard) { if (!(array && array.length)) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` with `n` elements taken from the end. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.takeRight([1, 2, 3]); * // => [3] * * _.takeRight([1, 2, 3], 2); * // => [2, 3] * * _.takeRight([1, 2, 3], 5); * // => [1, 2, 3] * * _.takeRight([1, 2, 3], 0); * // => [] */ function takeRight(array, n, guard) { var length = array ? array.length : 0; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); n = length - n; return baseSlice(array, n < 0 ? 0 : n, length); } /** * Creates a slice of `array` with elements taken from the end. Elements are * taken until `predicate` returns falsey. The predicate is invoked with * three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Array|Function|Object|string} [predicate=_.identity] * The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.takeRightWhile(users, function(o) { return !o.active; }); * // => objects for ['fred', 'pebbles'] * * // The `_.matches` iteratee shorthand. * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); * // => objects for ['pebbles'] * * // The `_.matchesProperty` iteratee shorthand. * _.takeRightWhile(users, ['active', false]); * // => objects for ['fred', 'pebbles'] * * // The `_.property` iteratee shorthand. * _.takeRightWhile(users, 'active'); * // => [] */ function takeRightWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), false, true) : []; } /** * Creates a slice of `array` with elements taken from the beginning. Elements * are taken until `predicate` returns falsey. The predicate is invoked with * three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Array|Function|Object|string} [predicate=_.identity] * The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false}, * { 'user': 'pebbles', 'active': true } * ]; * * _.takeWhile(users, function(o) { return !o.active; }); * // => objects for ['barney', 'fred'] * * // The `_.matches` iteratee shorthand. * _.takeWhile(users, { 'user': 'barney', 'active': false }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.takeWhile(users, ['active', false]); * // => objects for ['barney', 'fred'] * * // The `_.property` iteratee shorthand. * _.takeWhile(users, 'active'); * // => [] */ function takeWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3)) : []; } /** * Creates an array of unique values, in order, from all given arrays using * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) * for equality comparisons. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of combined values. * @example * * _.union([2, 1], [4, 2], [1, 2]); * // => [2, 1, 4] */ var union = rest(function(arrays) { return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); }); /** * This method is like `_.union` except that it accepts `iteratee` which is * invoked for each element of each `arrays` to generate the criterion by * which uniqueness is computed. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Array|Function|Object|string} [iteratee=_.identity] * The iteratee invoked per element. * @returns {Array} Returns the new array of combined values. * @example * * _.unionBy([2.1, 1.2], [4.3, 2.4], Math.floor); * // => [2.1, 1.2, 4.3] * * // The `_.property` iteratee shorthand. * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ var unionBy = rest(function(arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee)); }); /** * This method is like `_.union` except that it accepts `comparator` which * is invoked to compare elements of `arrays`. The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of combined values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.unionWith(objects, others, _.isEqual); * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ var unionWith = rest(function(arrays) { var comparator = last(arrays); if (isArrayLikeObject(comparator)) { comparator = undefined; } return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); }); /** * Creates a duplicate-free version of an array, using * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) * for equality comparisons, in which only the first occurrence of each * element is kept. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @returns {Array} Returns the new duplicate free array. * @example * * _.uniq([2, 1, 2]); * // => [2, 1] */ function uniq(array) { return (array && array.length) ? baseUniq(array) : []; } /** * This method is like `_.uniq` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * uniqueness is computed. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Array|Function|Object|string} [iteratee=_.identity] * The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * _.uniqBy([2.1, 1.2, 2.3], Math.floor); * // => [2.1, 1.2] * * // The `_.property` iteratee shorthand. * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ function uniqBy(array, iteratee) { return (array && array.length) ? baseUniq(array, getIteratee(iteratee)) : []; } /** * This method is like `_.uniq` except that it accepts `comparator` which * is invoked to compare elements of `array`. The comparator is invoked with * two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.uniqWith(objects, _.isEqual); * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] */ function uniqWith(array, comparator) { return (array && array.length) ? baseUniq(array, undefined, comparator) : []; } /** * This method is like `_.zip` except that it accepts an array of grouped * elements and creates an array regrouping the elements to their pre-zip * configuration. * * @static * @memberOf _ * @since 1.2.0 * @category Array * @param {Array} array The array of grouped elements to process. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip(['fred', 'barney'], [30, 40], [true, false]); * // => [['fred', 30, true], ['barney', 40, false]] * * _.unzip(zipped); * // => [['fred', 'barney'], [30, 40], [true, false]] */ function unzip(array) { if (!(array && array.length)) { return []; } var length = 0; array = arrayFilter(array, function(group) { if (isArrayLikeObject(group)) { length = nativeMax(group.length, length); return true; } }); return baseTimes(length, function(index) { return arrayMap(array, baseProperty(index)); }); } /** * This method is like `_.unzip` except that it accepts `iteratee` to specify * how regrouped values should be combined. The iteratee is invoked with the * elements of each group: (...group). * * @static * @memberOf _ * @since 3.8.0 * @category Array * @param {Array} array The array of grouped elements to process. * @param {Function} [iteratee=_.identity] The function to combine * regrouped values. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip([1, 2], [10, 20], [100, 200]); * // => [[1, 10, 100], [2, 20, 200]] * * _.unzipWith(zipped, _.add); * // => [3, 30, 300] */ function unzipWith(array, iteratee) { if (!(array && array.length)) { return []; } var result = unzip(array); if (iteratee == null) { return result; } return arrayMap(result, function(group) { return apply(iteratee, undefined, group); }); } /** * Creates an array excluding all given values using * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) * for equality comparisons. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...*} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.xor * @example * * _.without([1, 2, 1, 3], 1, 2); * // => [3] */ var without = rest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, values) : []; }); /** * Creates an array of unique values that is the * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) * of the given arrays. The order of result values is determined by the order * they occur in the arrays. * * @static * @memberOf _ * @since 2.4.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.without * @example * * _.xor([2, 1], [4, 2]); * // => [1, 4] */ var xor = rest(function(arrays) { return baseXor(arrayFilter(arrays, isArrayLikeObject)); }); /** * This method is like `_.xor` except that it accepts `iteratee` which is * invoked for each element of each `arrays` to generate the criterion by * which by which they're compared. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Array|Function|Object|string} [iteratee=_.identity] * The iteratee invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * _.xorBy([2.1, 1.2], [4.3, 2.4], Math.floor); * // => [1.2, 4.3] * * // The `_.property` iteratee shorthand. * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 2 }] */ var xorBy = rest(function(arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee)); }); /** * This method is like `_.xor` except that it accepts `comparator` which is * invoked to compare elements of `arrays`. The comparator is invoked with * two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.xorWith(objects, others, _.isEqual); * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ var xorWith = rest(function(arrays) { var comparator = last(arrays); if (isArrayLikeObject(comparator)) { comparator = undefined; } return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); }); /** * Creates an array of grouped elements, the first of which contains the * first elements of the given arrays, the second of which contains the * second elements of the given arrays, and so on. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to process. * @returns {Array} Returns the new array of grouped elements. * @example * * _.zip(['fred', 'barney'], [30, 40], [true, false]); * // => [['fred', 30, true], ['barney', 40, false]] */ var zip = rest(unzip); /** * This method is like `_.fromPairs` except that it accepts two arrays, * one of property identifiers and one of corresponding values. * * @static * @memberOf _ * @since 0.4.0 * @category Array * @param {Array} [props=[]] The property identifiers. * @param {Array} [values=[]] The property values. * @returns {Object} Returns the new object. * @example * * _.zipObject(['a', 'b'], [1, 2]); * // => { 'a': 1, 'b': 2 } */ function zipObject(props, values) { return baseZipObject(props || [], values || [], assignValue); } /** * This method is like `_.zipObject` except that it supports property paths. * * @static * @memberOf _ * @since 4.1.0 * @category Array * @param {Array} [props=[]] The property identifiers. * @param {Array} [values=[]] The property values. * @returns {Object} Returns the new object. * @example * * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } */ function zipObjectDeep(props, values) { return baseZipObject(props || [], values || [], baseSet); } /** * This method is like `_.zip` except that it accepts `iteratee` to specify * how grouped values should be combined. The iteratee is invoked with the * elements of each group: (...group). * * @static * @memberOf _ * @since 3.8.0 * @category Array * @param {...Array} [arrays] The arrays to process. * @param {Function} [iteratee=_.identity] The function to combine grouped values. * @returns {Array} Returns the new array of grouped elements. * @example * * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { * return a + b + c; * }); * // => [111, 222] */ var zipWith = rest(function(arrays) { var length = arrays.length, iteratee = length > 1 ? arrays[length - 1] : undefined; iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; return unzipWith(arrays, iteratee); }); /*------------------------------------------------------------------------*/ /** * Creates a `lodash` wrapper instance that wraps `value` with explicit method * chain sequences enabled. The result of such sequences must be unwrapped * with `_#value`. * * @static * @memberOf _ * @since 1.3.0 * @category Seq * @param {*} value The value to wrap. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'pebbles', 'age': 1 } * ]; * * var youngest = _ * .chain(users) * .sortBy('age') * .map(function(o) { * return o.user + ' is ' + o.age; * }) * .head() * .value(); * // => 'pebbles is 1' */ function chain(value) { var result = lodash(value); result.__chain__ = true; return result; } /** * This method invokes `interceptor` and returns `value`. The interceptor * is invoked with one argument; (value). The purpose of this method is to * "tap into" a method chain sequence in order to modify intermediate results. * * @static * @memberOf _ * @since 0.1.0 * @category Seq * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {*} Returns `value`. * @example * * _([1, 2, 3]) * .tap(function(array) { * // Mutate input array. * array.pop(); * }) * .reverse() * .value(); * // => [2, 1] */ function tap(value, interceptor) { interceptor(value); return value; } /** * This method is like `_.tap` except that it returns the result of `interceptor`. * The purpose of this method is to "pass thru" values replacing intermediate * results in a method chain sequence. * * @static * @memberOf _ * @since 3.0.0 * @category Seq * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {*} Returns the result of `interceptor`. * @example * * _(' abc ') * .chain() * .trim() * .thru(function(value) { * return [value]; * }) * .value(); * // => ['abc'] */ function thru(value, interceptor) { return interceptor(value); } /** * This method is the wrapper version of `_.at`. * * @name at * @memberOf _ * @since 1.0.0 * @category Seq * @param {...(string|string[])} [paths] The property paths of elements to pick. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; * * _(object).at(['a[0].b.c', 'a[1]']).value(); * // => [3, 4] * * _(['a', 'b', 'c']).at(0, 2).value(); * // => ['a', 'c'] */ var wrapperAt = rest(function(paths) { paths = baseFlatten(paths, 1); var length = paths.length, start = length ? paths[0] : 0, value = this.__wrapped__, interceptor = function(object) { return baseAt(object, paths); }; if (length > 1 || this.__actions__.length || !(value instanceof LazyWrapper) || !isIndex(start)) { return this.thru(interceptor); } value = value.slice(start, +start + (length ? 1 : 0)); value.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined }); return new LodashWrapper(value, this.__chain__).thru(function(array) { if (length && !array.length) { array.push(undefined); } return array; }); }); /** * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. * * @name chain * @memberOf _ * @since 0.1.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 } * ]; * * // A sequence without explicit chaining. * _(users).head(); * // => { 'user': 'barney', 'age': 36 } * * // A sequence with explicit chaining. * _(users) * .chain() * .head() * .pick('user') * .value(); * // => { 'user': 'barney' } */ function wrapperChain() { return chain(this); } /** * Executes the chain sequence and returns the wrapped result. * * @name commit * @memberOf _ * @since 3.2.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2]; * var wrapped = _(array).push(3); * * console.log(array); * // => [1, 2] * * wrapped = wrapped.commit(); * console.log(array); * // => [1, 2, 3] * * wrapped.last(); * // => 3 * * console.log(array); * // => [1, 2, 3] */ function wrapperCommit() { return new LodashWrapper(this.value(), this.__chain__); } /** * Gets the next value on a wrapped object following the * [iterator protocol](https://mdn.io/iteration_protocols#iterator). * * @name next * @memberOf _ * @since 4.0.0 * @category Seq * @returns {Object} Returns the next iterator value. * @example * * var wrapped = _([1, 2]); * * wrapped.next(); * // => { 'done': false, 'value': 1 } * * wrapped.next(); * // => { 'done': false, 'value': 2 } * * wrapped.next(); * // => { 'done': true, 'value': undefined } */ function wrapperNext() { if (this.__values__ === undefined) { this.__values__ = toArray(this.value()); } var done = this.__index__ >= this.__values__.length, value = done ? undefined : this.__values__[this.__index__++]; return { 'done': done, 'value': value }; } /** * Enables the wrapper to be iterable. * * @name Symbol.iterator * @memberOf _ * @since 4.0.0 * @category Seq * @returns {Object} Returns the wrapper object. * @example * * var wrapped = _([1, 2]); * * wrapped[Symbol.iterator]() === wrapped; * // => true * * Array.from(wrapped); * // => [1, 2] */ function wrapperToIterator() { return this; } /** * Creates a clone of the chain sequence planting `value` as the wrapped value. * * @name plant * @memberOf _ * @since 3.2.0 * @category Seq * @param {*} value The value to plant. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2]).map(square); * var other = wrapped.plant([3, 4]); * * other.value(); * // => [9, 16] * * wrapped.value(); * // => [1, 4] */ function wrapperPlant(value) { var result, parent = this; while (parent instanceof baseLodash) { var clone = wrapperClone(parent); clone.__index__ = 0; clone.__values__ = undefined; if (result) { previous.__wrapped__ = clone; } else { result = clone; } var previous = clone; parent = parent.__wrapped__; } previous.__wrapped__ = value; return result; } /** * This method is the wrapper version of `_.reverse`. * * **Note:** This method mutates the wrapped array. * * @name reverse * @memberOf _ * @since 0.1.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2, 3]; * * _(array).reverse().value() * // => [3, 2, 1] * * console.log(array); * // => [3, 2, 1] */ function wrapperReverse() { var value = this.__wrapped__; if (value instanceof LazyWrapper) { var wrapped = value; if (this.__actions__.length) { wrapped = new LazyWrapper(this); } wrapped = wrapped.reverse(); wrapped.__actions__.push({ 'func': thru, 'args': [reverse], 'thisArg': undefined }); return new LodashWrapper(wrapped, this.__chain__); } return this.thru(reverse); } /** * Executes the chain sequence to resolve the unwrapped value. * * @name value * @memberOf _ * @since 0.1.0 * @alias toJSON, valueOf * @category Seq * @returns {*} Returns the resolved unwrapped value. * @example * * _([1, 2, 3]).value(); * // => [1, 2, 3] */ function wrapperValue() { return baseWrapperValue(this.__wrapped__, this.__actions__); } /*------------------------------------------------------------------------*/ /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The corresponding value of * each key is the number of times the key was returned by `iteratee`. The * iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.5.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array|Function|Object|string} [iteratee=_.identity] * The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * _.countBy([6.1, 4.2, 6.3], Math.floor); * // => { '4': 1, '6': 2 } * * _.countBy(['one', 'two', 'three'], 'length'); * // => { '3': 2, '5': 1 } */ var countBy = createAggregator(function(result, value, key) { hasOwnProperty.call(result, key) ? ++result[key] : (result[key] = 1); }); /** * Checks if `predicate` returns truthy for **all** elements of `collection`. * Iteration is stopped once `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array|Function|Object|string} [predicate=_.identity] * The function invoked per iteration. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. * @example * * _.every([true, 1, null, 'yes'], Boolean); * // => false * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.every(users, { 'user': 'barney', 'active': false }); * // => false * * // The `_.matchesProperty` iteratee shorthand. * _.every(users, ['active', false]); * // => true * * // The `_.property` iteratee shorthand. * _.every(users, 'active'); * // => false */ function every(collection, predicate, guard) { var func = isArray(collection) ? arrayEvery : baseEvery; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined; } return func(collection, getIteratee(predicate, 3)); } /** * Iterates over elements of `collection`, returning an array of all elements * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array|Function|Object|string} [predicate=_.identity] * The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.reject * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * _.filter(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.filter(users, { 'age': 36, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.filter(users, 'active'); * // => objects for ['barney'] */ function filter(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, getIteratee(predicate, 3)); } /** * Iterates over elements of `collection`, returning the first element * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to search. * @param {Array|Function|Object|string} [predicate=_.identity] * The function invoked per iteration. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false }, * { 'user': 'pebbles', 'age': 1, 'active': true } * ]; * * _.find(users, function(o) { return o.age < 40; }); * // => object for 'barney' * * // The `_.matches` iteratee shorthand. * _.find(users, { 'age': 1, 'active': true }); * // => object for 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.find(users, ['active', false]); * // => object for 'fred' * * // The `_.property` iteratee shorthand. * _.find(users, 'active'); * // => object for 'barney' */ function find(collection, predicate) { predicate = getIteratee(predicate, 3); if (isArray(collection)) { var index = baseFindIndex(collection, predicate); return index > -1 ? collection[index] : undefined; } return baseFind(collection, predicate, baseEach); } /** * This method is like `_.find` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @category Collection * @param {Array|Object} collection The collection to search. * @param {Array|Function|Object|string} [predicate=_.identity] * The function invoked per iteration. * @returns {*} Returns the matched element, else `undefined`. * @example * * _.findLast([1, 2, 3, 4], function(n) { * return n % 2 == 1; * }); * // => 3 */ function findLast(collection, predicate) { predicate = getIteratee(predicate, 3); if (isArray(collection)) { var index = baseFindIndex(collection, predicate, true); return index > -1 ? collection[index] : undefined; } return baseFind(collection, predicate, baseEachRight); } /** * Creates a flattened array of values by running each element in `collection` * thru `iteratee` and flattening the mapped results. The iteratee is invoked * with three arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array|Function|Object|string} [iteratee=_.identity] * The function invoked per iteration. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [n, n]; * } * * _.flatMap([1, 2], duplicate); * // => [1, 1, 2, 2] */ function flatMap(collection, iteratee) { return baseFlatten(map(collection, iteratee), 1); } /** * This method is like `_.flatMap` except that it recursively flattens the * mapped results. * * @static * @memberOf _ * @since 4.7.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array|Function|Object|string} [iteratee=_.identity] * The function invoked per iteration. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [[[n, n]]]; * } * * _.flatMapDeep([1, 2], duplicate); * // => [1, 1, 2, 2] */ function flatMapDeep(collection, iteratee) { return baseFlatten(map(collection, iteratee), INFINITY); } /** * This method is like `_.flatMap` except that it recursively flattens the * mapped results up to `depth` times. * * @static * @memberOf _ * @since 4.7.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array|Function|Object|string} [iteratee=_.identity] * The function invoked per iteration. * @param {number} [depth=1] The maximum recursion depth. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [[[n, n]]]; * } * * _.flatMapDepth([1, 2], duplicate, 2); * // => [[1, 1], [2, 2]] */ function flatMapDepth(collection, iteratee, depth) { depth = depth === undefined ? 1 : toInteger(depth); return baseFlatten(map(collection, iteratee), depth); } /** * Iterates over elements of `collection` and invokes `iteratee` for each element. * The iteratee is invoked with three arguments: (value, index|key, collection). * Iteratee functions may exit iteration early by explicitly returning `false`. * * **Note:** As with other "Collections" methods, objects with a "length" * property are iterated like arrays. To avoid this behavior use `_.forIn` * or `_.forOwn` for object iteration. * * @static * @memberOf _ * @since 0.1.0 * @alias each * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEachRight * @example * * _([1, 2]).forEach(function(value) { * console.log(value); * }); * // => Logs `1` then `2`. * * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forEach(collection, iteratee) { var func = isArray(collection) ? arrayEach : baseEach; return func(collection, getIteratee(iteratee, 3)); } /** * This method is like `_.forEach` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @alias eachRight * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEach * @example * * _.forEachRight([1, 2], function(value) { * console.log(value); * }); * // => Logs `2` then `1`. */ function forEachRight(collection, iteratee) { var func = isArray(collection) ? arrayEachRight : baseEachRight; return func(collection, getIteratee(iteratee, 3)); } /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The order of grouped values * is determined by the order they occur in `collection`. The corresponding * value of each key is an array of elements responsible for generating the * key. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array|Function|Object|string} [iteratee=_.identity] * The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * _.groupBy([6.1, 4.2, 6.3], Math.floor); * // => { '4': [4.2], '6': [6.1, 6.3] } * * // The `_.property` iteratee shorthand. * _.groupBy(['one', 'two', 'three'], 'length'); * // => { '3': ['one', 'two'], '5': ['three'] } */ var groupBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { result[key].push(value); } else { result[key] = [value]; } }); /** * Checks if `value` is in `collection`. If `collection` is a string, it's * checked for a substring of `value`, otherwise * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) * is used for equality comparisons. If `fromIndex` is negative, it's used as * the offset from the end of `collection`. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to search. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {boolean} Returns `true` if `value` is found, else `false`. * @example * * _.includes([1, 2, 3], 1); * // => true * * _.includes([1, 2, 3], 1, 2); * // => false * * _.includes({ 'user': 'fred', 'age': 40 }, 'fred'); * // => true * * _.includes('pebbles', 'eb'); * // => true */ function includes(collection, value, fromIndex, guard) { collection = isArrayLike(collection) ? collection : values(collection); fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; var length = collection.length; if (fromIndex < 0) { fromIndex = nativeMax(length + fromIndex, 0); } return isString(collection) ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) : (!!length && baseIndexOf(collection, value, fromIndex) > -1); } /** * Invokes the method at `path` of each element in `collection`, returning * an array of the results of each invoked method. Any additional arguments * are provided to each invoked method. If `methodName` is a function, it's * invoked for and `this` bound to, each element in `collection`. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array|Function|string} path The path of the method to invoke or * the function invoked per iteration. * @param {...*} [args] The arguments to invoke each method with. * @returns {Array} Returns the array of results. * @example * * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); * // => [[1, 5, 7], [1, 2, 3]] * * _.invokeMap([123, 456], String.prototype.split, ''); * // => [['1', '2', '3'], ['4', '5', '6']] */ var invokeMap = rest(function(collection, path, args) { var index = -1, isFunc = typeof path == 'function', isProp = isKey(path), result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value) { var func = isFunc ? path : ((isProp && value != null) ? value[path] : undefined); result[++index] = func ? apply(func, value, args) : baseInvoke(value, path, args); }); return result; }); /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The corresponding value of * each key is the last element responsible for generating the key. The * iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array|Function|Object|string} [iteratee=_.identity] * The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * var array = [ * { 'dir': 'left', 'code': 97 }, * { 'dir': 'right', 'code': 100 } * ]; * * _.keyBy(array, function(o) { * return String.fromCharCode(o.code); * }); * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } * * _.keyBy(array, 'dir'); * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } */ var keyBy = createAggregator(function(result, value, key) { result[key] = value; }); /** * Creates an array of values by running each element in `collection` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. * * The guarded methods are: * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, * `template`, `trim`, `trimEnd`, `trimStart`, and `words` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array|Function|Object|string} [iteratee=_.identity] * The function invoked per iteration. * @returns {Array} Returns the new mapped array. * @example * * function square(n) { * return n * n; * } * * _.map([4, 8], square); * // => [16, 64] * * _.map({ 'a': 4, 'b': 8 }, square); * // => [16, 64] (iteration order is not guaranteed) * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * // The `_.property` iteratee shorthand. * _.map(users, 'user'); * // => ['barney', 'fred'] */ function map(collection, iteratee) { var func = isArray(collection) ? arrayMap : baseMap; return func(collection, getIteratee(iteratee, 3)); } /** * This method is like `_.sortBy` except that it allows specifying the sort * orders of the iteratees to sort by. If `orders` is unspecified, all values * are sorted in ascending order. Otherwise, specify an order of "desc" for * descending or "asc" for ascending sort order of corresponding values. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] * The iteratees to sort by. * @param {string[]} [orders] The sort orders of `iteratees`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 34 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 36 } * ]; * * // Sort by `user` in ascending order and by `age` in descending order. * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] */ function orderBy(collection, iteratees, orders, guard) { if (collection == null) { return []; } if (!isArray(iteratees)) { iteratees = iteratees == null ? [] : [iteratees]; } orders = guard ? undefined : orders; if (!isArray(orders)) { orders = orders == null ? [] : [orders]; } return baseOrderBy(collection, iteratees, orders); } /** * Creates an array of elements split into two groups, the first of which * contains elements `predicate` returns truthy for, the second of which * contains elements `predicate` returns falsey for. The predicate is * invoked with one argument: (value). * * @static * @memberOf _ * @since 3.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array|Function|Object|string} [predicate=_.identity] * The function invoked per iteration. * @returns {Array} Returns the array of grouped elements. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true }, * { 'user': 'pebbles', 'age': 1, 'active': false } * ]; * * _.partition(users, function(o) { return o.active; }); * // => objects for [['fred'], ['barney', 'pebbles']] * * // The `_.matches` iteratee shorthand. * _.partition(users, { 'age': 1, 'active': false }); * // => objects for [['pebbles'], ['barney', 'fred']] * * // The `_.matchesProperty` iteratee shorthand. * _.partition(users, ['active', false]); * // => objects for [['barney', 'pebbles'], ['fred']] * * // The `_.property` iteratee shorthand. * _.partition(users, 'active'); * // => objects for [['fred'], ['barney', 'pebbles']] */ var partition = createAggregator(function(result, value, key) { result[key ? 0 : 1].push(value); }, function() { return [[], []]; }); /** * Reduces `collection` to a value which is the accumulated result of running * each element in `collection` thru `iteratee`, where each successive * invocation is supplied the return value of the previous. If `accumulator` * is not given, the first element of `collection` is used as the initial * value. The iteratee is invoked with four arguments: * (accumulator, value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.reduce`, `_.reduceRight`, and `_.transform`. * * The guarded methods are: * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, * and `sortBy` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduceRight * @example * * _.reduce([1, 2], function(sum, n) { * return sum + n; * }, 0); * // => 3 * * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * return result; * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) */ function reduce(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); } /** * This method is like `_.reduce` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduce * @example * * var array = [[0, 1], [2, 3], [4, 5]]; * * _.reduceRight(array, function(flattened, other) { * return flattened.concat(other); * }, []); * // => [4, 5, 2, 3, 0, 1] */ function reduceRight(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduceRight : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); } /** * The opposite of `_.filter`; this method returns the elements of `collection` * that `predicate` does **not** return truthy for. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array|Function|Object|string} [predicate=_.identity] * The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.filter * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true } * ]; * * _.reject(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.reject(users, { 'age': 40, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.reject(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.reject(users, 'active'); * // => objects for ['barney'] */ function reject(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; predicate = getIteratee(predicate, 3); return func(collection, function(value, index, collection) { return !predicate(value, index, collection); }); } /** * Gets a random element from `collection`. * * @static * @memberOf _ * @since 2.0.0 * @category Collection * @param {Array|Object} collection The collection to sample. * @returns {*} Returns the random element. * @example * * _.sample([1, 2, 3, 4]); * // => 2 */ function sample(collection) { var array = isArrayLike(collection) ? collection : values(collection), length = array.length; return length > 0 ? array[baseRandom(0, length - 1)] : undefined; } /** * Gets `n` random elements at unique keys from `collection` up to the * size of `collection`. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to sample. * @param {number} [n=1] The number of elements to sample. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the random elements. * @example * * _.sampleSize([1, 2, 3], 2); * // => [3, 1] * * _.sampleSize([1, 2, 3], 4); * // => [2, 3, 1] */ function sampleSize(collection, n, guard) { var index = -1, result = toArray(collection), length = result.length, lastIndex = length - 1; if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { n = 1; } else { n = baseClamp(toInteger(n), 0, length); } while (++index < n) { var rand = baseRandom(index, lastIndex), value = result[rand]; result[rand] = result[index]; result[index] = value; } result.length = n; return result; } /** * Creates an array of shuffled values, using a version of the * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to shuffle. * @returns {Array} Returns the new shuffled array. * @example * * _.shuffle([1, 2, 3, 4]); * // => [4, 1, 3, 2] */ function shuffle(collection) { return sampleSize(collection, MAX_ARRAY_LENGTH); } /** * Gets the size of `collection` by returning its length for array-like * values or the number of own enumerable string keyed properties for objects. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @returns {number} Returns the collection size. * @example * * _.size([1, 2, 3]); * // => 3 * * _.size({ 'a': 1, 'b': 2 }); * // => 2 * * _.size('pebbles'); * // => 7 */ function size(collection) { if (collection == null) { return 0; } if (isArrayLike(collection)) { var result = collection.length; return (result && isString(collection)) ? stringSize(collection) : result; } if (isObjectLike(collection)) { var tag = getTag(collection); if (tag == mapTag || tag == setTag) { return collection.size; } } return keys(collection).length; } /** * Checks if `predicate` returns truthy for **any** element of `collection`. * Iteration is stopped once `predicate` returns truthy. The predicate is * invoked with three arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array|Function|Object|string} [predicate=_.identity] * The function invoked per iteration. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. * @example * * _.some([null, 0, 'yes', false], Boolean); * // => true * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.some(users, { 'user': 'barney', 'active': false }); * // => false * * // The `_.matchesProperty` iteratee shorthand. * _.some(users, ['active', false]); * // => true * * // The `_.property` iteratee shorthand. * _.some(users, 'active'); * // => true */ function some(collection, predicate, guard) { var func = isArray(collection) ? arraySome : baseSome; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined; } return func(collection, getIteratee(predicate, 3)); } /** * Creates an array of elements, sorted in ascending order by the results of * running each element in a collection thru each iteratee. This method * performs a stable sort, that is, it preserves the original sort order of * equal elements. The iteratees are invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {...(Array|Array[]|Function|Function[]|Object|Object[]|string|string[])} * [iteratees=[_.identity]] The iteratees to sort by. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 34 } * ]; * * _.sortBy(users, function(o) { return o.user; }); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] * * _.sortBy(users, ['user', 'age']); * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]] * * _.sortBy(users, 'user', function(o) { * return Math.floor(o.age / 10); * }); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] */ var sortBy = rest(function(collection, iteratees) { if (collection == null) { return []; } var length = iteratees.length; if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { iteratees = []; } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { iteratees = [iteratees[0]]; } iteratees = (iteratees.length == 1 && isArray(iteratees[0])) ? iteratees[0] : baseFlatten(iteratees, 1, isFlattenableIteratee); return baseOrderBy(collection, iteratees, []); }); /*------------------------------------------------------------------------*/ /** * Gets the timestamp of the number of milliseconds that have elapsed since * the Unix epoch (1 January 1970 00:00:00 UTC). * * @static * @memberOf _ * @since 2.4.0 * @type {Function} * @category Date * @returns {number} Returns the timestamp. * @example * * _.defer(function(stamp) { * console.log(_.now() - stamp); * }, _.now()); * // => Logs the number of milliseconds it took for the deferred function to be invoked. */ var now = Date.now; /*------------------------------------------------------------------------*/ /** * The opposite of `_.before`; this method creates a function that invokes * `func` once it's called `n` or more times. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {number} n The number of calls before `func` is invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var saves = ['profile', 'settings']; * * var done = _.after(saves.length, function() { * console.log('done saving!'); * }); * * _.forEach(saves, function(type) { * asyncSave({ 'type': type, 'complete': done }); * }); * // => Logs 'done saving!' after the two async saves have completed. */ function after(n, func) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n < 1) { return func.apply(this, arguments); } }; } /** * Creates a function that invokes `func`, with up to `n` arguments, * ignoring any additional arguments. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to cap arguments for. * @param {number} [n=func.length] The arity cap. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new capped function. * @example * * _.map(['6', '8', '10'], _.ary(parseInt, 1)); * // => [6, 8, 10] */ function ary(func, n, guard) { n = guard ? undefined : n; n = (func && n == null) ? func.length : n; return createWrapper(func, ARY_FLAG, undefined, undefined, undefined, undefined, n); } /** * Creates a function that invokes `func`, with the `this` binding and arguments * of the created function, while it's called less than `n` times. Subsequent * calls to the created function return the result of the last `func` invocation. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {number} n The number of calls at which `func` is no longer invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * jQuery(element).on('click', _.before(5, addContactToList)); * // => allows adding up to 4 contacts to the list */ function before(n, func) { var result; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n > 0) { result = func.apply(this, arguments); } if (n <= 1) { func = undefined; } return result; }; } /** * Creates a function that invokes `func` with the `this` binding of `thisArg` * and `partials` prepended to the arguments it receives. * * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for partially applied arguments. * * **Note:** Unlike native `Function#bind` this method doesn't set the "length" * property of bound functions. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * var greet = function(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * }; * * var object = { 'user': 'fred' }; * * var bound = _.bind(greet, object, 'hi'); * bound('!'); * // => 'hi fred!' * * // Bound with placeholders. * var bound = _.bind(greet, object, _, '!'); * bound('hi'); * // => 'hi fred!' */ var bind = rest(function(func, thisArg, partials) { var bitmask = BIND_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bind)); bitmask |= PARTIAL_FLAG; } return createWrapper(func, bitmask, thisArg, partials, holders); }); /** * Creates a function that invokes the method at `object[key]` with `partials` * prepended to the arguments it receives. * * This method differs from `_.bind` by allowing bound functions to reference * methods that may be redefined or don't yet exist. See * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) * for more details. * * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * @static * @memberOf _ * @since 0.10.0 * @category Function * @param {Object} object The object to invoke the method on. * @param {string} key The key of the method. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * var object = { * 'user': 'fred', * 'greet': function(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * }; * * var bound = _.bindKey(object, 'greet', 'hi'); * bound('!'); * // => 'hi fred!' * * object.greet = function(greeting, punctuation) { * return greeting + 'ya ' + this.user + punctuation; * }; * * bound('!'); * // => 'hiya fred!' * * // Bound with placeholders. * var bound = _.bindKey(object, 'greet', _, '!'); * bound('hi'); * // => 'hiya fred!' */ var bindKey = rest(function(object, key, partials) { var bitmask = BIND_FLAG | BIND_KEY_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bindKey)); bitmask |= PARTIAL_FLAG; } return createWrapper(key, bitmask, object, partials, holders); }); /** * Creates a function that accepts arguments of `func` and either invokes * `func` returning its result, if at least `arity` number of arguments have * been provided, or returns a function that accepts the remaining `func` * arguments, and so on. The arity of `func` may be specified if `func.length` * is not sufficient. * * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for provided arguments. * * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ * @since 2.0.0 * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curry(abc); * * curried(1)(2)(3); * // => [1, 2, 3] * * curried(1, 2)(3); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // Curried with placeholders. * curried(1)(_, 3)(2); * // => [1, 2, 3] */ function curry(func, arity, guard) { arity = guard ? undefined : arity; var result = createWrapper(func, CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); result.placeholder = curry.placeholder; return result; } /** * This method is like `_.curry` except that arguments are applied to `func` * in the manner of `_.partialRight` instead of `_.partial`. * * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for provided arguments. * * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curryRight(abc); * * curried(3)(2)(1); * // => [1, 2, 3] * * curried(2, 3)(1); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // Curried with placeholders. * curried(3)(1, _)(2); * // => [1, 2, 3] */ function curryRight(func, arity, guard) { arity = guard ? undefined : arity; var result = createWrapper(func, CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); result.placeholder = curryRight.placeholder; return result; } /** * Creates a debounced function that delays invoking `func` until after `wait` * milliseconds have elapsed since the last time the debounced function was * invoked. The debounced function comes with a `cancel` method to cancel * delayed `func` invocations and a `flush` method to immediately invoke them. * Provide an options object to indicate whether `func` should be invoked on * the leading and/or trailing edge of the `wait` timeout. The `func` is invoked * with the last arguments provided to the debounced function. Subsequent calls * to the debounced function return the result of the last `func` invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked * on the trailing edge of the timeout only if the debounced function is * invoked more than once during the `wait` timeout. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.debounce` and `_.throttle`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to debounce. * @param {number} [wait=0] The number of milliseconds to delay. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=false] * Specify invoking on the leading edge of the timeout. * @param {number} [options.maxWait] * The maximum time `func` is allowed to be delayed before it's invoked. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new debounced function. * @example * * // Avoid costly calculations while the window size is in flux. * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); * * // Invoke `sendMail` when clicked, debouncing subsequent calls. * jQuery(element).on('click', _.debounce(sendMail, 300, { * 'leading': true, * 'trailing': false * })); * * // Ensure `batchLog` is invoked once after 1 second of debounced calls. * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); * var source = new EventSource('/stream'); * jQuery(source).on('message', debounced); * * // Cancel the trailing debounced invocation. * jQuery(window).on('popstate', debounced.cancel); */ function debounce(func, wait, options) { var lastArgs, lastThis, maxWait, result, timerId, lastCallTime = 0, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } wait = toNumber(wait) || 0; if (isObject(options)) { leading = !!options.leading; maxing = 'maxWait' in options; maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; trailing = 'trailing' in options ? !!options.trailing : trailing; } function invokeFunc(time) { var args = lastArgs, thisArg = lastThis; lastArgs = lastThis = undefined; lastInvokeTime = time; result = func.apply(thisArg, args); return result; } function leadingEdge(time) { // Reset any `maxWait` timer. lastInvokeTime = time; // Start the timer for the trailing edge. timerId = setTimeout(timerExpired, wait); // Invoke the leading edge. return leading ? invokeFunc(time) : result; } function remainingWait(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, result = wait - timeSinceLastCall; return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result; } function shouldInvoke(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime; // Either this is the first call, activity has stopped and we're at the // trailing edge, the system time has gone backwards and we're treating // it as the trailing edge, or we've hit the `maxWait` limit. return (!lastCallTime || (timeSinceLastCall >= wait) || (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); } function timerExpired() { var time = now(); if (shouldInvoke(time)) { return trailingEdge(time); } // Restart the timer. timerId = setTimeout(timerExpired, remainingWait(time)); } function trailingEdge(time) { clearTimeout(timerId); timerId = undefined; // Only invoke if we have `lastArgs` which means `func` has been // debounced at least once. if (trailing && lastArgs) { return invokeFunc(time); } lastArgs = lastThis = undefined; return result; } function cancel() { if (timerId !== undefined) { clearTimeout(timerId); } lastCallTime = lastInvokeTime = 0; lastArgs = lastThis = timerId = undefined; } function flush() { return timerId === undefined ? result : trailingEdge(now()); } function debounced() { var time = now(), isInvoking = shouldInvoke(time); lastArgs = arguments; lastThis = this; lastCallTime = time; if (isInvoking) { if (timerId === undefined) { return leadingEdge(lastCallTime); } if (maxing) { // Handle invocations in a tight loop. clearTimeout(timerId); timerId = setTimeout(timerExpired, wait); return invokeFunc(lastCallTime); } } if (timerId === undefined) { timerId = setTimeout(timerExpired, wait); } return result; } debounced.cancel = cancel; debounced.flush = flush; return debounced; } /** * Defers invoking the `func` until the current call stack has cleared. Any * additional arguments are provided to `func` when it's invoked. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to defer. * @param {...*} [args] The arguments to invoke `func` with. * @returns {number} Returns the timer id. * @example * * _.defer(function(text) { * console.log(text); * }, 'deferred'); * // => Logs 'deferred' after one or more milliseconds. */ var defer = rest(function(func, args) { return baseDelay(func, 1, args); }); /** * Invokes `func` after `wait` milliseconds. Any additional arguments are * provided to `func` when it's invoked. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {...*} [args] The arguments to invoke `func` with. * @returns {number} Returns the timer id. * @example * * _.delay(function(text) { * console.log(text); * }, 1000, 'later'); * // => Logs 'later' after one second. */ var delay = rest(function(func, wait, args) { return baseDelay(func, toNumber(wait) || 0, args); }); /** * Creates a function that invokes `func` with arguments reversed. * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to flip arguments for. * @returns {Function} Returns the new flipped function. * @example * * var flipped = _.flip(function() { * return _.toArray(arguments); * }); * * flipped('a', 'b', 'c', 'd'); * // => ['d', 'c', 'b', 'a'] */ function flip(func) { return createWrapper(func, FLIP_FLAG); } /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-map-prototype-object) * method interface of `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result); return result; }; memoized.cache = new (memoize.Cache || MapCache); return memoized; } // Assign cache to `_.memoize`. memoize.Cache = MapCache; /** * Creates a function that negates the result of the predicate `func`. The * `func` predicate is invoked with the `this` binding and arguments of the * created function. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} predicate The predicate to negate. * @returns {Function} Returns the new negated function. * @example * * function isEven(n) { * return n % 2 == 0; * } * * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); * // => [1, 3, 5] */ function negate(predicate) { if (typeof predicate != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return function() { return !predicate.apply(this, arguments); }; } /** * Creates a function that is restricted to invoking `func` once. Repeat calls * to the function return the value of the first invocation. The `func` is * invoked with the `this` binding and arguments of the created function. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var initialize = _.once(createApplication); * initialize(); * initialize(); * // `initialize` invokes `createApplication` once */ function once(func) { return before(2, func); } /** * Creates a function that invokes `func` with arguments transformed by * corresponding `transforms`. * * @static * @since 4.0.0 * @memberOf _ * @category Function * @param {Function} func The function to wrap. * @param {...(Array|Array[]|Function|Function[]|Object|Object[]|string|string[])} * [transforms[_.identity]] The functions to transform. * @returns {Function} Returns the new function. * @example * * function doubled(n) { * return n * 2; * } * * function square(n) { * return n * n; * } * * var func = _.overArgs(function(x, y) { * return [x, y]; * }, square, doubled); * * func(9, 3); * // => [81, 6] * * func(10, 5); * // => [100, 10] */ var overArgs = rest(function(func, transforms) { transforms = (transforms.length == 1 && isArray(transforms[0])) ? arrayMap(transforms[0], baseUnary(getIteratee())) : arrayMap(baseFlatten(transforms, 1, isFlattenableIteratee), baseUnary(getIteratee())); var funcsLength = transforms.length; return rest(function(args) { var index = -1, length = nativeMin(args.length, funcsLength); while (++index < length) { args[index] = transforms[index].call(this, args[index]); } return apply(func, this, args); }); }); /** * Creates a function that invokes `func` with `partials` prepended to the * arguments it receives. This method is like `_.bind` except it does **not** * alter the `this` binding. * * The `_.partial.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 0.2.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * var greet = function(greeting, name) { * return greeting + ' ' + name; * }; * * var sayHelloTo = _.partial(greet, 'hello'); * sayHelloTo('fred'); * // => 'hello fred' * * // Partially applied with placeholders. * var greetFred = _.partial(greet, _, 'fred'); * greetFred('hi'); * // => 'hi fred' */ var partial = rest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partial)); return createWrapper(func, PARTIAL_FLAG, undefined, partials, holders); }); /** * This method is like `_.partial` except that partially applied arguments * are appended to the arguments it receives. * * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 1.0.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * var greet = function(greeting, name) { * return greeting + ' ' + name; * }; * * var greetFred = _.partialRight(greet, 'fred'); * greetFred('hi'); * // => 'hi fred' * * // Partially applied with placeholders. * var sayHelloTo = _.partialRight(greet, 'hello', _); * sayHelloTo('fred'); * // => 'hello fred' */ var partialRight = rest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partialRight)); return createWrapper(func, PARTIAL_RIGHT_FLAG, undefined, partials, holders); }); /** * Creates a function that invokes `func` with arguments arranged according * to the specified `indexes` where the argument value at the first index is * provided as the first argument, the argument value at the second index is * provided as the second argument, and so on. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to rearrange arguments for. * @param {...(number|number[])} indexes The arranged argument indexes. * @returns {Function} Returns the new function. * @example * * var rearged = _.rearg(function(a, b, c) { * return [a, b, c]; * }, 2, 0, 1); * * rearged('b', 'c', 'a') * // => ['a', 'b', 'c'] */ var rearg = rest(function(func, indexes) { return createWrapper(func, REARG_FLAG, undefined, undefined, undefined, baseFlatten(indexes, 1)); }); /** * Creates a function that invokes `func` with the `this` binding of the * created function and arguments from `start` and beyond provided as * an array. * * **Note:** This method is based on the * [rest parameter](https://mdn.io/rest_parameters). * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. * @example * * var say = _.rest(function(what, names) { * return what + ' ' + _.initial(names).join(', ') + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); * }); * * say('hello', 'fred', 'barney', 'pebbles'); * // => 'hello fred, barney, & pebbles' */ function rest(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = nativeMax(start === undefined ? (func.length - 1) : toInteger(start), 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } switch (start) { case 0: return func.call(this, array); case 1: return func.call(this, args[0], array); case 2: return func.call(this, args[0], args[1], array); } var otherArgs = Array(start + 1); index = -1; while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = array; return apply(func, this, otherArgs); }; } /** * Creates a function that invokes `func` with the `this` binding of the * create function and an array of arguments much like * [`Function#apply`](http://www.ecma-international.org/ecma-262/6.0/#sec-function.prototype.apply). * * **Note:** This method is based on the * [spread operator](https://mdn.io/spread_operator). * * @static * @memberOf _ * @since 3.2.0 * @category Function * @param {Function} func The function to spread arguments over. * @param {number} [start=0] The start position of the spread. * @returns {Function} Returns the new function. * @example * * var say = _.spread(function(who, what) { * return who + ' says ' + what; * }); * * say(['fred', 'hello']); * // => 'fred says hello' * * var numbers = Promise.all([ * Promise.resolve(40), * Promise.resolve(36) * ]); * * numbers.then(_.spread(function(x, y) { * return x + y; * })); * // => a Promise of 76 */ function spread(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = start === undefined ? 0 : nativeMax(toInteger(start), 0); return rest(function(args) { var array = args[start], otherArgs = castSlice(args, 0, start); if (array) { arrayPush(otherArgs, array); } return apply(func, this, otherArgs); }); } /** * Creates a throttled function that only invokes `func` at most once per * every `wait` milliseconds. The throttled function comes with a `cancel` * method to cancel delayed `func` invocations and a `flush` method to * immediately invoke them. Provide an options object to indicate whether * `func` should be invoked on the leading and/or trailing edge of the `wait` * timeout. The `func` is invoked with the last arguments provided to the * throttled function. Subsequent calls to the throttled function return the * result of the last `func` invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the throttled function * is invoked more than once during the `wait` timeout. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.throttle` and `_.debounce`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to throttle. * @param {number} [wait=0] The number of milliseconds to throttle invocations to. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=true] * Specify invoking on the leading edge of the timeout. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new throttled function. * @example * * // Avoid excessively updating the position while scrolling. * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); * * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); * jQuery(element).on('click', throttled); * * // Cancel the trailing throttled invocation. * jQuery(window).on('popstate', throttled.cancel); */ function throttle(func, wait, options) { var leading = true, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (isObject(options)) { leading = 'leading' in options ? !!options.leading : leading; trailing = 'trailing' in options ? !!options.trailing : trailing; } return debounce(func, wait, { 'leading': leading, 'maxWait': wait, 'trailing': trailing }); } /** * Creates a function that accepts up to one argument, ignoring any * additional arguments. * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. * @example * * _.map(['6', '8', '10'], _.unary(parseInt)); * // => [6, 8, 10] */ function unary(func) { return ary(func, 1); } /** * Creates a function that provides `value` to the wrapper function as its * first argument. Any additional arguments provided to the function are * appended to those provided to the wrapper function. The wrapper is invoked * with the `this` binding of the created function. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {*} value The value to wrap. * @param {Function} [wrapper=identity] The wrapper function. * @returns {Function} Returns the new function. * @example * * var p = _.wrap(_.escape, function(func, text) { * return '<p>' + func(text) + '</p>'; * }); * * p('fred, barney, & pebbles'); * // => '<p>fred, barney, &amp; pebbles</p>' */ function wrap(value, wrapper) { wrapper = wrapper == null ? identity : wrapper; return partial(wrapper, value); } /*------------------------------------------------------------------------*/ /** * Casts `value` as an array if it's not one. * * @static * @memberOf _ * @since 4.4.0 * @category Lang * @param {*} value The value to inspect. * @returns {Array} Returns the cast array. * @example * * _.castArray(1); * // => [1] * * _.castArray({ 'a': 1 }); * // => [{ 'a': 1 }] * * _.castArray('abc'); * // => ['abc'] * * _.castArray(null); * // => [null] * * _.castArray(undefined); * // => [undefined] * * _.castArray(); * // => [] * * var array = [1, 2, 3]; * console.log(_.castArray(array) === array); * // => true */ function castArray() { if (!arguments.length) { return []; } var value = arguments[0]; return isArray(value) ? value : [value]; } /** * Creates a shallow clone of `value`. * * **Note:** This method is loosely based on the * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) * and supports cloning arrays, array buffers, booleans, date objects, maps, * numbers, `Object` objects, regexes, sets, strings, symbols, and typed * arrays. The own enumerable properties of `arguments` objects are cloned * as plain objects. An empty object is returned for uncloneable values such * as error objects, functions, DOM nodes, and WeakMaps. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to clone. * @returns {*} Returns the cloned value. * @see _.cloneDeep * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var shallow = _.clone(objects); * console.log(shallow[0] === objects[0]); * // => true */ function clone(value) { return baseClone(value, false, true); } /** * This method is like `_.clone` except that it accepts `customizer` which * is invoked to produce the cloned value. If `customizer` returns `undefined`, * cloning is handled by the method instead. The `customizer` is invoked with * up to four arguments; (value [, index|key, object, stack]). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to clone. * @param {Function} [customizer] The function to customize cloning. * @returns {*} Returns the cloned value. * @see _.cloneDeepWith * @example * * function customizer(value) { * if (_.isElement(value)) { * return value.cloneNode(false); * } * } * * var el = _.cloneWith(document.body, customizer); * * console.log(el === document.body); * // => false * console.log(el.nodeName); * // => 'BODY' * console.log(el.childNodes.length); * // => 0 */ function cloneWith(value, customizer) { return baseClone(value, false, true, customizer); } /** * This method is like `_.clone` except that it recursively clones `value`. * * @static * @memberOf _ * @since 1.0.0 * @category Lang * @param {*} value The value to recursively clone. * @returns {*} Returns the deep cloned value. * @see _.clone * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var deep = _.cloneDeep(objects); * console.log(deep[0] === objects[0]); * // => false */ function cloneDeep(value) { return baseClone(value, true, true); } /** * This method is like `_.cloneWith` except that it recursively clones `value`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to recursively clone. * @param {Function} [customizer] The function to customize cloning. * @returns {*} Returns the deep cloned value. * @see _.cloneWith * @example * * function customizer(value) { * if (_.isElement(value)) { * return value.cloneNode(true); * } * } * * var el = _.cloneDeepWith(document.body, customizer); * * console.log(el === document.body); * // => false * console.log(el.nodeName); * // => 'BODY' * console.log(el.childNodes.length); * // => 20 */ function cloneDeepWith(value, customizer) { return baseClone(value, true, true, customizer); } /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'user': 'fred' }; * var other = { 'user': 'fred' }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } /** * Checks if `value` is greater than `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than `other`, * else `false`. * @see _.lt * @example * * _.gt(3, 1); * // => true * * _.gt(3, 3); * // => false * * _.gt(1, 3); * // => false */ var gt = createRelationalOperation(baseGt); /** * Checks if `value` is greater than or equal to `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than or equal to * `other`, else `false`. * @see _.lte * @example * * _.gte(3, 1); * // => true * * _.gte(3, 3); * // => true * * _.gte(1, 3); * // => false */ var gte = createRelationalOperation(function(value, other) { return value >= other; }); /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ function isArguments(value) { // Safari 8.1 incorrectly makes `arguments.callee` enumerable in strict mode. return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); } /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @type {Function} * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, * else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; /** * Checks if `value` is classified as an `ArrayBuffer` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, * else `false`. * @example * * _.isArrayBuffer(new ArrayBuffer(2)); * // => true * * _.isArrayBuffer(new Array(2)); * // => false */ function isArrayBuffer(value) { return isObjectLike(value) && objectToString.call(value) == arrayBufferTag; } /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(getLength(value)) && !isFunction(value); } /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } /** * Checks if `value` is classified as a boolean primitive or object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, * else `false`. * @example * * _.isBoolean(false); * // => true * * _.isBoolean(null); * // => false */ function isBoolean(value) { return value === true || value === false || (isObjectLike(value) && objectToString.call(value) == boolTag); } /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = !Buffer ? constant(false) : function(value) { return value instanceof Buffer; }; /** * Checks if `value` is classified as a `Date` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, * else `false`. * @example * * _.isDate(new Date); * // => true * * _.isDate('Mon April 23 2012'); * // => false */ function isDate(value) { return isObjectLike(value) && objectToString.call(value) == dateTag; } /** * Checks if `value` is likely a DOM element. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a DOM element, * else `false`. * @example * * _.isElement(document.body); * // => true * * _.isElement('<body>'); * // => false */ function isElement(value) { return !!value && value.nodeType === 1 && isObjectLike(value) && !isPlainObject(value); } /** * Checks if `value` is an empty object, collection, map, or set. * * Objects are considered empty if they have no own enumerable string keyed * properties. * * Array-like values such as `arguments` objects, arrays, buffers, strings, or * jQuery-like collections are considered empty if they have a `length` of `0`. * Similarly, maps and sets are considered empty if they have a `size` of `0`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * * _.isEmpty(null); * // => true * * _.isEmpty(true); * // => true * * _.isEmpty(1); * // => true * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({ 'a': 1 }); * // => false */ function isEmpty(value) { if (isArrayLike(value) && (isArray(value) || isString(value) || isFunction(value.splice) || isArguments(value) || isBuffer(value))) { return !value.length; } if (isObjectLike(value)) { var tag = getTag(value); if (tag == mapTag || tag == setTag) { return !value.size; } } for (var key in value) { if (hasOwnProperty.call(value, key)) { return false; } } return !(nonEnumShadows && keys(value).length); } /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are **not** supported. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, * else `false`. * @example * * var object = { 'user': 'fred' }; * var other = { 'user': 'fred' }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ function isEqual(value, other) { return baseIsEqual(value, other); } /** * This method is like `_.isEqual` except that it accepts `customizer` which * is invoked to compare values. If `customizer` returns `undefined`, comparisons * are handled by the method instead. The `customizer` is invoked with up to * six arguments: (objValue, othValue [, index|key, object, other, stack]). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if the values are equivalent, * else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, othValue) { * if (isGreeting(objValue) && isGreeting(othValue)) { * return true; * } * } * * var array = ['hello', 'goodbye']; * var other = ['hi', 'goodbye']; * * _.isEqualWith(array, other, customizer); * // => true */ function isEqualWith(value, other, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; var result = customizer ? customizer(value, other) : undefined; return result === undefined ? baseIsEqual(value, other, customizer) : !!result; } /** * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, * `SyntaxError`, `TypeError`, or `URIError` object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an error object, * else `false`. * @example * * _.isError(new Error); * // => true * * _.isError(Error); * // => false */ function isError(value) { if (!isObjectLike(value)) { return false; } return (objectToString.call(value) == errorTag) || (typeof value.message == 'string' && typeof value.name == 'string'); } /** * Checks if `value` is a finite primitive number. * * **Note:** This method is based on * [`Number.isFinite`](https://mdn.io/Number/isFinite). * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a finite number, * else `false`. * @example * * _.isFinite(3); * // => true * * _.isFinite(Number.MIN_VALUE); * // => true * * _.isFinite(Infinity); * // => false * * _.isFinite('3'); * // => false */ function isFinite(value) { return typeof value == 'number' && nativeIsFinite(value); } /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, * else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 8 which returns 'object' for typed array and weak map constructors, // and PhantomJS 1.9 which returns 'function' for `NodeList` instances. var tag = isObject(value) ? objectToString.call(value) : ''; return tag == funcTag || tag == genTag; } /** * Checks if `value` is an integer. * * **Note:** This method is based on * [`Number.isInteger`](https://mdn.io/Number/isInteger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an integer, else `false`. * @example * * _.isInteger(3); * // => true * * _.isInteger(Number.MIN_VALUE); * // => false * * _.isInteger(Infinity); * // => false * * _.isInteger('3'); * // => false */ function isInteger(value) { return typeof value == 'number' && value == toInteger(value); } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, * else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/6.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return !!value && (type == 'object' || type == 'function'); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** * Checks if `value` is classified as a `Map` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, * else `false`. * @example * * _.isMap(new Map); * // => true * * _.isMap(new WeakMap); * // => false */ function isMap(value) { return isObjectLike(value) && getTag(value) == mapTag; } /** * Performs a partial deep comparison between `object` and `source` to * determine if `object` contains equivalent property values. This method is * equivalent to a `_.matches` function when `source` is partially applied. * * **Note:** This method supports comparing the same values as `_.isEqual`. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * var object = { 'user': 'fred', 'age': 40 }; * * _.isMatch(object, { 'age': 40 }); * // => true * * _.isMatch(object, { 'age': 36 }); * // => false */ function isMatch(object, source) { return object === source || baseIsMatch(object, source, getMatchData(source)); } /** * This method is like `_.isMatch` except that it accepts `customizer` which * is invoked to compare values. If `customizer` returns `undefined`, comparisons * are handled by the method instead. The `customizer` is invoked with five * arguments: (objValue, srcValue, index|key, object, source). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, srcValue) { * if (isGreeting(objValue) && isGreeting(srcValue)) { * return true; * } * } * * var object = { 'greeting': 'hello' }; * var source = { 'greeting': 'hi' }; * * _.isMatchWith(object, source, customizer); * // => true */ function isMatchWith(object, source, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseIsMatch(object, source, getMatchData(source), customizer); } /** * Checks if `value` is `NaN`. * * **Note:** This method is based on * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for * `undefined` and other non-number values. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN(value) { // An `NaN` primitive is the only value that is not equal to itself. // Perform the `toStringTag` check first to avoid errors with some // ActiveX objects in IE. return isNumber(value) && value != +value; } /** * Checks if `value` is a native function. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. * @example * * _.isNative(Array.prototype.push); * // => true * * _.isNative(_); * // => false */ function isNative(value) { if (!isObject(value)) { return false; } var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * Checks if `value` is `null`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `null`, else `false`. * @example * * _.isNull(null); * // => true * * _.isNull(void 0); * // => false */ function isNull(value) { return value === null; } /** * Checks if `value` is `null` or `undefined`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is nullish, else `false`. * @example * * _.isNil(null); * // => true * * _.isNil(void 0); * // => true * * _.isNil(NaN); * // => false */ function isNil(value) { return value == null; } /** * Checks if `value` is classified as a `Number` primitive or object. * * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are * classified as numbers, use the `_.isFinite` method. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, * else `false`. * @example * * _.isNumber(3); * // => true * * _.isNumber(Number.MIN_VALUE); * // => true * * _.isNumber(Infinity); * // => true * * _.isNumber('3'); * // => false */ function isNumber(value) { return typeof value == 'number' || (isObjectLike(value) && objectToString.call(value) == numberTag); } /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, * else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike(value) || objectToString.call(value) != objectTag || isHostObject(value)) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return (typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString); } /** * Checks if `value` is classified as a `RegExp` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, * else `false`. * @example * * _.isRegExp(/abc/); * // => true * * _.isRegExp('/abc/'); * // => false */ function isRegExp(value) { return isObject(value) && objectToString.call(value) == regexpTag; } /** * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 * double precision number which isn't the result of a rounded unsafe integer. * * **Note:** This method is based on * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a safe integer, * else `false`. * @example * * _.isSafeInteger(3); * // => true * * _.isSafeInteger(Number.MIN_VALUE); * // => false * * _.isSafeInteger(Infinity); * // => false * * _.isSafeInteger('3'); * // => false */ function isSafeInteger(value) { return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is classified as a `Set` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, * else `false`. * @example * * _.isSet(new Set); * // => true * * _.isSet(new WeakSet); * // => false */ function isSet(value) { return isObjectLike(value) && getTag(value) == setTag; } /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, * else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); } /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, * else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && objectToString.call(value) == symbolTag); } /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, * else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ function isTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objectToString.call(value)]; } /** * Checks if `value` is `undefined`. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true * * _.isUndefined(null); * // => false */ function isUndefined(value) { return value === undefined; } /** * Checks if `value` is classified as a `WeakMap` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, * else `false`. * @example * * _.isWeakMap(new WeakMap); * // => true * * _.isWeakMap(new Map); * // => false */ function isWeakMap(value) { return isObjectLike(value) && getTag(value) == weakMapTag; } /** * Checks if `value` is classified as a `WeakSet` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, * else `false`. * @example * * _.isWeakSet(new WeakSet); * // => true * * _.isWeakSet(new Set); * // => false */ function isWeakSet(value) { return isObjectLike(value) && objectToString.call(value) == weakSetTag; } /** * Checks if `value` is less than `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than `other`, * else `false`. * @see _.gt * @example * * _.lt(1, 3); * // => true * * _.lt(3, 3); * // => false * * _.lt(3, 1); * // => false */ var lt = createRelationalOperation(baseLt); /** * Checks if `value` is less than or equal to `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than or equal to * `other`, else `false`. * @see _.gte * @example * * _.lte(1, 3); * // => true * * _.lte(3, 3); * // => true * * _.lte(3, 1); * // => false */ var lte = createRelationalOperation(function(value, other) { return value <= other; }); /** * Converts `value` to an array. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to convert. * @returns {Array} Returns the converted array. * @example * * _.toArray({ 'a': 1, 'b': 2 }); * // => [1, 2] * * _.toArray('abc'); * // => ['a', 'b', 'c'] * * _.toArray(1); * // => [] * * _.toArray(null); * // => [] */ function toArray(value) { if (!value) { return []; } if (isArrayLike(value)) { return isString(value) ? stringToArray(value) : copyArray(value); } if (iteratorSymbol && value[iteratorSymbol]) { return iteratorToArray(value[iteratorSymbol]()); } var tag = getTag(value), func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); return func(value); } /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber(value); if (value === INFINITY || value === -INFINITY) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } /** * Converts `value` to an integer. * * **Note:** This function is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/6.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = toFinite(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } /** * Converts `value` to an integer suitable for use as the length of an * array-like object. * * **Note:** This method is based on * [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toLength(3.2); * // => 3 * * _.toLength(Number.MIN_VALUE); * // => 0 * * _.toLength(Infinity); * // => 4294967295 * * _.toLength('3.2'); * // => 3 */ function toLength(value) { return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; } /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other = isFunction(value.valueOf) ? value.valueOf() : value; value = isObject(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } /** * Converts `value` to a plain object flattening inherited enumerable string * keyed properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return copyObject(value, keysIn(value)); } /** * Converts `value` to a safe integer. A safe integer can be compared and * represented correctly. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toSafeInteger(3.2); * // => 3 * * _.toSafeInteger(Number.MIN_VALUE); * // => 0 * * _.toSafeInteger(Infinity); * // => 9007199254740991 * * _.toSafeInteger('3.2'); * // => 3 */ function toSafeInteger(value) { return baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); } /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {string} Returns the string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } /*------------------------------------------------------------------------*/ /** * Assigns own enumerable string keyed properties of source objects to the * destination object. Source objects are applied from left to right. * Subsequent sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object` and is loosely based on * [`Object.assign`](https://mdn.io/Object/assign). * * @static * @memberOf _ * @since 0.10.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.assignIn * @example * * function Foo() { * this.c = 3; * } * * function Bar() { * this.e = 5; * } * * Foo.prototype.d = 4; * Bar.prototype.f = 6; * * _.assign({ 'a': 1 }, new Foo, new Bar); * // => { 'a': 1, 'c': 3, 'e': 5 } */ var assign = createAssigner(function(object, source) { if (nonEnumShadows || isPrototype(source) || isArrayLike(source)) { copyObject(source, keys(source), object); return; } for (var key in source) { if (hasOwnProperty.call(source, key)) { assignValue(object, key, source[key]); } } }); /** * This method is like `_.assign` except that it iterates over own and * inherited source properties. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extend * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.assign * @example * * function Foo() { * this.b = 2; * } * * function Bar() { * this.d = 4; * } * * Foo.prototype.c = 3; * Bar.prototype.e = 5; * * _.assignIn({ 'a': 1 }, new Foo, new Bar); * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5 } */ var assignIn = createAssigner(function(object, source) { if (nonEnumShadows || isPrototype(source) || isArrayLike(source)) { copyObject(source, keysIn(source), object); return; } for (var key in source) { assignValue(object, key, source[key]); } }); /** * This method is like `_.assignIn` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extendWith * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignInWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keysIn(source), object, customizer); }); /** * This method is like `_.assign` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignInWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keys(source), object, customizer); }); /** * Creates an array of values corresponding to `paths` of `object`. * * @static * @memberOf _ * @since 1.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {...(string|string[])} [paths] The property paths of elements to pick. * @returns {Array} Returns the picked values. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; * * _.at(object, ['a[0].b.c', 'a[1]']); * // => [3, 4] * * _.at(['a', 'b', 'c'], 0, 2); * // => ['a', 'c'] */ var at = rest(function(object, paths) { return baseAt(object, baseFlatten(paths, 1)); }); /** * Creates an object that inherits from the `prototype` object. If a * `properties` object is given, its own enumerable string keyed properties * are assigned to the created object. * * @static * @memberOf _ * @since 2.3.0 * @category Object * @param {Object} prototype The object to inherit from. * @param {Object} [properties] The properties to assign to the object. * @returns {Object} Returns the new object. * @example * * function Shape() { * this.x = 0; * this.y = 0; * } * * function Circle() { * Shape.call(this); * } * * Circle.prototype = _.create(Shape.prototype, { * 'constructor': Circle * }); * * var circle = new Circle; * circle instanceof Circle; * // => true * * circle instanceof Shape; * // => true */ function create(prototype, properties) { var result = baseCreate(prototype); return properties ? baseAssign(result, properties) : result; } /** * Assigns own and inherited enumerable string keyed properties of source * objects to the destination object for all destination properties that * resolve to `undefined`. Source objects are applied from left to right. * Once a property is set, additional values of the same property are ignored. * * **Note:** This method mutates `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaultsDeep * @example * * _.defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' }); * // => { 'user': 'barney', 'age': 36 } */ var defaults = rest(function(args) { args.push(undefined, assignInDefaults); return apply(assignInWith, undefined, args); }); /** * This method is like `_.defaults` except that it recursively assigns * default properties. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 3.10.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaults * @example * * _.defaultsDeep({ 'user': { 'name': 'barney' } }, { 'user': { 'name': 'fred', 'age': 36 } }); * // => { 'user': { 'name': 'barney', 'age': 36 } } * */ var defaultsDeep = rest(function(args) { args.push(undefined, mergeDefaults); return apply(mergeWith, undefined, args); }); /** * This method is like `_.find` except that it returns the key of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Object * @param {Object} object The object to search. * @param {Array|Function|Object|string} [predicate=_.identity] * The function invoked per iteration. * @returns {string|undefined} Returns the key of the matched element, * else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findKey(users, function(o) { return o.age < 40; }); * // => 'barney' (iteration order is not guaranteed) * * // The `_.matches` iteratee shorthand. * _.findKey(users, { 'age': 1, 'active': true }); * // => 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.findKey(users, ['active', false]); * // => 'fred' * * // The `_.property` iteratee shorthand. * _.findKey(users, 'active'); * // => 'barney' */ function findKey(object, predicate) { return baseFind(object, getIteratee(predicate, 3), baseForOwn, true); } /** * This method is like `_.findKey` except that it iterates over elements of * a collection in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to search. * @param {Array|Function|Object|string} [predicate=_.identity] * The function invoked per iteration. * @returns {string|undefined} Returns the key of the matched element, * else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findLastKey(users, function(o) { return o.age < 40; }); * // => returns 'pebbles' assuming `_.findKey` returns 'barney' * * // The `_.matches` iteratee shorthand. * _.findLastKey(users, { 'age': 36, 'active': true }); * // => 'barney' * * // The `_.matchesProperty` iteratee shorthand. * _.findLastKey(users, ['active', false]); * // => 'fred' * * // The `_.property` iteratee shorthand. * _.findLastKey(users, 'active'); * // => 'pebbles' */ function findLastKey(object, predicate) { return baseFind(object, getIteratee(predicate, 3), baseForOwnRight, true); } /** * Iterates over own and inherited enumerable string keyed properties of an * object and invokes `iteratee` for each property. The iteratee is invoked * with three arguments: (value, key, object). Iteratee functions may exit * iteration early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forInRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forIn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). */ function forIn(object, iteratee) { return object == null ? object : baseFor(object, getIteratee(iteratee, 3), keysIn); } /** * This method is like `_.forIn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forIn * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forInRight(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. */ function forInRight(object, iteratee) { return object == null ? object : baseForRight(object, getIteratee(iteratee, 3), keysIn); } /** * Iterates over own enumerable string keyed properties of an object and * invokes `iteratee` for each property. The iteratee is invoked with three * arguments: (value, key, object). Iteratee functions may exit iteration * early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwnRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forOwn(object, iteratee) { return object && baseForOwn(object, getIteratee(iteratee, 3)); } /** * This method is like `_.forOwn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwn * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwnRight(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. */ function forOwnRight(object, iteratee) { return object && baseForOwnRight(object, getIteratee(iteratee, 3)); } /** * Creates an array of function property names from own enumerable properties * of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the function names. * @see _.functionsIn * @example * * function Foo() { * this.a = _.constant('a'); * this.b = _.constant('b'); * } * * Foo.prototype.c = _.constant('c'); * * _.functions(new Foo); * // => ['a', 'b'] */ function functions(object) { return object == null ? [] : baseFunctions(object, keys(object)); } /** * Creates an array of function property names from own and inherited * enumerable properties of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the function names. * @see _.functions * @example * * function Foo() { * this.a = _.constant('a'); * this.b = _.constant('b'); * } * * Foo.prototype.c = _.constant('c'); * * _.functionsIn(new Foo); * // => ['a', 'b', 'c'] */ function functionsIn(object) { return object == null ? [] : baseFunctions(object, keysIn(object)); } /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is used in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : baseGet(object, path); return result === undefined ? defaultValue : result; } /** * Checks if `path` is a direct property of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = { 'a': { 'b': 2 } }; * var other = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.has(object, 'a'); * // => true * * _.has(object, 'a.b'); * // => true * * _.has(object, ['a', 'b']); * // => true * * _.has(other, 'a'); * // => false */ function has(object, path) { return object != null && hasPath(object, path, baseHas); } /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && hasPath(object, path, baseHasIn); } /** * Creates an object composed of the inverted keys and values of `object`. * If `object` contains duplicate values, subsequent values overwrite * property assignments of previous values. * * @static * @memberOf _ * @since 0.7.0 * @category Object * @param {Object} object The object to invert. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invert(object); * // => { '1': 'c', '2': 'b' } */ var invert = createInverter(function(result, value, key) { result[value] = key; }, constant(identity)); /** * This method is like `_.invert` except that the inverted object is generated * from the results of running each element of `object` thru `iteratee`. The * corresponding inverted value of each inverted key is an array of keys * responsible for generating the inverted value. The iteratee is invoked * with one argument: (value). * * @static * @memberOf _ * @since 4.1.0 * @category Object * @param {Object} object The object to invert. * @param {Array|Function|Object|string} [iteratee=_.identity] * The iteratee invoked per element. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invertBy(object); * // => { '1': ['a', 'c'], '2': ['b'] } * * _.invertBy(object, function(value) { * return 'group' + value; * }); * // => { 'group1': ['a', 'c'], 'group2': ['b'] } */ var invertBy = createInverter(function(result, value, key) { if (hasOwnProperty.call(result, value)) { result[value].push(key); } else { result[value] = [key]; } }, getIteratee); /** * Invokes the method at `path` of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the method to invoke. * @param {...*} [args] The arguments to invoke the method with. * @returns {*} Returns the result of the invoked method. * @example * * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; * * _.invoke(object, 'a[0].b.c.slice', 1, 3); * // => [2, 3] */ var invoke = rest(baseInvoke); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { var isProto = isPrototype(object); if (!(isProto || isArrayLike(object))) { return baseKeys(object); } var indexes = indexKeys(object), skipIndexes = !!indexes, result = indexes || [], length = result.length; for (var key in object) { if (baseHas(object, key) && !(skipIndexes && (key == 'length' || isIndex(key, length))) && !(isProto && key == 'constructor')) { result.push(key); } } return result; } /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { var index = -1, isProto = isPrototype(object), props = baseKeysIn(object), propsLength = props.length, indexes = indexKeys(object), skipIndexes = !!indexes, result = indexes || [], length = result.length; while (++index < propsLength) { var key = props[index]; if (!(skipIndexes && (key == 'length' || isIndex(key, length))) && !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } /** * The opposite of `_.mapValues`; this method creates an object with the * same values as `object` and keys generated by running each own enumerable * string keyed property of `object` thru `iteratee`. The iteratee is invoked * with three arguments: (value, key, object). * * @static * @memberOf _ * @since 3.8.0 * @category Object * @param {Object} object The object to iterate over. * @param {Array|Function|Object|string} [iteratee=_.identity] * The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapValues * @example * * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { * return key + value; * }); * // => { 'a1': 1, 'b2': 2 } */ function mapKeys(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { result[iteratee(value, key, object)] = value; }); return result; } /** * Creates an object with the same keys as `object` and values generated * by running each own enumerable string keyed property of `object` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, key, object). * * @static * @memberOf _ * @since 2.4.0 * @category Object * @param {Object} object The object to iterate over. * @param {Array|Function|Object|string} [iteratee=_.identity] * The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapKeys * @example * * var users = { * 'fred': { 'user': 'fred', 'age': 40 }, * 'pebbles': { 'user': 'pebbles', 'age': 1 } * }; * * _.mapValues(users, function(o) { return o.age; }); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) * * // The `_.property` iteratee shorthand. * _.mapValues(users, 'age'); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) */ function mapValues(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { result[key] = iteratee(value, key, object); }); return result; } /** * This method is like `_.assign` except that it recursively merges own and * inherited enumerable string keyed properties of source objects into the * destination object. Source properties that resolve to `undefined` are * skipped if a destination value exists. Array and plain object properties * are merged recursively. Other objects and value types are overridden by * assignment. Source objects are applied from left to right. Subsequent * sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 0.5.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * var users = { * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }] * }; * * var ages = { * 'data': [{ 'age': 36 }, { 'age': 40 }] * }; * * _.merge(users, ages); * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] } */ var merge = createAssigner(function(object, source, srcIndex) { baseMerge(object, source, srcIndex); }); /** * This method is like `_.merge` except that it accepts `customizer` which * is invoked to produce the merged values of the destination and source * properties. If `customizer` returns `undefined`, merging is handled by the * method instead. The `customizer` is invoked with seven arguments: * (objValue, srcValue, key, object, source, stack). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} customizer The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * function customizer(objValue, srcValue) { * if (_.isArray(objValue)) { * return objValue.concat(srcValue); * } * } * * var object = { * 'fruits': ['apple'], * 'vegetables': ['beet'] * }; * * var other = { * 'fruits': ['banana'], * 'vegetables': ['carrot'] * }; * * _.mergeWith(object, other, customizer); * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] } */ var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { baseMerge(object, source, srcIndex, customizer); }); /** * The opposite of `_.pick`; this method creates an object composed of the * own and inherited enumerable string keyed properties of `object` that are * not omitted. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [props] The property identifiers to omit. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omit(object, ['a', 'c']); * // => { 'b': '2' } */ var omit = rest(function(object, props) { if (object == null) { return {}; } props = arrayMap(baseFlatten(props, 1), toKey); return basePick(object, baseDifference(getAllKeysIn(object), props)); }); /** * The opposite of `_.pickBy`; this method creates an object composed of * the own and inherited enumerable string keyed properties of `object` that * `predicate` doesn't return truthy for. The predicate is invoked with two * arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Array|Function|Object|string} [predicate=_.identity] * The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omitBy(object, _.isNumber); * // => { 'b': '2' } */ function omitBy(object, predicate) { predicate = getIteratee(predicate); return basePickBy(object, function(value, key) { return !predicate(value, key); }); } /** * Creates an object composed of the picked `object` properties. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [props] The property identifiers to pick. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pick(object, ['a', 'c']); * // => { 'a': 1, 'c': 3 } */ var pick = rest(function(object, props) { return object == null ? {} : basePick(object, arrayMap(baseFlatten(props, 1), toKey)); }); /** * Creates an object composed of the `object` properties `predicate` returns * truthy for. The predicate is invoked with two arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Array|Function|Object|string} [predicate=_.identity] * The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pickBy(object, _.isNumber); * // => { 'a': 1, 'c': 3 } */ function pickBy(object, predicate) { return object == null ? {} : basePickBy(object, getIteratee(predicate)); } /** * This method is like `_.get` except that if the resolved value is a * function it's invoked with the `this` binding of its parent object and * its result is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to resolve. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; * * _.result(object, 'a[0].b.c1'); * // => 3 * * _.result(object, 'a[0].b.c2'); * // => 4 * * _.result(object, 'a[0].b.c3', 'default'); * // => 'default' * * _.result(object, 'a[0].b.c3', _.constant('default')); * // => 'default' */ function result(object, path, defaultValue) { path = isKey(path, object) ? [path] : castPath(path); var index = -1, length = path.length; // Ensure the loop is entered when path is empty. if (!length) { object = undefined; length = 1; } while (++index < length) { var value = object == null ? undefined : object[toKey(path[index])]; if (value === undefined) { index = length; value = defaultValue; } object = isFunction(value) ? value.call(object) : value; } return object; } /** * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, * it's created. Arrays are created for missing index properties while objects * are created for all other missing properties. Use `_.setWith` to customize * `path` creation. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @returns {Object} Returns `object`. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.set(object, 'a[0].b.c', 4); * console.log(object.a[0].b.c); * // => 4 * * _.set(object, ['x', '0', 'y', 'z'], 5); * console.log(object.x[0].y.z); * // => 5 */ function set(object, path, value) { return object == null ? object : baseSet(object, path, value); } /** * This method is like `_.set` except that it accepts `customizer` which is * invoked to produce the objects of `path`. If `customizer` returns `undefined` * path creation is handled by the method instead. The `customizer` is invoked * with three arguments: (nsValue, key, nsObject). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * var object = {}; * * _.setWith(object, '[0][1]', 'a', Object); * // => { '0': { '1': 'a' } } */ function setWith(object, path, value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return object == null ? object : baseSet(object, path, value, customizer); } /** * Creates an array of own enumerable string keyed-value pairs for `object` * which can be consumed by `_.fromPairs`. If `object` is a map or set, its * entries are returned. * * @static * @memberOf _ * @since 4.0.0 * @alias entries * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the key-value pairs. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.toPairs(new Foo); * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) */ var toPairs = createToPairs(keys); /** * Creates an array of own and inherited enumerable string keyed-value pairs * for `object` which can be consumed by `_.fromPairs`. If `object` is a map * or set, its entries are returned. * * @static * @memberOf _ * @since 4.0.0 * @alias entriesIn * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the key-value pairs. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.toPairsIn(new Foo); * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) */ var toPairsIn = createToPairs(keysIn); /** * An alternative to `_.reduce`; this method transforms `object` to a new * `accumulator` object which is the result of running each of its own * enumerable string keyed properties thru `iteratee`, with each invocation * potentially mutating the `accumulator` object. The iteratee is invoked * with four arguments: (accumulator, value, key, object). Iteratee functions * may exit iteration early by explicitly returning `false`. * * @static * @memberOf _ * @since 1.3.0 * @category Object * @param {Array|Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The custom accumulator value. * @returns {*} Returns the accumulated value. * @example * * _.transform([2, 3, 4], function(result, n) { * result.push(n *= n); * return n % 2 == 0; * }, []); * // => [4, 9] * * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } */ function transform(object, iteratee, accumulator) { var isArr = isArray(object) || isTypedArray(object); iteratee = getIteratee(iteratee, 4); if (accumulator == null) { if (isArr || isObject(object)) { var Ctor = object.constructor; if (isArr) { accumulator = isArray(object) ? new Ctor : []; } else { accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; } } else { accumulator = {}; } } (isArr ? arrayEach : baseForOwn)(object, function(value, index, object) { return iteratee(accumulator, value, index, object); }); return accumulator; } /** * Removes the property at `path` of `object`. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. * @example * * var object = { 'a': [{ 'b': { 'c': 7 } }] }; * _.unset(object, 'a[0].b.c'); * // => true * * console.log(object); * // => { 'a': [{ 'b': {} }] }; * * _.unset(object, ['a', '0', 'b', 'c']); * // => true * * console.log(object); * // => { 'a': [{ 'b': {} }] }; */ function unset(object, path) { return object == null ? true : baseUnset(object, path); } /** * This method is like `_.set` except that accepts `updater` to produce the * value to set. Use `_.updateWith` to customize `path` creation. The `updater` * is invoked with one argument: (value). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.6.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {Function} updater The function to produce the updated value. * @returns {Object} Returns `object`. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.update(object, 'a[0].b.c', function(n) { return n * n; }); * console.log(object.a[0].b.c); * // => 9 * * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); * console.log(object.x[0].y.z); * // => 0 */ function update(object, path, updater) { return object == null ? object : baseUpdate(object, path, castFunction(updater)); } /** * This method is like `_.update` except that it accepts `customizer` which is * invoked to produce the objects of `path`. If `customizer` returns `undefined` * path creation is handled by the method instead. The `customizer` is invoked * with three arguments: (nsValue, key, nsObject). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.6.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {Function} updater The function to produce the updated value. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * var object = {}; * * _.updateWith(object, '[0][1]', _.constant('a'), Object); * // => { '0': { '1': 'a' } } */ function updateWith(object, path, updater, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); } /** * Creates an array of the own enumerable string keyed property values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.values(new Foo); * // => [1, 2] (iteration order is not guaranteed) * * _.values('hi'); * // => ['h', 'i'] */ function values(object) { return object ? baseValues(object, keys(object)) : []; } /** * Creates an array of the own and inherited enumerable string keyed property * values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.valuesIn(new Foo); * // => [1, 2, 3] (iteration order is not guaranteed) */ function valuesIn(object) { return object == null ? [] : baseValues(object, keysIn(object)); } /*------------------------------------------------------------------------*/ /** * Clamps `number` within the inclusive `lower` and `upper` bounds. * * @static * @memberOf _ * @since 4.0.0 * @category Number * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. * @example * * _.clamp(-10, -5, 5); * // => -5 * * _.clamp(10, -5, 5); * // => 5 */ function clamp(number, lower, upper) { if (upper === undefined) { upper = lower; lower = undefined; } if (upper !== undefined) { upper = toNumber(upper); upper = upper === upper ? upper : 0; } if (lower !== undefined) { lower = toNumber(lower); lower = lower === lower ? lower : 0; } return baseClamp(toNumber(number), lower, upper); } /** * Checks if `n` is between `start` and up to, but not including, `end`. If * `end` is not specified, it's set to `start` with `start` then set to `0`. * If `start` is greater than `end` the params are swapped to support * negative ranges. * * @static * @memberOf _ * @since 3.3.0 * @category Number * @param {number} number The number to check. * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `number` is in the range, else `false`. * @see _.range, _.rangeRight * @example * * _.inRange(3, 2, 4); * // => true * * _.inRange(4, 8); * // => true * * _.inRange(4, 2); * // => false * * _.inRange(2, 2); * // => false * * _.inRange(1.2, 2); * // => true * * _.inRange(5.2, 4); * // => false * * _.inRange(-3, -2, -6); * // => true */ function inRange(number, start, end) { start = toNumber(start) || 0; if (end === undefined) { end = start; start = 0; } else { end = toNumber(end) || 0; } number = toNumber(number); return baseInRange(number, start, end); } /** * Produces a random number between the inclusive `lower` and `upper` bounds. * If only one argument is provided a number between `0` and the given number * is returned. If `floating` is `true`, or either `lower` or `upper` are * floats, a floating-point number is returned instead of an integer. * * **Note:** JavaScript follows the IEEE-754 standard for resolving * floating-point values which can produce unexpected results. * * @static * @memberOf _ * @since 0.7.0 * @category Number * @param {number} [lower=0] The lower bound. * @param {number} [upper=1] The upper bound. * @param {boolean} [floating] Specify returning a floating-point number. * @returns {number} Returns the random number. * @example * * _.random(0, 5); * // => an integer between 0 and 5 * * _.random(5); * // => also an integer between 0 and 5 * * _.random(5, true); * // => a floating-point number between 0 and 5 * * _.random(1.2, 5.2); * // => a floating-point number between 1.2 and 5.2 */ function random(lower, upper, floating) { if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { upper = floating = undefined; } if (floating === undefined) { if (typeof upper == 'boolean') { floating = upper; upper = undefined; } else if (typeof lower == 'boolean') { floating = lower; lower = undefined; } } if (lower === undefined && upper === undefined) { lower = 0; upper = 1; } else { lower = toNumber(lower) || 0; if (upper === undefined) { upper = lower; lower = 0; } else { upper = toNumber(upper) || 0; } } if (lower > upper) { var temp = lower; lower = upper; upper = temp; } if (floating || lower % 1 || upper % 1) { var rand = nativeRandom(); return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); } return baseRandom(lower, upper); } /*------------------------------------------------------------------------*/ /** * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the camel cased string. * @example * * _.camelCase('Foo Bar'); * // => 'fooBar' * * _.camelCase('--foo-bar--'); * // => 'fooBar' * * _.camelCase('__FOO_BAR__'); * // => 'fooBar' */ var camelCase = createCompounder(function(result, word, index) { word = word.toLowerCase(); return result + (index ? capitalize(word) : word); }); /** * Converts the first character of `string` to upper case and the remaining * to lower case. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to capitalize. * @returns {string} Returns the capitalized string. * @example * * _.capitalize('FRED'); * // => 'Fred' */ function capitalize(string) { return upperFirst(toString(string).toLowerCase()); } /** * Deburrs `string` by converting * [latin-1 supplementary letters](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) * to basic latin letters and removing * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to deburr. * @returns {string} Returns the deburred string. * @example * * _.deburr('déjà vu'); * // => 'deja vu' */ function deburr(string) { string = toString(string); return string && string.replace(reLatin1, deburrLetter).replace(reComboMark, ''); } /** * Checks if `string` ends with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to search. * @param {string} [target] The string to search for. * @param {number} [position=string.length] The position to search from. * @returns {boolean} Returns `true` if `string` ends with `target`, * else `false`. * @example * * _.endsWith('abc', 'c'); * // => true * * _.endsWith('abc', 'b'); * // => false * * _.endsWith('abc', 'b', 2); * // => true */ function endsWith(string, target, position) { string = toString(string); target = baseToString(target); var length = string.length; position = position === undefined ? length : baseClamp(toInteger(position), 0, length); position -= target.length; return position >= 0 && string.indexOf(target, position) == position; } /** * Converts the characters "&", "<", ">", '"', "'", and "\`" in `string` to * their corresponding HTML entities. * * **Note:** No other characters are escaped. To escape additional * characters use a third-party library like [_he_](https://mths.be/he). * * Though the ">" character is escaped for symmetry, characters like * ">" and "/" don't need escaping in HTML and have no special meaning * unless they're part of a tag or unquoted attribute value. See * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) * (under "semi-related fun fact") for more details. * * Backticks are escaped because in IE < 9, they can break out of * attribute values or HTML comments. See [#59](https://html5sec.org/#59), * [#102](https://html5sec.org/#102), [#108](https://html5sec.org/#108), and * [#133](https://html5sec.org/#133) of the * [HTML5 Security Cheatsheet](https://html5sec.org/) for more details. * * When working with HTML you should always * [quote attribute values](http://wonko.com/post/html-escaping) to reduce * XSS vectors. * * @static * @since 0.1.0 * @memberOf _ * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escape('fred, barney, & pebbles'); * // => 'fred, barney, &amp; pebbles' */ function escape(string) { string = toString(string); return (string && reHasUnescapedHtml.test(string)) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string; } /** * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escapeRegExp('[lodash](https://lodash.com/)'); * // => '\[lodash\]\(https://lodash\.com/\)' */ function escapeRegExp(string) { string = toString(string); return (string && reHasRegExpChar.test(string)) ? string.replace(reRegExpChar, '\\$&') : string; } /** * Converts `string` to * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the kebab cased string. * @example * * _.kebabCase('Foo Bar'); * // => 'foo-bar' * * _.kebabCase('fooBar'); * // => 'foo-bar' * * _.kebabCase('__FOO_BAR__'); * // => 'foo-bar' */ var kebabCase = createCompounder(function(result, word, index) { return result + (index ? '-' : '') + word.toLowerCase(); }); /** * Converts `string`, as space separated words, to lower case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the lower cased string. * @example * * _.lowerCase('--Foo-Bar--'); * // => 'foo bar' * * _.lowerCase('fooBar'); * // => 'foo bar' * * _.lowerCase('__FOO_BAR__'); * // => 'foo bar' */ var lowerCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + word.toLowerCase(); }); /** * Converts the first character of `string` to lower case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the converted string. * @example * * _.lowerFirst('Fred'); * // => 'fred' * * _.lowerFirst('FRED'); * // => 'fRED' */ var lowerFirst = createCaseFirst('toLowerCase'); /** * Pads `string` on the left and right sides if it's shorter than `length`. * Padding characters are truncated if they can't be evenly divided by `length`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.pad('abc', 8); * // => ' abc ' * * _.pad('abc', 8, '_-'); * // => '_-abc_-_' * * _.pad('abc', 3); * // => 'abc' */ function pad(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; if (!length || strLength >= length) { return string; } var mid = (length - strLength) / 2; return ( createPadding(nativeFloor(mid), chars) + string + createPadding(nativeCeil(mid), chars) ); } /** * Pads `string` on the right side if it's shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padEnd('abc', 6); * // => 'abc ' * * _.padEnd('abc', 6, '_-'); * // => 'abc_-_' * * _.padEnd('abc', 3); * // => 'abc' */ function padEnd(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return (length && strLength < length) ? (string + createPadding(length - strLength, chars)) : string; } /** * Pads `string` on the left side if it's shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padStart('abc', 6); * // => ' abc' * * _.padStart('abc', 6, '_-'); * // => '_-_abc' * * _.padStart('abc', 3); * // => 'abc' */ function padStart(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return (length && strLength < length) ? (createPadding(length - strLength, chars) + string) : string; } /** * Converts `string` to an integer of the specified radix. If `radix` is * `undefined` or `0`, a `radix` of `10` is used unless `value` is a * hexadecimal, in which case a `radix` of `16` is used. * * **Note:** This method aligns with the * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. * * @static * @memberOf _ * @since 1.1.0 * @category String * @param {string} string The string to convert. * @param {number} [radix=10] The radix to interpret `value` by. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {number} Returns the converted integer. * @example * * _.parseInt('08'); * // => 8 * * _.map(['6', '08', '10'], _.parseInt); * // => [6, 8, 10] */ function parseInt(string, radix, guard) { // Chrome fails to trim leading <BOM> whitespace characters. // See https://bugs.chromium.org/p/v8/issues/detail?id=3109 for more details. if (guard || radix == null) { radix = 0; } else if (radix) { radix = +radix; } string = toString(string).replace(reTrim, ''); return nativeParseInt(string, radix || (reHasHexPrefix.test(string) ? 16 : 10)); } /** * Repeats the given string `n` times. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to repeat. * @param {number} [n=1] The number of times to repeat the string. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the repeated string. * @example * * _.repeat('*', 3); * // => '***' * * _.repeat('abc', 2); * // => 'abcabc' * * _.repeat('abc', 0); * // => '' */ function repeat(string, n, guard) { if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { n = 1; } else { n = toInteger(n); } return baseRepeat(toString(string), n); } /** * Replaces matches for `pattern` in `string` with `replacement`. * * **Note:** This method is based on * [`String#replace`](https://mdn.io/String/replace). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to modify. * @param {RegExp|string} pattern The pattern to replace. * @param {Function|string} replacement The match replacement. * @returns {string} Returns the modified string. * @example * * _.replace('Hi Fred', 'Fred', 'Barney'); * // => 'Hi Barney' */ function replace() { var args = arguments, string = toString(args[0]); return args.length < 3 ? string : nativeReplace.call(string, args[1], args[2]); } /** * Converts `string` to * [snake case](https://en.wikipedia.org/wiki/Snake_case). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the snake cased string. * @example * * _.snakeCase('Foo Bar'); * // => 'foo_bar' * * _.snakeCase('fooBar'); * // => 'foo_bar' * * _.snakeCase('--FOO-BAR--'); * // => 'foo_bar' */ var snakeCase = createCompounder(function(result, word, index) { return result + (index ? '_' : '') + word.toLowerCase(); }); /** * Splits `string` by `separator`. * * **Note:** This method is based on * [`String#split`](https://mdn.io/String/split). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to split. * @param {RegExp|string} separator The separator pattern to split by. * @param {number} [limit] The length to truncate results to. * @returns {Array} Returns the string segments. * @example * * _.split('a-b-c', '-', 2); * // => ['a', 'b'] */ function split(string, separator, limit) { if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { separator = limit = undefined; } limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; if (!limit) { return []; } string = toString(string); if (string && ( typeof separator == 'string' || (separator != null && !isRegExp(separator)) )) { separator = baseToString(separator); if (separator == '' && reHasComplexSymbol.test(string)) { return castSlice(stringToArray(string), 0, limit); } } return nativeSplit.call(string, separator, limit); } /** * Converts `string` to * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). * * @static * @memberOf _ * @since 3.1.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the start cased string. * @example * * _.startCase('--foo-bar--'); * // => 'Foo Bar' * * _.startCase('fooBar'); * // => 'Foo Bar' * * _.startCase('__FOO_BAR__'); * // => 'FOO BAR' */ var startCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + upperFirst(word); }); /** * Checks if `string` starts with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to search. * @param {string} [target] The string to search for. * @param {number} [position=0] The position to search from. * @returns {boolean} Returns `true` if `string` starts with `target`, * else `false`. * @example * * _.startsWith('abc', 'a'); * // => true * * _.startsWith('abc', 'b'); * // => false * * _.startsWith('abc', 'b', 1); * // => true */ function startsWith(string, target, position) { string = toString(string); position = baseClamp(toInteger(position), 0, string.length); return string.lastIndexOf(baseToString(target), position) == position; } /** * Creates a compiled template function that can interpolate data properties * in "interpolate" delimiters, HTML-escape interpolated data properties in * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data * properties may be accessed as free variables in the template. If a setting * object is given, it takes precedence over `_.templateSettings` values. * * **Note:** In the development build `_.template` utilizes * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) * for easier debugging. * * For more information on precompiling templates see * [lodash's custom builds documentation](https://lodash.com/custom-builds). * * For more information on Chrome extension sandboxes see * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). * * @static * @since 0.1.0 * @memberOf _ * @category String * @param {string} [string=''] The template string. * @param {Object} [options={}] The options object. * @param {RegExp} [options.escape=_.templateSettings.escape] * The HTML "escape" delimiter. * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] * The "evaluate" delimiter. * @param {Object} [options.imports=_.templateSettings.imports] * An object to import into the template as free variables. * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] * The "interpolate" delimiter. * @param {string} [options.sourceURL='lodash.templateSources[n]'] * The sourceURL of the compiled template. * @param {string} [options.variable='obj'] * The data object variable name. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the compiled template function. * @example * * // Use the "interpolate" delimiter to create a compiled template. * var compiled = _.template('hello <%= user %>!'); * compiled({ 'user': 'fred' }); * // => 'hello fred!' * * // Use the HTML "escape" delimiter to escape data property values. * var compiled = _.template('<b><%- value %></b>'); * compiled({ 'value': '<script>' }); * // => '<b>&lt;script&gt;</b>' * * // Use the "evaluate" delimiter to execute JavaScript and generate HTML. * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>'); * compiled({ 'users': ['fred', 'barney'] }); * // => '<li>fred</li><li>barney</li>' * * // Use the internal `print` function in "evaluate" delimiters. * var compiled = _.template('<% print("hello " + user); %>!'); * compiled({ 'user': 'barney' }); * // => 'hello barney!' * * // Use the ES delimiter as an alternative to the default "interpolate" delimiter. * var compiled = _.template('hello ${ user }!'); * compiled({ 'user': 'pebbles' }); * // => 'hello pebbles!' * * // Use backslashes to treat delimiters as plain text. * var compiled = _.template('<%= "\\<%- value %\\>" %>'); * compiled({ 'value': 'ignored' }); * // => '<%- value %>' * * // Use the `imports` option to import `jQuery` as `jq`. * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>'; * var compiled = _.template(text, { 'imports': { 'jq': jQuery } }); * compiled({ 'users': ['fred', 'barney'] }); * // => '<li>fred</li><li>barney</li>' * * // Use the `sourceURL` option to specify a custom sourceURL for the template. * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' }); * compiled(data); * // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector. * * // Use the `variable` option to ensure a with-statement isn't used in the compiled template. * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' }); * compiled.source; * // => function(data) { * // var __t, __p = ''; * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!'; * // return __p; * // } * * // Use custom template delimiters. * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g; * var compiled = _.template('hello {{ user }}!'); * compiled({ 'user': 'mustache' }); * // => 'hello mustache!' * * // Use the `source` property to inline compiled templates for meaningful * // line numbers in error messages and stack traces. * fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\ * var JST = {\ * "main": ' + _.template(mainText).source + '\ * };\ * '); */ function template(string, options, guard) { // Based on John Resig's `tmpl` implementation // (http://ejohn.org/blog/javascript-micro-templating/) // and Laura Doktorova's doT.js (https://github.com/olado/doT). var settings = lodash.templateSettings; if (guard && isIterateeCall(string, options, guard)) { options = undefined; } string = toString(string); options = assignInWith({}, options, settings, assignInDefaults); var imports = assignInWith({}, options.imports, settings.imports, assignInDefaults), importsKeys = keys(imports), importsValues = baseValues(imports, importsKeys); var isEscaping, isEvaluating, index = 0, interpolate = options.interpolate || reNoMatch, source = "__p += '"; // Compile the regexp to match each delimiter. var reDelimiters = RegExp( (options.escape || reNoMatch).source + '|' + interpolate.source + '|' + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' + (options.evaluate || reNoMatch).source + '|$' , 'g'); // Use a sourceURL for easier debugging. var sourceURL = '//# sourceURL=' + ('sourceURL' in options ? options.sourceURL : ('lodash.templateSources[' + (++templateCounter) + ']') ) + '\n'; string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { interpolateValue || (interpolateValue = esTemplateValue); // Escape characters that can't be included in string literals. source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar); // Replace delimiters with snippets. if (escapeValue) { isEscaping = true; source += "' +\n__e(" + escapeValue + ") +\n'"; } if (evaluateValue) { isEvaluating = true; source += "';\n" + evaluateValue + ";\n__p += '"; } if (interpolateValue) { source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"; } index = offset + match.length; // The JS engine embedded in Adobe products needs `match` returned in // order to produce the correct `offset` value. return match; }); source += "';\n"; // If `variable` is not specified wrap a with-statement around the generated // code to add the data object to the top of the scope chain. var variable = options.variable; if (!variable) { source = 'with (obj) {\n' + source + '\n}\n'; } // Cleanup code by stripping empty strings. source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source) .replace(reEmptyStringMiddle, '$1') .replace(reEmptyStringTrailing, '$1;'); // Frame code as the function body. source = 'function(' + (variable || 'obj') + ') {\n' + (variable ? '' : 'obj || (obj = {});\n' ) + "var __t, __p = ''" + (isEscaping ? ', __e = _.escape' : '' ) + (isEvaluating ? ', __j = Array.prototype.join;\n' + "function print() { __p += __j.call(arguments, '') }\n" : ';\n' ) + source + 'return __p\n}'; var result = attempt(function() { return Function(importsKeys, sourceURL + 'return ' + source) .apply(undefined, importsValues); }); // Provide the compiled function's source by its `toString` method or // the `source` property as a convenience for inlining compiled templates. result.source = source; if (isError(result)) { throw result; } return result; } /** * Converts `string`, as a whole, to lower case just like * [String#toLowerCase](https://mdn.io/toLowerCase). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the lower cased string. * @example * * _.toLower('--Foo-Bar--'); * // => '--foo-bar--' * * _.toLower('fooBar'); * // => 'foobar' * * _.toLower('__FOO_BAR__'); * // => '__foo_bar__' */ function toLower(value) { return toString(value).toLowerCase(); } /** * Converts `string`, as a whole, to upper case just like * [String#toUpperCase](https://mdn.io/toUpperCase). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the upper cased string. * @example * * _.toUpper('--foo-bar--'); * // => '--FOO-BAR--' * * _.toUpper('fooBar'); * // => 'FOOBAR' * * _.toUpper('__foo_bar__'); * // => '__FOO_BAR__' */ function toUpper(value) { return toString(value).toUpperCase(); } /** * Removes leading and trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trim(' abc '); * // => 'abc' * * _.trim('-_-abc-_-', '_-'); * // => 'abc' * * _.map([' foo ', ' bar '], _.trim); * // => ['foo', 'bar'] */ function trim(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.replace(reTrim, ''); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), chrSymbols = stringToArray(chars), start = charsStartIndex(strSymbols, chrSymbols), end = charsEndIndex(strSymbols, chrSymbols) + 1; return castSlice(strSymbols, start, end).join(''); } /** * Removes trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trimEnd(' abc '); * // => ' abc' * * _.trimEnd('-_-abc-_-', '_-'); * // => '-_-abc' */ function trimEnd(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.replace(reTrimEnd, ''); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), end = charsEndIndex(strSymbols, stringToArray(chars)) + 1; return castSlice(strSymbols, 0, end).join(''); } /** * Removes leading whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trimStart(' abc '); * // => 'abc ' * * _.trimStart('-_-abc-_-', '_-'); * // => 'abc-_-' */ function trimStart(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.replace(reTrimStart, ''); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), start = charsStartIndex(strSymbols, stringToArray(chars)); return castSlice(strSymbols, start).join(''); } /** * Truncates `string` if it's longer than the given maximum string length. * The last characters of the truncated string are replaced with the omission * string which defaults to "...". * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to truncate. * @param {Object} [options={}] The options object. * @param {number} [options.length=30] The maximum string length. * @param {string} [options.omission='...'] The string to indicate text is omitted. * @param {RegExp|string} [options.separator] The separator pattern to truncate to. * @returns {string} Returns the truncated string. * @example * * _.truncate('hi-diddly-ho there, neighborino'); * // => 'hi-diddly-ho there, neighbo...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'length': 24, * 'separator': ' ' * }); * // => 'hi-diddly-ho there,...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'length': 24, * 'separator': /,? +/ * }); * // => 'hi-diddly-ho there...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'omission': ' [...]' * }); * // => 'hi-diddly-ho there, neig [...]' */ function truncate(string, options) { var length = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION; if (isObject(options)) { var separator = 'separator' in options ? options.separator : separator; length = 'length' in options ? toInteger(options.length) : length; omission = 'omission' in options ? baseToString(options.omission) : omission; } string = toString(string); var strLength = string.length; if (reHasComplexSymbol.test(string)) { var strSymbols = stringToArray(string); strLength = strSymbols.length; } if (length >= strLength) { return string; } var end = length - stringSize(omission); if (end < 1) { return omission; } var result = strSymbols ? castSlice(strSymbols, 0, end).join('') : string.slice(0, end); if (separator === undefined) { return result + omission; } if (strSymbols) { end += (result.length - end); } if (isRegExp(separator)) { if (string.slice(end).search(separator)) { var match, substring = result; if (!separator.global) { separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g'); } separator.lastIndex = 0; while ((match = separator.exec(substring))) { var newEnd = match.index; } result = result.slice(0, newEnd === undefined ? end : newEnd); } } else if (string.indexOf(baseToString(separator), end) != end) { var index = result.lastIndexOf(separator); if (index > -1) { result = result.slice(0, index); } } return result + omission; } /** * The inverse of `_.escape`; this method converts the HTML entities * `&amp;`, `&lt;`, `&gt;`, `&quot;`, `&#39;`, and `&#96;` in `string` to * their corresponding characters. * * **Note:** No other HTML entities are unescaped. To unescape additional * HTML entities use a third-party library like [_he_](https://mths.be/he). * * @static * @memberOf _ * @since 0.6.0 * @category String * @param {string} [string=''] The string to unescape. * @returns {string} Returns the unescaped string. * @example * * _.unescape('fred, barney, &amp; pebbles'); * // => 'fred, barney, & pebbles' */ function unescape(string) { string = toString(string); return (string && reHasEscapedHtml.test(string)) ? string.replace(reEscapedHtml, unescapeHtmlChar) : string; } /** * Converts `string`, as space separated words, to upper case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the upper cased string. * @example * * _.upperCase('--foo-bar'); * // => 'FOO BAR' * * _.upperCase('fooBar'); * // => 'FOO BAR' * * _.upperCase('__foo_bar__'); * // => 'FOO BAR' */ var upperCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + word.toUpperCase(); }); /** * Converts the first character of `string` to upper case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the converted string. * @example * * _.upperFirst('fred'); * // => 'Fred' * * _.upperFirst('FRED'); * // => 'FRED' */ var upperFirst = createCaseFirst('toUpperCase'); /** * Splits `string` into an array of its words. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {RegExp|string} [pattern] The pattern to match words. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the words of `string`. * @example * * _.words('fred, barney, & pebbles'); * // => ['fred', 'barney', 'pebbles'] * * _.words('fred, barney, & pebbles', /[^, ]+/g); * // => ['fred', 'barney', '&', 'pebbles'] */ function words(string, pattern, guard) { string = toString(string); pattern = guard ? undefined : pattern; if (pattern === undefined) { pattern = reHasComplexWord.test(string) ? reComplexWord : reBasicWord; } return string.match(pattern) || []; } /*------------------------------------------------------------------------*/ /** * Attempts to invoke `func`, returning either the result or the caught error * object. Any additional arguments are provided to `func` when it's invoked. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {Function} func The function to attempt. * @param {...*} [args] The arguments to invoke `func` with. * @returns {*} Returns the `func` result or error object. * @example * * // Avoid throwing errors for invalid selectors. * var elements = _.attempt(function(selector) { * return document.querySelectorAll(selector); * }, '>_>'); * * if (_.isError(elements)) { * elements = []; * } */ var attempt = rest(function(func, args) { try { return apply(func, undefined, args); } catch (e) { return isError(e) ? e : new Error(e); } }); /** * Binds methods of an object to the object itself, overwriting the existing * method. * * **Note:** This method doesn't set the "length" property of bound functions. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {Object} object The object to bind and assign the bound methods to. * @param {...(string|string[])} methodNames The object method names to bind. * @returns {Object} Returns `object`. * @example * * var view = { * 'label': 'docs', * 'onClick': function() { * console.log('clicked ' + this.label); * } * }; * * _.bindAll(view, 'onClick'); * jQuery(element).on('click', view.onClick); * // => Logs 'clicked docs' when clicked. */ var bindAll = rest(function(object, methodNames) { arrayEach(baseFlatten(methodNames, 1), function(key) { key = toKey(key); object[key] = bind(object[key], object); }); return object; }); /** * Creates a function that iterates over `pairs` and invokes the corresponding * function of the first predicate to return truthy. The predicate-function * pairs are invoked with the `this` binding and arguments of the created * function. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {Array} pairs The predicate-function pairs. * @returns {Function} Returns the new composite function. * @example * * var func = _.cond([ * [_.matches({ 'a': 1 }), _.constant('matches A')], * [_.conforms({ 'b': _.isNumber }), _.constant('matches B')], * [_.constant(true), _.constant('no match')] * ]); * * func({ 'a': 1, 'b': 2 }); * // => 'matches A' * * func({ 'a': 0, 'b': 1 }); * // => 'matches B' * * func({ 'a': '1', 'b': '2' }); * // => 'no match' */ function cond(pairs) { var length = pairs ? pairs.length : 0, toIteratee = getIteratee(); pairs = !length ? [] : arrayMap(pairs, function(pair) { if (typeof pair[1] != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return [toIteratee(pair[0]), pair[1]]; }); return rest(function(args) { var index = -1; while (++index < length) { var pair = pairs[index]; if (apply(pair[0], this, args)) { return apply(pair[1], this, args); } } }); } /** * Creates a function that invokes the predicate properties of `source` with * the corresponding property values of a given object, returning `true` if * all predicates return truthy, else `false`. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {Object} source The object of property predicates to conform to. * @returns {Function} Returns the new spec function. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 } * ]; * * _.filter(users, _.conforms({ 'age': _.partial(_.gt, _, 38) })); * // => [{ 'user': 'fred', 'age': 40 }] */ function conforms(source) { return baseConforms(baseClone(source, true)); } /** * Creates a function that returns `value`. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {*} value The value to return from the new function. * @returns {Function} Returns the new constant function. * @example * * var object = { 'user': 'fred' }; * var getter = _.constant(object); * * getter() === object; * // => true */ function constant(value) { return function() { return value; }; } /** * Creates a function that returns the result of invoking the given functions * with the `this` binding of the created function, where each successive * invocation is supplied the return value of the previous. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {...(Function|Function[])} [funcs] Functions to invoke. * @returns {Function} Returns the new composite function. * @see _.flowRight * @example * * function square(n) { * return n * n; * } * * var addSquare = _.flow(_.add, square); * addSquare(1, 2); * // => 9 */ var flow = createFlow(); /** * This method is like `_.flow` except that it creates a function that * invokes the given functions from right to left. * * @static * @since 3.0.0 * @memberOf _ * @category Util * @param {...(Function|Function[])} [funcs] Functions to invoke. * @returns {Function} Returns the new composite function. * @see _.flow * @example * * function square(n) { * return n * n; * } * * var addSquare = _.flowRight(square, _.add); * addSquare(1, 2); * // => 9 */ var flowRight = createFlow(true); /** * This method returns the first argument given to it. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'user': 'fred' }; * * _.identity(object) === object; * // => true */ function identity(value) { return value; } /** * Creates a function that invokes `func` with the arguments of the created * function. If `func` is a property name, the created function returns the * property value for a given element. If `func` is an array or object, the * created function returns `true` for elements that contain the equivalent * source properties, otherwise it returns `false`. * * @static * @since 4.0.0 * @memberOf _ * @category Util * @param {*} [func=_.identity] The value to convert to a callback. * @returns {Function} Returns the callback. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true })); * // => [{ 'user': 'barney', 'age': 36, 'active': true }] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, _.iteratee(['user', 'fred'])); * // => [{ 'user': 'fred', 'age': 40 }] * * // The `_.property` iteratee shorthand. * _.map(users, _.iteratee('user')); * // => ['barney', 'fred'] * * // Create custom iteratee shorthands. * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) { * return !_.isRegExp(func) ? iteratee(func) : function(string) { * return func.test(string); * }; * }); * * _.filter(['abc', 'def'], /ef/); * // => ['def'] */ function iteratee(func) { return baseIteratee(typeof func == 'function' ? func : baseClone(func, true)); } /** * Creates a function that performs a partial deep comparison between a given * object and `source`, returning `true` if the given object has equivalent * property values, else `false`. The created function is equivalent to * `_.isMatch` with a `source` partially applied. * * **Note:** This method supports comparing the same values as `_.isEqual`. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * _.filter(users, _.matches({ 'age': 40, 'active': false })); * // => [{ 'user': 'fred', 'age': 40, 'active': false }] */ function matches(source) { return baseMatches(baseClone(source, true)); } /** * Creates a function that performs a partial deep comparison between the * value at `path` of a given object to `srcValue`, returning `true` if the * object value is equivalent, else `false`. * * **Note:** This method supports comparing the same values as `_.isEqual`. * * @static * @memberOf _ * @since 3.2.0 * @category Util * @param {Array|string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. * @example * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * _.find(users, _.matchesProperty('user', 'fred')); * // => { 'user': 'fred' } */ function matchesProperty(path, srcValue) { return baseMatchesProperty(path, baseClone(srcValue, true)); } /** * Creates a function that invokes the method at `path` of a given object. * Any additional arguments are provided to the invoked method. * * @static * @memberOf _ * @since 3.7.0 * @category Util * @param {Array|string} path The path of the method to invoke. * @param {...*} [args] The arguments to invoke the method with. * @returns {Function} Returns the new invoker function. * @example * * var objects = [ * { 'a': { 'b': _.constant(2) } }, * { 'a': { 'b': _.constant(1) } } * ]; * * _.map(objects, _.method('a.b')); * // => [2, 1] * * _.map(objects, _.method(['a', 'b'])); * // => [2, 1] */ var method = rest(function(path, args) { return function(object) { return baseInvoke(object, path, args); }; }); /** * The opposite of `_.method`; this method creates a function that invokes * the method at a given path of `object`. Any additional arguments are * provided to the invoked method. * * @static * @memberOf _ * @since 3.7.0 * @category Util * @param {Object} object The object to query. * @param {...*} [args] The arguments to invoke the method with. * @returns {Function} Returns the new invoker function. * @example * * var array = _.times(3, _.constant), * object = { 'a': array, 'b': array, 'c': array }; * * _.map(['a[2]', 'c[0]'], _.methodOf(object)); * // => [2, 0] * * _.map([['a', '2'], ['c', '0']], _.methodOf(object)); * // => [2, 0] */ var methodOf = rest(function(object, args) { return function(path) { return baseInvoke(object, path, args); }; }); /** * Adds all own enumerable string keyed function properties of a source * object to the destination object. If `object` is a function, then methods * are added to its prototype as well. * * **Note:** Use `_.runInContext` to create a pristine `lodash` function to * avoid conflicts caused by modifying the original. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {Function|Object} [object=lodash] The destination object. * @param {Object} source The object of functions to add. * @param {Object} [options={}] The options object. * @param {boolean} [options.chain=true] Specify whether mixins are chainable. * @returns {Function|Object} Returns `object`. * @example * * function vowels(string) { * return _.filter(string, function(v) { * return /[aeiou]/i.test(v); * }); * } * * _.mixin({ 'vowels': vowels }); * _.vowels('fred'); * // => ['e'] * * _('fred').vowels().value(); * // => ['e'] * * _.mixin({ 'vowels': vowels }, { 'chain': false }); * _('fred').vowels(); * // => ['e'] */ function mixin(object, source, options) { var props = keys(source), methodNames = baseFunctions(source, props); if (options == null && !(isObject(source) && (methodNames.length || !props.length))) { options = source; source = object; object = this; methodNames = baseFunctions(source, keys(source)); } var chain = !(isObject(options) && 'chain' in options) || !!options.chain, isFunc = isFunction(object); arrayEach(methodNames, function(methodName) { var func = source[methodName]; object[methodName] = func; if (isFunc) { object.prototype[methodName] = function() { var chainAll = this.__chain__; if (chain || chainAll) { var result = object(this.__wrapped__), actions = result.__actions__ = copyArray(this.__actions__); actions.push({ 'func': func, 'args': arguments, 'thisArg': object }); result.__chain__ = chainAll; return result; } return func.apply(object, arrayPush([this.value()], arguments)); }; } }); return object; } /** * Reverts the `_` variable to its previous value and returns a reference to * the `lodash` function. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @returns {Function} Returns the `lodash` function. * @example * * var lodash = _.noConflict(); */ function noConflict() { if (root._ === this) { root._ = oldDash; } return this; } /** * A no-operation function that returns `undefined` regardless of the * arguments it receives. * * @static * @memberOf _ * @since 2.3.0 * @category Util * @example * * var object = { 'user': 'fred' }; * * _.noop(object) === undefined; * // => true */ function noop() { // No operation performed. } /** * Creates a function that gets the argument at `n` index. If `n` is negative, * the nth argument from the end is returned. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {number} [n=0] The index of the argument to return. * @returns {Function} Returns the new pass-thru function. * @example * * var func = _.nthArg(1); * func('a', 'b', 'c', 'd'); * // => 'b' * * var func = _.nthArg(-2); * func('a', 'b', 'c', 'd'); * // => 'c' */ function nthArg(n) { n = toInteger(n); return rest(function(args) { return baseNth(args, n); }); } /** * Creates a function that invokes `iteratees` with the arguments it receives * and returns their results. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {...(Array|Array[]|Function|Function[]|Object|Object[]|string|string[])} * [iteratees=[_.identity]] The iteratees to invoke. * @returns {Function} Returns the new function. * @example * * var func = _.over(Math.max, Math.min); * * func(1, 2, 3, 4); * // => [4, 1] */ var over = createOver(arrayMap); /** * Creates a function that checks if **all** of the `predicates` return * truthy when invoked with the arguments it receives. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {...(Array|Array[]|Function|Function[]|Object|Object[]|string|string[])} * [predicates=[_.identity]] The predicates to check. * @returns {Function} Returns the new function. * @example * * var func = _.overEvery(Boolean, isFinite); * * func('1'); * // => true * * func(null); * // => false * * func(NaN); * // => false */ var overEvery = createOver(arrayEvery); /** * Creates a function that checks if **any** of the `predicates` return * truthy when invoked with the arguments it receives. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {...(Array|Array[]|Function|Function[]|Object|Object[]|string|string[])} * [predicates=[_.identity]] The predicates to check. * @returns {Function} Returns the new function. * @example * * var func = _.overSome(Boolean, isFinite); * * func('1'); * // => true * * func(null); * // => true * * func(NaN); * // => false */ var overSome = createOver(arraySome); /** * Creates a function that returns the value at `path` of a given object. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. * @example * * var objects = [ * { 'a': { 'b': 2 } }, * { 'a': { 'b': 1 } } * ]; * * _.map(objects, _.property('a.b')); * // => [2, 1] * * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); * // => [1, 2] */ function property(path) { return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); } /** * The opposite of `_.property`; this method creates a function that returns * the value at a given path of `object`. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {Object} object The object to query. * @returns {Function} Returns the new accessor function. * @example * * var array = [0, 1, 2], * object = { 'a': array, 'b': array, 'c': array }; * * _.map(['a[2]', 'c[0]'], _.propertyOf(object)); * // => [2, 0] * * _.map([['a', '2'], ['c', '0']], _.propertyOf(object)); * // => [2, 0] */ function propertyOf(object) { return function(path) { return object == null ? undefined : baseGet(object, path); }; } /** * Creates an array of numbers (positive and/or negative) progressing from * `start` up to, but not including, `end`. A step of `-1` is used if a negative * `start` is specified without an `end` or `step`. If `end` is not specified, * it's set to `start` with `start` then set to `0`. * * **Note:** JavaScript follows the IEEE-754 standard for resolving * floating-point values which can produce unexpected results. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns the range of numbers. * @see _.inRange, _.rangeRight * @example * * _.range(4); * // => [0, 1, 2, 3] * * _.range(-4); * // => [0, -1, -2, -3] * * _.range(1, 5); * // => [1, 2, 3, 4] * * _.range(0, 20, 5); * // => [0, 5, 10, 15] * * _.range(0, -4, -1); * // => [0, -1, -2, -3] * * _.range(1, 4, 0); * // => [1, 1, 1] * * _.range(0); * // => [] */ var range = createRange(); /** * This method is like `_.range` except that it populates values in * descending order. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns the range of numbers. * @see _.inRange, _.range * @example * * _.rangeRight(4); * // => [3, 2, 1, 0] * * _.rangeRight(-4); * // => [-3, -2, -1, 0] * * _.rangeRight(1, 5); * // => [4, 3, 2, 1] * * _.rangeRight(0, 20, 5); * // => [15, 10, 5, 0] * * _.rangeRight(0, -4, -1); * // => [-3, -2, -1, 0] * * _.rangeRight(1, 4, 0); * // => [1, 1, 1] * * _.rangeRight(0); * // => [] */ var rangeRight = createRange(true); /** * Invokes the iteratee `n` times, returning an array of the results of * each invocation. The iteratee is invoked with one argument; (index). * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {number} n The number of times to invoke `iteratee`. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the array of results. * @example * * _.times(3, String); * // => ['0', '1', '2'] * * _.times(4, _.constant(true)); * // => [true, true, true, true] */ function times(n, iteratee) { n = toInteger(n); if (n < 1 || n > MAX_SAFE_INTEGER) { return []; } var index = MAX_ARRAY_LENGTH, length = nativeMin(n, MAX_ARRAY_LENGTH); iteratee = getIteratee(iteratee); n -= MAX_ARRAY_LENGTH; var result = baseTimes(length, iteratee); while (++index < n) { iteratee(index); } return result; } /** * Converts `value` to a property path array. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {*} value The value to convert. * @returns {Array} Returns the new property path array. * @example * * _.toPath('a.b.c'); * // => ['a', 'b', 'c'] * * _.toPath('a[0].b.c'); * // => ['a', '0', 'b', 'c'] * * var path = ['a', 'b', 'c'], * newPath = _.toPath(path); * * console.log(newPath); * // => ['a', 'b', 'c'] * * console.log(path === newPath); * // => false */ function toPath(value) { if (isArray(value)) { return arrayMap(value, toKey); } return isSymbol(value) ? [value] : copyArray(stringToPath(value)); } /** * Generates a unique ID. If `prefix` is given, the ID is appended to it. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {string} [prefix=''] The value to prefix the ID with. * @returns {string} Returns the unique ID. * @example * * _.uniqueId('contact_'); * // => 'contact_104' * * _.uniqueId(); * // => '105' */ function uniqueId(prefix) { var id = ++idCounter; return toString(prefix) + id; } /*------------------------------------------------------------------------*/ /** * Adds two numbers. * * @static * @memberOf _ * @since 3.4.0 * @category Math * @param {number} augend The first number in an addition. * @param {number} addend The second number in an addition. * @returns {number} Returns the total. * @example * * _.add(6, 4); * // => 10 */ var add = createMathOperation(function(augend, addend) { return augend + addend; }); /** * Computes `number` rounded up to `precision`. * * @static * @memberOf _ * @since 3.10.0 * @category Math * @param {number} number The number to round up. * @param {number} [precision=0] The precision to round up to. * @returns {number} Returns the rounded up number. * @example * * _.ceil(4.006); * // => 5 * * _.ceil(6.004, 2); * // => 6.01 * * _.ceil(6040, -2); * // => 6100 */ var ceil = createRound('ceil'); /** * Divide two numbers. * * @static * @memberOf _ * @since 4.7.0 * @category Math * @param {number} dividend The first number in a division. * @param {number} divisor The second number in a division. * @returns {number} Returns the quotient. * @example * * _.divide(6, 4); * // => 1.5 */ var divide = createMathOperation(function(dividend, divisor) { return dividend / divisor; }); /** * Computes `number` rounded down to `precision`. * * @static * @memberOf _ * @since 3.10.0 * @category Math * @param {number} number The number to round down. * @param {number} [precision=0] The precision to round down to. * @returns {number} Returns the rounded down number. * @example * * _.floor(4.006); * // => 4 * * _.floor(0.046, 2); * // => 0.04 * * _.floor(4060, -2); * // => 4000 */ var floor = createRound('floor'); /** * Computes the maximum value of `array`. If `array` is empty or falsey, * `undefined` is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Math * @param {Array} array The array to iterate over. * @returns {*} Returns the maximum value. * @example * * _.max([4, 2, 8, 6]); * // => 8 * * _.max([]); * // => undefined */ function max(array) { return (array && array.length) ? baseExtremum(array, identity, baseGt) : undefined; } /** * This method is like `_.max` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * the value is ranked. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Array|Function|Object|string} [iteratee=_.identity] * The iteratee invoked per element. * @returns {*} Returns the maximum value. * @example * * var objects = [{ 'n': 1 }, { 'n': 2 }]; * * _.maxBy(objects, function(o) { return o.n; }); * // => { 'n': 2 } * * // The `_.property` iteratee shorthand. * _.maxBy(objects, 'n'); * // => { 'n': 2 } */ function maxBy(array, iteratee) { return (array && array.length) ? baseExtremum(array, getIteratee(iteratee), baseGt) : undefined; } /** * Computes the mean of the values in `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @returns {number} Returns the mean. * @example * * _.mean([4, 2, 8, 6]); * // => 5 */ function mean(array) { return baseMean(array, identity); } /** * This method is like `_.mean` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be averaged. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.7.0 * @category Math * @param {Array} array The array to iterate over. * @param {Array|Function|Object|string} [iteratee=_.identity] * The iteratee invoked per element. * @returns {number} Returns the mean. * @example * * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; * * _.meanBy(objects, function(o) { return o.n; }); * // => 5 * * // The `_.property` iteratee shorthand. * _.meanBy(objects, 'n'); * // => 5 */ function meanBy(array, iteratee) { return baseMean(array, getIteratee(iteratee)); } /** * Computes the minimum value of `array`. If `array` is empty or falsey, * `undefined` is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Math * @param {Array} array The array to iterate over. * @returns {*} Returns the minimum value. * @example * * _.min([4, 2, 8, 6]); * // => 2 * * _.min([]); * // => undefined */ function min(array) { return (array && array.length) ? baseExtremum(array, identity, baseLt) : undefined; } /** * This method is like `_.min` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * the value is ranked. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Array|Function|Object|string} [iteratee=_.identity] * The iteratee invoked per element. * @returns {*} Returns the minimum value. * @example * * var objects = [{ 'n': 1 }, { 'n': 2 }]; * * _.minBy(objects, function(o) { return o.n; }); * // => { 'n': 1 } * * // The `_.property` iteratee shorthand. * _.minBy(objects, 'n'); * // => { 'n': 1 } */ function minBy(array, iteratee) { return (array && array.length) ? baseExtremum(array, getIteratee(iteratee), baseLt) : undefined; } /** * Multiply two numbers. * * @static * @memberOf _ * @since 4.7.0 * @category Math * @param {number} multiplier The first number in a multiplication. * @param {number} multiplicand The second number in a multiplication. * @returns {number} Returns the product. * @example * * _.multiply(6, 4); * // => 24 */ var multiply = createMathOperation(function(multiplier, multiplicand) { return multiplier * multiplicand; }); /** * Computes `number` rounded to `precision`. * * @static * @memberOf _ * @since 3.10.0 * @category Math * @param {number} number The number to round. * @param {number} [precision=0] The precision to round to. * @returns {number} Returns the rounded number. * @example * * _.round(4.006); * // => 4 * * _.round(4.006, 2); * // => 4.01 * * _.round(4060, -2); * // => 4100 */ var round = createRound('round'); /** * Subtract two numbers. * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {number} minuend The first number in a subtraction. * @param {number} subtrahend The second number in a subtraction. * @returns {number} Returns the difference. * @example * * _.subtract(6, 4); * // => 2 */ var subtract = createMathOperation(function(minuend, subtrahend) { return minuend - subtrahend; }); /** * Computes the sum of the values in `array`. * * @static * @memberOf _ * @since 3.4.0 * @category Math * @param {Array} array The array to iterate over. * @returns {number} Returns the sum. * @example * * _.sum([4, 2, 8, 6]); * // => 20 */ function sum(array) { return (array && array.length) ? baseSum(array, identity) : 0; } /** * This method is like `_.sum` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be summed. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Array|Function|Object|string} [iteratee=_.identity] * The iteratee invoked per element. * @returns {number} Returns the sum. * @example * * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; * * _.sumBy(objects, function(o) { return o.n; }); * // => 20 * * // The `_.property` iteratee shorthand. * _.sumBy(objects, 'n'); * // => 20 */ function sumBy(array, iteratee) { return (array && array.length) ? baseSum(array, getIteratee(iteratee)) : 0; } /*------------------------------------------------------------------------*/ // Add methods that return wrapped values in chain sequences. lodash.after = after; lodash.ary = ary; lodash.assign = assign; lodash.assignIn = assignIn; lodash.assignInWith = assignInWith; lodash.assignWith = assignWith; lodash.at = at; lodash.before = before; lodash.bind = bind; lodash.bindAll = bindAll; lodash.bindKey = bindKey; lodash.castArray = castArray; lodash.chain = chain; lodash.chunk = chunk; lodash.compact = compact; lodash.concat = concat; lodash.cond = cond; lodash.conforms = conforms; lodash.constant = constant; lodash.countBy = countBy; lodash.create = create; lodash.curry = curry; lodash.curryRight = curryRight; lodash.debounce = debounce; lodash.defaults = defaults; lodash.defaultsDeep = defaultsDeep; lodash.defer = defer; lodash.delay = delay; lodash.difference = difference; lodash.differenceBy = differenceBy; lodash.differenceWith = differenceWith; lodash.drop = drop; lodash.dropRight = dropRight; lodash.dropRightWhile = dropRightWhile; lodash.dropWhile = dropWhile; lodash.fill = fill; lodash.filter = filter; lodash.flatMap = flatMap; lodash.flatMapDeep = flatMapDeep; lodash.flatMapDepth = flatMapDepth; lodash.flatten = flatten; lodash.flattenDeep = flattenDeep; lodash.flattenDepth = flattenDepth; lodash.flip = flip; lodash.flow = flow; lodash.flowRight = flowRight; lodash.fromPairs = fromPairs; lodash.functions = functions; lodash.functionsIn = functionsIn; lodash.groupBy = groupBy; lodash.initial = initial; lodash.intersection = intersection; lodash.intersectionBy = intersectionBy; lodash.intersectionWith = intersectionWith; lodash.invert = invert; lodash.invertBy = invertBy; lodash.invokeMap = invokeMap; lodash.iteratee = iteratee; lodash.keyBy = keyBy; lodash.keys = keys; lodash.keysIn = keysIn; lodash.map = map; lodash.mapKeys = mapKeys; lodash.mapValues = mapValues; lodash.matches = matches; lodash.matchesProperty = matchesProperty; lodash.memoize = memoize; lodash.merge = merge; lodash.mergeWith = mergeWith; lodash.method = method; lodash.methodOf = methodOf; lodash.mixin = mixin; lodash.negate = negate; lodash.nthArg = nthArg; lodash.omit = omit; lodash.omitBy = omitBy; lodash.once = once; lodash.orderBy = orderBy; lodash.over = over; lodash.overArgs = overArgs; lodash.overEvery = overEvery; lodash.overSome = overSome; lodash.partial = partial; lodash.partialRight = partialRight; lodash.partition = partition; lodash.pick = pick; lodash.pickBy = pickBy; lodash.property = property; lodash.propertyOf = propertyOf; lodash.pull = pull; lodash.pullAll = pullAll; lodash.pullAllBy = pullAllBy; lodash.pullAllWith = pullAllWith; lodash.pullAt = pullAt; lodash.range = range; lodash.rangeRight = rangeRight; lodash.rearg = rearg; lodash.reject = reject; lodash.remove = remove; lodash.rest = rest; lodash.reverse = reverse; lodash.sampleSize = sampleSize; lodash.set = set; lodash.setWith = setWith; lodash.shuffle = shuffle; lodash.slice = slice; lodash.sortBy = sortBy; lodash.sortedUniq = sortedUniq; lodash.sortedUniqBy = sortedUniqBy; lodash.split = split; lodash.spread = spread; lodash.tail = tail; lodash.take = take; lodash.takeRight = takeRight; lodash.takeRightWhile = takeRightWhile; lodash.takeWhile = takeWhile; lodash.tap = tap; lodash.throttle = throttle; lodash.thru = thru; lodash.toArray = toArray; lodash.toPairs = toPairs; lodash.toPairsIn = toPairsIn; lodash.toPath = toPath; lodash.toPlainObject = toPlainObject; lodash.transform = transform; lodash.unary = unary; lodash.union = union; lodash.unionBy = unionBy; lodash.unionWith = unionWith; lodash.uniq = uniq; lodash.uniqBy = uniqBy; lodash.uniqWith = uniqWith; lodash.unset = unset; lodash.unzip = unzip; lodash.unzipWith = unzipWith; lodash.update = update; lodash.updateWith = updateWith; lodash.values = values; lodash.valuesIn = valuesIn; lodash.without = without; lodash.words = words; lodash.wrap = wrap; lodash.xor = xor; lodash.xorBy = xorBy; lodash.xorWith = xorWith; lodash.zip = zip; lodash.zipObject = zipObject; lodash.zipObjectDeep = zipObjectDeep; lodash.zipWith = zipWith; // Add aliases. lodash.entries = toPairs; lodash.entriesIn = toPairsIn; lodash.extend = assignIn; lodash.extendWith = assignInWith; // Add methods to `lodash.prototype`. mixin(lodash, lodash); /*------------------------------------------------------------------------*/ // Add methods that return unwrapped values in chain sequences. lodash.add = add; lodash.attempt = attempt; lodash.camelCase = camelCase; lodash.capitalize = capitalize; lodash.ceil = ceil; lodash.clamp = clamp; lodash.clone = clone; lodash.cloneDeep = cloneDeep; lodash.cloneDeepWith = cloneDeepWith; lodash.cloneWith = cloneWith; lodash.deburr = deburr; lodash.divide = divide; lodash.endsWith = endsWith; lodash.eq = eq; lodash.escape = escape; lodash.escapeRegExp = escapeRegExp; lodash.every = every; lodash.find = find; lodash.findIndex = findIndex; lodash.findKey = findKey; lodash.findLast = findLast; lodash.findLastIndex = findLastIndex; lodash.findLastKey = findLastKey; lodash.floor = floor; lodash.forEach = forEach; lodash.forEachRight = forEachRight; lodash.forIn = forIn; lodash.forInRight = forInRight; lodash.forOwn = forOwn; lodash.forOwnRight = forOwnRight; lodash.get = get; lodash.gt = gt; lodash.gte = gte; lodash.has = has; lodash.hasIn = hasIn; lodash.head = head; lodash.identity = identity; lodash.includes = includes; lodash.indexOf = indexOf; lodash.inRange = inRange; lodash.invoke = invoke; lodash.isArguments = isArguments; lodash.isArray = isArray; lodash.isArrayBuffer = isArrayBuffer; lodash.isArrayLike = isArrayLike; lodash.isArrayLikeObject = isArrayLikeObject; lodash.isBoolean = isBoolean; lodash.isBuffer = isBuffer; lodash.isDate = isDate; lodash.isElement = isElement; lodash.isEmpty = isEmpty; lodash.isEqual = isEqual; lodash.isEqualWith = isEqualWith; lodash.isError = isError; lodash.isFinite = isFinite; lodash.isFunction = isFunction; lodash.isInteger = isInteger; lodash.isLength = isLength; lodash.isMap = isMap; lodash.isMatch = isMatch; lodash.isMatchWith = isMatchWith; lodash.isNaN = isNaN; lodash.isNative = isNative; lodash.isNil = isNil; lodash.isNull = isNull; lodash.isNumber = isNumber; lodash.isObject = isObject; lodash.isObjectLike = isObjectLike; lodash.isPlainObject = isPlainObject; lodash.isRegExp = isRegExp; lodash.isSafeInteger = isSafeInteger; lodash.isSet = isSet; lodash.isString = isString; lodash.isSymbol = isSymbol; lodash.isTypedArray = isTypedArray; lodash.isUndefined = isUndefined; lodash.isWeakMap = isWeakMap; lodash.isWeakSet = isWeakSet; lodash.join = join; lodash.kebabCase = kebabCase; lodash.last = last; lodash.lastIndexOf = lastIndexOf; lodash.lowerCase = lowerCase; lodash.lowerFirst = lowerFirst; lodash.lt = lt; lodash.lte = lte; lodash.max = max; lodash.maxBy = maxBy; lodash.mean = mean; lodash.meanBy = meanBy; lodash.min = min; lodash.minBy = minBy; lodash.multiply = multiply; lodash.nth = nth; lodash.noConflict = noConflict; lodash.noop = noop; lodash.now = now; lodash.pad = pad; lodash.padEnd = padEnd; lodash.padStart = padStart; lodash.parseInt = parseInt; lodash.random = random; lodash.reduce = reduce; lodash.reduceRight = reduceRight; lodash.repeat = repeat; lodash.replace = replace; lodash.result = result; lodash.round = round; lodash.runInContext = runInContext; lodash.sample = sample; lodash.size = size; lodash.snakeCase = snakeCase; lodash.some = some; lodash.sortedIndex = sortedIndex; lodash.sortedIndexBy = sortedIndexBy; lodash.sortedIndexOf = sortedIndexOf; lodash.sortedLastIndex = sortedLastIndex; lodash.sortedLastIndexBy = sortedLastIndexBy; lodash.sortedLastIndexOf = sortedLastIndexOf; lodash.startCase = startCase; lodash.startsWith = startsWith; lodash.subtract = subtract; lodash.sum = sum; lodash.sumBy = sumBy; lodash.template = template; lodash.times = times; lodash.toFinite = toFinite; lodash.toInteger = toInteger; lodash.toLength = toLength; lodash.toLower = toLower; lodash.toNumber = toNumber; lodash.toSafeInteger = toSafeInteger; lodash.toString = toString; lodash.toUpper = toUpper; lodash.trim = trim; lodash.trimEnd = trimEnd; lodash.trimStart = trimStart; lodash.truncate = truncate; lodash.unescape = unescape; lodash.uniqueId = uniqueId; lodash.upperCase = upperCase; lodash.upperFirst = upperFirst; // Add aliases. lodash.each = forEach; lodash.eachRight = forEachRight; lodash.first = head; mixin(lodash, (function() { var source = {}; baseForOwn(lodash, function(func, methodName) { if (!hasOwnProperty.call(lodash.prototype, methodName)) { source[methodName] = func; } }); return source; }()), { 'chain': false }); /*------------------------------------------------------------------------*/ /** * The semantic version number. * * @static * @memberOf _ * @type {string} */ lodash.VERSION = VERSION; // Assign default placeholders. arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) { lodash[methodName].placeholder = lodash; }); // Add `LazyWrapper` methods for `_.drop` and `_.take` variants. arrayEach(['drop', 'take'], function(methodName, index) { LazyWrapper.prototype[methodName] = function(n) { var filtered = this.__filtered__; if (filtered && !index) { return new LazyWrapper(this); } n = n === undefined ? 1 : nativeMax(toInteger(n), 0); var result = this.clone(); if (filtered) { result.__takeCount__ = nativeMin(n, result.__takeCount__); } else { result.__views__.push({ 'size': nativeMin(n, MAX_ARRAY_LENGTH), 'type': methodName + (result.__dir__ < 0 ? 'Right' : '') }); } return result; }; LazyWrapper.prototype[methodName + 'Right'] = function(n) { return this.reverse()[methodName](n).reverse(); }; }); // Add `LazyWrapper` methods that accept an `iteratee` value. arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) { var type = index + 1, isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG; LazyWrapper.prototype[methodName] = function(iteratee) { var result = this.clone(); result.__iteratees__.push({ 'iteratee': getIteratee(iteratee, 3), 'type': type }); result.__filtered__ = result.__filtered__ || isFilter; return result; }; }); // Add `LazyWrapper` methods for `_.head` and `_.last`. arrayEach(['head', 'last'], function(methodName, index) { var takeName = 'take' + (index ? 'Right' : ''); LazyWrapper.prototype[methodName] = function() { return this[takeName](1).value()[0]; }; }); // Add `LazyWrapper` methods for `_.initial` and `_.tail`. arrayEach(['initial', 'tail'], function(methodName, index) { var dropName = 'drop' + (index ? '' : 'Right'); LazyWrapper.prototype[methodName] = function() { return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1); }; }); LazyWrapper.prototype.compact = function() { return this.filter(identity); }; LazyWrapper.prototype.find = function(predicate) { return this.filter(predicate).head(); }; LazyWrapper.prototype.findLast = function(predicate) { return this.reverse().find(predicate); }; LazyWrapper.prototype.invokeMap = rest(function(path, args) { if (typeof path == 'function') { return new LazyWrapper(this); } return this.map(function(value) { return baseInvoke(value, path, args); }); }); LazyWrapper.prototype.reject = function(predicate) { predicate = getIteratee(predicate, 3); return this.filter(function(value) { return !predicate(value); }); }; LazyWrapper.prototype.slice = function(start, end) { start = toInteger(start); var result = this; if (result.__filtered__ && (start > 0 || end < 0)) { return new LazyWrapper(result); } if (start < 0) { result = result.takeRight(-start); } else if (start) { result = result.drop(start); } if (end !== undefined) { end = toInteger(end); result = end < 0 ? result.dropRight(-end) : result.take(end - start); } return result; }; LazyWrapper.prototype.takeRightWhile = function(predicate) { return this.reverse().takeWhile(predicate).reverse(); }; LazyWrapper.prototype.toArray = function() { return this.take(MAX_ARRAY_LENGTH); }; // Add `LazyWrapper` methods to `lodash.prototype`. baseForOwn(LazyWrapper.prototype, function(func, methodName) { var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName), isTaker = /^(?:head|last)$/.test(methodName), lodashFunc = lodash[isTaker ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName], retUnwrapped = isTaker || /^find/.test(methodName); if (!lodashFunc) { return; } lodash.prototype[methodName] = function() { var value = this.__wrapped__, args = isTaker ? [1] : arguments, isLazy = value instanceof LazyWrapper, iteratee = args[0], useLazy = isLazy || isArray(value); var interceptor = function(value) { var result = lodashFunc.apply(lodash, arrayPush([value], args)); return (isTaker && chainAll) ? result[0] : result; }; if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) { // Avoid lazy use if the iteratee has a "length" value other than `1`. isLazy = useLazy = false; } var chainAll = this.__chain__, isHybrid = !!this.__actions__.length, isUnwrapped = retUnwrapped && !chainAll, onlyLazy = isLazy && !isHybrid; if (!retUnwrapped && useLazy) { value = onlyLazy ? value : new LazyWrapper(this); var result = func.apply(value, args); result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined }); return new LodashWrapper(result, chainAll); } if (isUnwrapped && onlyLazy) { return func.apply(this, args); } result = this.thru(interceptor); return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result; }; }); // Add `Array` methods to `lodash.prototype`. arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) { var func = arrayProto[methodName], chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru', retUnwrapped = /^(?:pop|shift)$/.test(methodName); lodash.prototype[methodName] = function() { var args = arguments; if (retUnwrapped && !this.__chain__) { var value = this.value(); return func.apply(isArray(value) ? value : [], args); } return this[chainName](function(value) { return func.apply(isArray(value) ? value : [], args); }); }; }); // Map minified method names to their real names. baseForOwn(LazyWrapper.prototype, function(func, methodName) { var lodashFunc = lodash[methodName]; if (lodashFunc) { var key = (lodashFunc.name + ''), names = realNames[key] || (realNames[key] = []); names.push({ 'name': methodName, 'func': lodashFunc }); } }); realNames[createHybridWrapper(undefined, BIND_KEY_FLAG).name] = [{ 'name': 'wrapper', 'func': undefined }]; // Add methods to `LazyWrapper`. LazyWrapper.prototype.clone = lazyClone; LazyWrapper.prototype.reverse = lazyReverse; LazyWrapper.prototype.value = lazyValue; // Add chain sequence methods to the `lodash` wrapper. lodash.prototype.at = wrapperAt; lodash.prototype.chain = wrapperChain; lodash.prototype.commit = wrapperCommit; lodash.prototype.next = wrapperNext; lodash.prototype.plant = wrapperPlant; lodash.prototype.reverse = wrapperReverse; lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue; if (iteratorSymbol) { lodash.prototype[iteratorSymbol] = wrapperToIterator; } return lodash; } /*--------------------------------------------------------------------------*/ // Export lodash. var _ = runInContext(); // Expose Lodash on the free variable `window` or `self` when available so it's // globally accessible, even when bundled with Browserify, Webpack, etc. This // also prevents errors in cases where Lodash is loaded by a script tag in the // presence of an AMD loader. See http://requirejs.org/docs/errors.html#mismatch // for more details. Use `_.noConflict` to remove Lodash from the global object. (freeWindow || freeSelf || {})._ = _; // Some AMD build optimizers like r.js check for condition patterns like the following: if (true) { // Define as an anonymous module so, through path mapping, it can be // referenced as the "underscore" module. !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { return _; }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } // Check for `exports` after `define` in case a build optimizer adds an `exports` object. else if (freeExports && freeModule) { // Export for Node.js. if (moduleExports) { (freeModule.exports = _)._ = _; } // Export for CommonJS support. freeExports._ = _; } else { // Export to the global object. root._ = _; } }.call(this)); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(17)(module), (function() { return this; }()))) /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/** * A higher-order-component for handling onClickOutside for React components. */ (function(root) { "use strict"; // administrative var registeredComponents = []; var handlers = []; var IGNORE_CLASS = 'ignore-react-onclickoutside'; var DEFAULT_EVENTS = ['mousedown', 'touchstart']; /** * Check whether some DOM node is our Component's node. */ var isNodeFound = function(current, componentNode, ignoreClass) { if (current === componentNode) { return true; } // SVG <use/> elements do not technically reside in the rendered DOM, so // they do not have classList directly, but they offer a link to their // corresponding element, which can have classList. This extra check is for // that case. // See: http://www.w3.org/TR/SVG11/struct.html#InterfaceSVGUseElement // Discussion: https://github.com/Pomax/react-onclickoutside/pull/17 if (current.correspondingElement) { return current.correspondingElement.classList.contains(ignoreClass); } return current.classList.contains(ignoreClass); }; /** * Generate the event handler that checks whether a clicked DOM node * is inside of, or lives outside of, our Component's node tree. */ var generateOutsideCheck = function(componentNode, eventHandler, ignoreClass, preventDefault, stopPropagation) { return function(evt) { if (preventDefault) { evt.preventDefault(); } if (stopPropagation) { evt.stopPropagation(); } var current = evt.target; var found = false; // If source=local then this event came from "somewhere" // inside and should be ignored. We could handle this with // a layered approach, too, but that requires going back to // thinking in terms of Dom node nesting, running counter // to React's "you shouldn't care about the DOM" philosophy. while(current.parentNode) { found = isNodeFound(current, componentNode, ignoreClass); if(found) return; current = current.parentNode; } // If element is in a detached DOM, consider it "not clicked // outside", as it cannot be known whether it was outside. if(current !== document) return; eventHandler(evt); } }; /** * This function generates the HOC function that you'll use * in order to impart onOutsideClick listening to an * arbitrary component. */ function setupHOC(root, React, ReactDOM) { // The actual Component-wrapping HOC: return function(Component) { var wrapComponentWithOnClickOutsideHandling = React.createClass({ statics: { /** * Access the wrapped Component's class. */ getClass: function() { if (Component.getClass) { return Component.getClass(); } return Component; } }, /** * Access the wrapped Component's instance. */ getInstance: function() { return this.refs.instance; }, // this is given meaning in componentDidMount __outsideClickHandler: function(evt) {}, /** * Add click listeners to the current document, * linked to this component's state. */ componentDidMount: function() { var instance = this.getInstance(); if(typeof instance.handleClickOutside !== "function") { throw new Error("Component lacks a handleClickOutside(event) function for processing outside click events."); } var fn = this.__outsideClickHandler = generateOutsideCheck( ReactDOM.findDOMNode(instance), instance.handleClickOutside.bind(instance), this.props.outsideClickIgnoreClass || IGNORE_CLASS, this.props.preventDefault || false, this.props.stopPropagation || false ); var pos = registeredComponents.length; registeredComponents.push(this); handlers[pos] = fn; // If there is a truthy disableOnClickOutside property for this // component, don't immediately start listening for outside events. if (!this.props.disableOnClickOutside) { this.enableOnClickOutside(); } }, /** * Track for disableOnClickOutside props changes and enable/disable click outside */ componentWillReceiveProps: function(nextProps) { if (this.props.disableOnClickOutside && !nextProps.disableOnClickOutside) { this.enableOnClickOutside(); } else if (!this.props.disableOnClickOutside && nextProps.disableOnClickOutside) { this.disableOnClickOutside(); } }, /** * Remove the document's event listeners */ componentWillUnmount: function() { this.disableOnClickOutside(); this.__outsideClickHandler = false; var pos = registeredComponents.indexOf(this); if( pos>-1) { // clean up so we don't leak memory if (handlers[pos]) { handlers.splice(pos, 1); } registeredComponents.splice(pos, 1); } }, /** * Can be called to explicitly enable event listening * for clicks and touches outside of this element. */ enableOnClickOutside: function() { var fn = this.__outsideClickHandler; if (typeof document !== "undefined") { var events = this.props.eventTypes || DEFAULT_EVENTS; if (!events.forEach) { events = [events] }; events.forEach(function (eventName) { document.addEventListener(eventName, fn); }); } }, /** * Can be called to explicitly disable event listening * for clicks and touches outside of this element. */ disableOnClickOutside: function() { var fn = this.__outsideClickHandler; if (typeof document !== "undefined") { var events = this.props.eventTypes || DEFAULT_EVENTS; if (!events.forEach) { events = [events] }; events.forEach(function (eventName) { document.removeEventListener(eventName, fn); }); } }, /** * Pass-through render */ render: function() { var passedProps = this.props; var props = { ref: 'instance' }; Object.keys(this.props).forEach(function(key) { props[key] = passedProps[key]; }); return React.createElement(Component, props); } }); // Add display name for React devtools (function bindWrappedComponentName(c, wrapper) { var componentName = c.displayName || c.name || 'Component' wrapper.displayName = 'OnClickOutside(' + componentName + ')'; }(Component, wrapComponentWithOnClickOutsideHandling)); return wrapComponentWithOnClickOutsideHandling; }; } /** * This function sets up the library in ways that * work with the various modulde loading solutions * used in JavaScript land today. */ function setupBinding(root, factory) { if (true) { // AMD. Register as an anonymous module. !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(1),__webpack_require__(4)], __WEBPACK_AMD_DEFINE_RESULT__ = function(React, ReactDom) { return factory(root, React, ReactDom); }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof exports === 'object') { // Node. Note that this does not work with strict // CommonJS, but only CommonJS-like environments // that support module.exports module.exports = factory(root, require('react'), require('react-dom')); } else { // Browser globals (root is window) root.onClickOutside = factory(root, React, ReactDOM); } } // Make it all happen setupBinding(root, setupHOC); }(this)); /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(4); var _classnames = __webpack_require__(3); var _classnames2 = _interopRequireDefault(_classnames); var _keyCode = __webpack_require__(2); var _keyCode2 = _interopRequireDefault(_keyCode); var _reactOnclickoutside = __webpack_require__(6); var _reactOnclickoutside2 = _interopRequireDefault(_reactOnclickoutside); /** * Token * * Individual token component, generally displayed within the TokenizerInput * component, but can also be rendered on its own. */ var Token = _react2['default'].createClass({ displayName: 'Token', propTypes: { /** * Handler for removing/deleting the token. If not defined, the token will * be rendered in a read-only state. */ onRemove: _react.PropTypes.func }, getInitialState: function getInitialState() { return { selected: false }; }, render: function render() { return this.props.onRemove && !this.props.disabled ? this._renderRemoveableToken() : this._renderToken(); }, _renderRemoveableToken: function _renderRemoveableToken() { return _react2['default'].createElement( 'div', { className: (0, _classnames2['default'])('token', 'token-removeable', { 'token-selected': this.state.selected }, this.props.className), onBlur: this._handleBlur, onClick: this._handleSelect, onFocus: this._handleSelect, onKeyDown: this._handleKeyDown, tabIndex: 0 }, this.props.children, _react2['default'].createElement( 'span', { className: 'close-button', onClick: this._handleRemove, role: 'button' }, '×' ) ); }, _renderToken: function _renderToken() { var _props = this.props; var className = _props.className; var disabled = _props.disabled; var href = _props.href; var classnames = (0, _classnames2['default'])('token', className); if (href) { return _react2['default'].createElement( 'a', { className: classnames, disabled: disabled, href: href }, this.props.children ); } return _react2['default'].createElement( 'div', { className: classnames, disabled: disabled }, this.props.children ); }, _handleBlur: function _handleBlur(e) { (0, _reactDom.findDOMNode)(this).blur(); this.setState({ selected: false }); }, _handleKeyDown: function _handleKeyDown(e) { switch (e.keyCode) { case _keyCode2['default'].BACKSPACE: if (this.state.selected) { // Prevent backspace keypress from triggering the browser "back" // action. e.preventDefault(); this._handleRemove(); } break; } }, /** * From `onClickOutside` mixin. */ handleClickOutside: function handleClickOutside(e) { this._handleBlur(); }, _handleRemove: function _handleRemove(e) { this.props.onRemove && this.props.onRemove(); }, _handleSelect: function _handleSelect(e) { e.stopPropagation(); this.setState({ selected: true }); } }); exports['default'] = (0, _reactOnclickoutside2['default'])(Token); module.exports = exports['default']; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _reactInputAutosize = __webpack_require__(16); var _reactInputAutosize2 = _interopRequireDefault(_reactInputAutosize); var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _TokenReact = __webpack_require__(7); var _TokenReact2 = _interopRequireDefault(_TokenReact); var _classnames = __webpack_require__(3); var _classnames2 = _interopRequireDefault(_classnames); var _reactDom = __webpack_require__(4); var _keyCode = __webpack_require__(2); /** * TokenizerInput * * Accepts multiple selections from a Typeahead component and renders them as * tokens within an input. */ var TokenizerInput = _react2['default'].createClass({ displayName: 'TokenizerInput', propTypes: { disabled: _react.PropTypes.bool, labelKey: _react.PropTypes.string, placeholder: _react.PropTypes.string, selected: _react.PropTypes.array }, getInitialState: function getInitialState() { return { isFocused: false }; }, render: function render() { var _props = this.props; var disabled = _props.disabled; var placeholder = _props.placeholder; var selected = _props.selected; var text = _props.text; return _react2['default'].createElement( 'div', { className: (0, _classnames2['default'])('bootstrap-tokenizer', 'clearfix', 'form-control', { 'focus': this.state.isFocused }), disabled: disabled, onClick: this._handleInputFocus, onFocus: this._handleInputFocus, style: { cursor: 'text', height: 'auto' }, tabIndex: -1 }, selected.map(this._renderToken), _react2['default'].createElement(_reactInputAutosize2['default'], { className: 'bootstrap-tokenizer-input', disabled: disabled, inputStyle: { backgroundColor: 'inherit', border: 0, boxShadow: 'none', cursor: 'inherit', outline: 'none', padding: 0 }, onBlur: this._handleBlur, onChange: this._handleChange, onFocus: this.props.onFocus, onKeyDown: this._handleKeydown, placeholder: selected.length ? null : placeholder, ref: 'input', type: 'text', value: text }) ); }, _renderToken: function _renderToken(option, idx) { var _props2 = this.props; var disabled = _props2.disabled; var labelKey = _props2.labelKey; var onRemove = _props2.onRemove; return _react2['default'].createElement( _TokenReact2['default'], { disabled: disabled, key: idx, onRemove: function () { return onRemove(option); } }, option[labelKey] ); }, _handleBlur: function _handleBlur(e) { this.setState({ isFocused: false }); this.props.onBlur(e); }, _handleChange: function _handleChange(e) { this.props.onChange(e.target.value); }, _handleKeydown: function _handleKeydown(e) { switch (e.keyCode) { case _keyCode.BACKSPACE: var inputNode = (0, _reactDom.findDOMNode)(this.refs.input); if (inputNode && inputNode.contains(document.activeElement) && !this.props.text) { // If the input is selected and there is no text, select the last // token when the user hits backspace. var sibling = inputNode.previousSibling; sibling && sibling.focus(); } break; } this.props.onKeyDown(e); }, _handleInputFocus: function _handleInputFocus(e) { if (this.props.disabled) { e.target.blur(); return; } // If the user clicks anywhere inside the tokenizer besides a token, // focus the input. this.refs.input.focus(); this.setState({ isFocused: true }); } }); exports['default'] = TokenizerInput; module.exports = exports['default']; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _TokenizerInputReact = __webpack_require__(8); var _TokenizerInputReact2 = _interopRequireDefault(_TokenizerInputReact); var _TypeaheadInputReact = __webpack_require__(10); var _TypeaheadInputReact2 = _interopRequireDefault(_TypeaheadInputReact); var _TypeaheadMenuReact = __webpack_require__(11); var _TypeaheadMenuReact2 = _interopRequireDefault(_TypeaheadMenuReact); var _lodash = __webpack_require__(5); var _keyCode = __webpack_require__(2); var _reactOnclickoutside = __webpack_require__(6); var _reactOnclickoutside2 = _interopRequireDefault(_reactOnclickoutside); /** * Typeahead */ var Typeahead = _react2['default'].createClass({ displayName: 'Typeahead', propTypes: { /** * Specify menu alignment. The default value is `justify`, which makes the * menu as wide as the input and truncates long values. Specifying `left` * or `right` will align the menu to that side and the width will be * determined by the length of menu item values. */ align: _react.PropTypes.oneOf(['justify', 'left', 'right']), /** * Allows the creation of new selections on the fly. Note that any new items * will be added to the list of selections, but not the list of original * options unless handled as such by `Typeahead`'s parent. */ allowNew: _react.PropTypes.bool, /** * Specify any pre-selected options. Use only if you want the component to * be uncontrolled. */ defaultSelected: _react.PropTypes.array, /** * Whether to disable the input. Will also disable selections when * `multiple={true}`. */ disabled: _react.PropTypes.bool, /** * Message to display in the menu if there are no valid results. */ emptyLabel: _react.PropTypes.string, /** * Specify which option key to use for display. By default, the selector * will use the `label` key. */ labelKey: _react.PropTypes.string, /** * Maximum height of the dropdown menu, in px. */ maxHeight: _react.PropTypes.number, /** * Number of input characters that must be entered before showing results. */ minLength: _react.PropTypes.number, /** * Whether or not multiple selections are allowed. */ multiple: _react.PropTypes.bool, /** * Provides the ability to specify a prefix before the user-entered text to * indicate that the selection will be new. No-op unless `allowNew={true}`. */ newSelectionPrefix: _react.PropTypes.string, onBlur: _react.PropTypes.func, /** * Callback for handling selected values. */ onChange: _react.PropTypes.func, /** * Callback for handling changes to the user-input text. */ onInputChange: _react.PropTypes.func, /** * Full set of options, including pre-selected options. */ options: _react.PropTypes.array.isRequired, /** * For large option sets, initially display a subset of results for improved * performance. If users scroll to the end, the last item will be a link to * display the next set of results. Value represents the number of results * to display. `0` will display all results. */ paginateResults: _react.PropTypes.number, /** * Placeholder text for the input. */ placeholder: _react.PropTypes.string, /** * Provides a hook for customized rendering of menu item contents. */ renderMenuItemChildren: _react.PropTypes.func, /** * The selected option(s) displayed in the input. Use this prop if you want * to control the component via its parent. */ selected: _react.PropTypes.array }, getDefaultProps: function getDefaultProps() { return { allowNew: false, defaultSelected: [], labelKey: 'label', onBlur: _lodash.noop, onChange: _lodash.noop, onInputChange: _lodash.noop, minLength: 0, multiple: false, selected: [] }; }, getInitialState: function getInitialState() { var defaultSelected = this.props.defaultSelected; var selected = this.props.selected.slice(); if (!(0, _lodash.isEmpty)(defaultSelected)) { selected = defaultSelected; } return { activeIndex: -1, selected: selected, showMenu: false, text: '' }; }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { var multiple = nextProps.multiple; var selected = nextProps.selected; if (!(0, _lodash.isEqual)(selected, this.props.selected)) { // If new selections are passed in via props, treat the component as a // controlled input. this.setState({ selected: selected }); } if (multiple !== this.props.multiple) { this.setState({ text: '' }); } }, render: function render() { var filteredOptions = this._getFilteredOptions(); return _react2['default'].createElement( 'div', { className: 'bootstrap-typeahead open', style: { position: 'relative' } }, this._renderInput(filteredOptions), this._renderMenu(filteredOptions) ); }, /** * Public method to allow external clearing of the input. Clears both text * and selection(s). */ clear: function clear() { var selected = []; var text = ''; this.setState(_extends({}, this.getInitialState(), { selected: selected, text: text })); this.props.onChange(selected); this.props.onInputChange(text); }, /** * Filter out options that don't match the input string or, if multiple * selections are allowed, that have already been selected. */ _getFilteredOptions: function _getFilteredOptions() { var _props = this.props; var allowNew = _props.allowNew; var labelKey = _props.labelKey; var minLength = _props.minLength; var multiple = _props.multiple; var options = _props.options; var _state = this.state; var selected = _state.selected; var text = _state.text; if (text.length < minLength) { return []; } var filteredOptions = options.filter(function (option) { var labelString = option[labelKey]; if (!labelString || typeof labelString !== 'string') { throw new Error('One or more options does not have a valid label string. Please ' + 'check the `labelKey` prop to ensure that it matches the correct ' + 'option key and provides a string for filtering and display.'); } return !(labelString.toLowerCase().indexOf(text.toLowerCase()) === -1 || multiple && (0, _lodash.find)(selected, option)); }); if (!filteredOptions.length && allowNew && !!text.trim()) { var newOption = { id: (0, _lodash.uniqueId)('new-id-'), customOption: true }; newOption[labelKey] = text; filteredOptions = [newOption]; } return filteredOptions; }, _renderInput: function _renderInput(filteredOptions) { var _this = this; var _props2 = this.props; var labelKey = _props2.labelKey; var multiple = _props2.multiple; var _state2 = this.state; var activeIndex = _state2.activeIndex; var selected = _state2.selected; var text = _state2.text; var Input = multiple ? _TokenizerInputReact2['default'] : _TypeaheadInputReact2['default']; var inputProps = (0, _lodash.pick)(this.props, ['disabled', 'placeholder']); return _react2['default'].createElement(Input, _extends({}, inputProps, { activeIndex: activeIndex, labelKey: labelKey, onAdd: this._handleAddOption, onBlur: this._handleBlur, onChange: this._handleTextChange, onFocus: this._handleFocus, onKeyDown: function (e) { return _this._handleKeydown(filteredOptions, e); }, onRemove: this._handleRemoveOption, options: filteredOptions, selected: selected.slice(), text: text })); }, _renderMenu: function _renderMenu(filteredOptions) { var _props3 = this.props; var labelKey = _props3.labelKey; var minLength = _props3.minLength; var _state3 = this.state; var activeIndex = _state3.activeIndex; var showMenu = _state3.showMenu; var text = _state3.text; if (!(showMenu && text.length >= minLength)) { return null; } var menuProps = (0, _lodash.pick)(this.props, ['align', 'emptyLabel', 'maxHeight', 'newSelectionPrefix', 'renderMenuItemChildren']); return _react2['default'].createElement(_TypeaheadMenuReact2['default'], _extends({}, menuProps, { activeIndex: activeIndex, initialResultCount: this.props.paginateResults, labelKey: labelKey, onClick: this._handleAddOption, options: filteredOptions, text: text })); }, _handleBlur: function _handleBlur(e) { // Note: Don't hide the menu here, since that interferes with other actions // like making a selection by clicking on a menu item. this.props.onBlur(e); }, _handleFocus: function _handleFocus() { this.setState({ showMenu: true }); }, _handleTextChange: function _handleTextChange(text) { var _getInitialState = this.getInitialState(); var activeIndex = _getInitialState.activeIndex; this.setState({ activeIndex: activeIndex, showMenu: true, text: text }); this.props.onInputChange(text); }, _handleKeydown: function _handleKeydown(options, e) { var activeIndex = this.state.activeIndex; switch (e.keyCode) { case _keyCode.BACKSPACE: // Don't let the browser go back. e.stopPropagation(); break; case _keyCode.UP: case _keyCode.DOWN: // Prevent page from scrolling. e.preventDefault(); // Increment or decrement index based on user keystroke. activeIndex += e.keyCode === _keyCode.UP ? -1 : 1; // If we've reached the end, go back to the beginning or vice-versa. if (activeIndex === options.length) { activeIndex = -1; } else if (activeIndex === -2) { activeIndex = options.length - 1; } this.setState({ activeIndex: activeIndex }); break; case _keyCode.ESC: case _keyCode.TAB: // Prevent things like unintentionally closing dialogs. e.stopPropagation(); this._hideDropdown(); break; case _keyCode.RETURN: if (this.state.showMenu) { var selected = options[activeIndex]; selected && this._handleAddOption(selected); } break; } }, _handleAddOption: function _handleAddOption(selectedOption) { var _props4 = this.props; var multiple = _props4.multiple; var labelKey = _props4.labelKey; var onChange = _props4.onChange; var onInputChange = _props4.onInputChange; var selected = undefined; var text = undefined; if (multiple) { // If multiple selections are allowed, add the new selection to the // existing selections. selected = this.state.selected.concat(selectedOption); text = ''; } else { // If only a single selection is allowed, replace the existing selection // with the new one. selected = [selectedOption]; text = selectedOption[labelKey]; } this.setState({ selected: selected, text: text }); this._hideDropdown(); onChange(selected); onInputChange(text); }, _handleRemoveOption: function _handleRemoveOption(removedOption) { var selected = this.state.selected.slice(); selected = selected.filter(function (option) { return !(0, _lodash.isEqual)(option, removedOption); }); this.setState({ selected: selected }); this._hideDropdown(); this.props.onChange(selected); }, /** * From `listensToClickOutside` HOC. */ handleClickOutside: function handleClickOutside(e) { this._hideDropdown(); }, _hideDropdown: function _hideDropdown() { var _getInitialState2 = this.getInitialState(); var activeIndex = _getInitialState2.activeIndex; var showMenu = _getInitialState2.showMenu; this.setState({ activeIndex: activeIndex, showMenu: showMenu }); } }); exports['default'] = (0, _reactOnclickoutside2['default'])(Typeahead); module.exports = exports['default']; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(3); var _classnames2 = _interopRequireDefault(_classnames); var _lodash = __webpack_require__(5); var _keyCode = __webpack_require__(2); /** * TypeaheadInput * * Handles a single selection from the Typeahead component. */ var TypeaheadInput = _react2['default'].createClass({ displayName: 'TypeaheadInput', propTypes: { disabled: _react.PropTypes.bool, labelKey: _react.PropTypes.string, onBlur: _react.PropTypes.func, onChange: _react.PropTypes.func, onFocus: _react.PropTypes.func, options: _react.PropTypes.array, placeholder: _react.PropTypes.string, selected: _react.PropTypes.array, text: _react.PropTypes.string }, getInitialState: function getInitialState() { return { isFocused: false }; }, componentDidUpdate: function componentDidUpdate(prevProps, prevState) { var inputText = this._getInputText(); this.refs.input.selectionStart = inputText.length; }, render: function render() { var _props = this.props; var className = _props.className; var disabled = _props.disabled; var selected = _props.selected; var inputProps = (0, _lodash.pick)(this.props, ['disabled', 'onFocus', 'placeholder']); return _react2['default'].createElement( 'div', { className: (0, _classnames2['default'])('bootstrap-typeahead-input', className), onClick: this._handleInputFocus, onFocus: this._handleInputFocus, style: { outline: 'none' }, tabIndex: -1 }, _react2['default'].createElement('input', _extends({}, inputProps, { className: (0, _classnames2['default'])('bootstrap-typeahead-input-main', 'form-control', { 'has-selection': !!selected.length }), onBlur: this._handleBlur, onChange: this._handleChange, onKeyDown: this._handleKeydown, ref: 'input', style: { backgroundColor: !disabled && 'transparent', display: 'block', position: 'relative', zIndex: 1 }, type: 'text', value: this._getInputText() })), _react2['default'].createElement('input', { className: 'bootstrap-typeahead-input-hint form-control', style: { borderColor: 'transparent', bottom: 0, boxShadow: 'none', display: 'block', position: 'absolute', top: 0, width: '100%', zIndex: 0 }, tabIndex: -1, type: 'text', value: this._getHintText() }) ); }, _getHintText: function _getHintText() { var _props2 = this.props; var activeIndex = _props2.activeIndex; var options = _props2.options; var labelKey = _props2.labelKey; var text = _props2.text; var firstOption = (0, _lodash.head)(options); var firstOptionString = firstOption && firstOption[labelKey]; // Only show the hint if: if ( // The input is focused. this.state.isFocused && // The input contains text. text && // None of the menu options are focused. activeIndex === -1 && // The input text corresponds to the beginning of the first option. firstOptionString && firstOptionString.toLowerCase().indexOf(text.toLowerCase()) === 0) { // Text matching is case-insensitive, so to display the hint correctly, // splice the input text with the rest of the actual string. return text + firstOptionString.slice(text.length, firstOptionString.length); } return ''; }, _getInputText: function _getInputText() { var _props3 = this.props; var activeIndex = _props3.activeIndex; var labelKey = _props3.labelKey; var options = _props3.options; var selected = _props3.selected; var text = _props3.text; var selectedItem = !!selected.length && (0, _lodash.head)(selected); if (selectedItem) { return selectedItem[labelKey]; } if (activeIndex >= 0) { return options[activeIndex][labelKey]; } return text; }, _handleBlur: function _handleBlur(e) { this.setState({ isFocused: false }); this.props.onBlur(e); }, _handleChange: function _handleChange(e) { // Clear any selections when text is entered. var _props4 = this.props; var onRemove = _props4.onRemove; var selected = _props4.selected; !!selected.length && onRemove((0, _lodash.head)(selected)); this.props.onChange(e.target.value); }, /** * If the containing parent div is focused or clicked, focus the input. */ _handleInputFocus: function _handleInputFocus(e) { this.setState({ isFocused: true }); this.refs.input.focus(); }, _handleKeydown: function _handleKeydown(e) { var _props5 = this.props; var activeIndex = _props5.activeIndex; var options = _props5.options; var onAdd = _props5.onAdd; var selected = _props5.selected; var text = _props5.text; switch (e.keyCode) { case _keyCode.RIGHT: case _keyCode.TAB: var cursorPos = this.refs.input.selectionStart; var hasHintText = !!this._getHintText(); // Autocomplete the selection if all of the following are true: if ( // There's a hint or a menu item is highlighted. (hasHintText || activeIndex !== -1) && // There's no current selection. !selected.length && // The input cursor is at the end of the text string when the user // hits the right arrow key. !(e.keyCode === _keyCode.RIGHT && cursorPos !== text.length)) { e.preventDefault(); var selectedOption = hasHintText ? (0, _lodash.head)(options) : options[activeIndex]; onAdd && onAdd(selectedOption); } break; } this.props.onKeyDown(e); } }); exports['default'] = TypeaheadInput; module.exports = exports['default']; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _reactHighlighter = __webpack_require__(14); var _reactHighlighter2 = _interopRequireDefault(_reactHighlighter); var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(4); var _classnames = __webpack_require__(3); var _classnames2 = _interopRequireDefault(_classnames); var Menu = function Menu(props) { return _react2['default'].createElement( 'ul', _extends({}, props, { className: (0, _classnames2['default'])('dropdown-menu', props.className) }), props.children ); }; var MenuItem = _react2['default'].createClass({ displayName: 'MenuItem', componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (nextProps.active) { (0, _reactDom.findDOMNode)(this).firstChild.focus(); } }, render: function render() { var _props = this.props; var active = _props.active; var children = _props.children; var className = _props.className; var disabled = _props.disabled; return _react2['default'].createElement( 'li', { className: (0, _classnames2['default'])({ 'active': active, 'disabled': disabled }, className) }, _react2['default'].createElement( 'a', { href: '#', onClick: this._handleClick }, children ) ); }, _handleClick: function _handleClick(e) { e.preventDefault(); this.props.onClick && this.props.onClick(); } }); var TypeaheadMenu = _react2['default'].createClass({ displayName: 'TypeaheadMenu', propTypes: { activeIndex: _react.PropTypes.number, align: _react.PropTypes.oneOf(['justify', 'left', 'right']), emptyLabel: _react.PropTypes.string, initialResultCount: _react.PropTypes.number, labelKey: _react.PropTypes.string.isRequired, maxHeight: _react.PropTypes.number, newSelectionPrefix: _react.PropTypes.string, options: _react.PropTypes.array, renderMenuItemChildren: _react.PropTypes.func, text: _react.PropTypes.string.isRequired }, getDefaultProps: function getDefaultProps() { return { align: 'justify', emptyLabel: 'No matches found.', initialResultCount: 100, maxHeight: 300, newSelectionPrefix: 'New selection:' }; }, getInitialState: function getInitialState() { return { /** * Max number of results to display, for performance reasons. If this * number is less than the number of available results, the user will see * an option to display more results. */ resultCount: this.props.initialResultCount }; }, render: function render() { var _props2 = this.props; var align = _props2.align; var maxHeight = _props2.maxHeight; var options = _props2.options; // Render the max number of results or all results. var results = options.slice(0, this.state.resultCount || options.length); results = results.length ? results.map(this._renderMenuItem) : _react2['default'].createElement( MenuItem, { disabled: true }, this.props.emptyLabel ); // Allow user to see more results, if available. var paginationItem = undefined; var separator = undefined; if (results.length < options.length) { paginationItem = _react2['default'].createElement( MenuItem, { className: 'bootstrap-typeahead-menu-paginator', onClick: this._handlePagination }, 'Display next ', this.props.initialResultCount, ' results...' ); separator = _react2['default'].createElement('li', { className: 'divider', role: 'separator' }); } return _react2['default'].createElement( Menu, { className: (0, _classnames2['default'])('bootstrap-typeahead-menu', { 'dropdown-menu-justify': align === 'justify', 'dropdown-menu-right': align === 'right' }), style: { maxHeight: maxHeight + 'px', overflow: 'auto' } }, results, separator, paginationItem ); }, _renderMenuItem: function _renderMenuItem(option, idx) { var _props3 = this.props; var activeIndex = _props3.activeIndex; var labelKey = _props3.labelKey; var newSelectionPrefix = _props3.newSelectionPrefix; var _onClick = _props3.onClick; var renderMenuItemChildren = _props3.renderMenuItemChildren; var text = _props3.text; var menuItemProps = { active: idx === activeIndex, key: idx, onClick: function onClick() { return _onClick(option); } }; return renderMenuItemChildren ? _react2['default'].createElement( MenuItem, menuItemProps, renderMenuItemChildren(this.props, option, idx) ) : _react2['default'].createElement( MenuItem, menuItemProps, option.customOption && newSelectionPrefix + ' ', _react2['default'].createElement( _reactHighlighter2['default'], { search: text }, option[labelKey] ) ); }, _handlePagination: function _handlePagination(e) { var resultCount = this.state.resultCount + this.props.initialResultCount; this.setState({ resultCount: resultCount }); } }); exports['default'] = TypeaheadMenu; module.exports = exports['default']; /***/ }, /* 12 */ /***/ function(module, exports) { module.exports = function blacklist (src) { var copy = {} var filter = arguments[1] if (typeof filter === 'string') { filter = {} for (var i = 1; i < arguments.length; i++) { filter[arguments[i]] = true } } for (var key in src) { // blacklist? if (filter[key]) continue copy[key] = src[key] } return copy } /***/ }, /* 13 */ /***/ function(module, exports) { 'use strict'; var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; module.exports = function (str) { if (typeof str !== 'string') { throw new TypeError('Expected a string'); } return str.replace(matchOperatorsRe, '\\$&'); }; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { var React = __webpack_require__(1); var RegExpPropType = __webpack_require__(15); var escapeStringRegexp = __webpack_require__(13); var blacklist = __webpack_require__(12); var Highlighter = React.createClass({displayName: "Highlighter", count: 0, propTypes: { search: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number, React.PropTypes.bool, RegExpPropType ]).isRequired, caseSensitive: React.PropTypes.bool, matchElement: React.PropTypes.string, matchClass: React.PropTypes.string, matchStyle: React.PropTypes.object }, getDefaultProps: function() { return { caseSensitive: false, matchElement: 'strong', matchClass: 'highlight', matchStyle: {} } }, render: function() { var props = blacklist(this.props, 'search', 'caseSensitive', 'matchElement', 'matchClass', 'matchStyle'); return React.createElement('span', props, this.renderElement(this.props.children)); }, /** * A wrapper to the highlight method to determine when the highlighting * process should occur. * * @param {string} subject * The body of text that will be searched for highlighted words. * * @return {Array} * An array of ReactElements */ renderElement: function(subject) { if (this.isScalar() && this.hasSearch()) { var search = this.getSearch(); return this.highlightChildren(subject, search); } return this.props.children; }, /** * Determine if props are valid types for processing. * * @return {Boolean} */ isScalar: function() { return (/string|number|boolean/).test(typeof this.props.children); }, /** * Determine if required search prop is defined and valid. * * @return {Boolean} */ hasSearch: function() { return (typeof this.props.search !== 'undefined') && this.props.search; }, /** * Get the search prop, but always in the form of a regular expression. Use * this as a proxy to this.props.search for consistency. * * @return {RegExp} */ getSearch: function() { if (this.props.search instanceof RegExp) { return this.props.search; } var flags = ''; if (!this.props.caseSensitive) { flags +='i'; } var search = this.props.search; if (typeof this.props.search === 'string') { search = escapeStringRegexp(search); } return new RegExp(search, flags); }, /** * Get the indexes of the first and last characters of the matched string. * * @param {string} subject * The string to search against. * * @param {RegExp} search * The regex search query. * * @return {Object} * An object consisting of "first" and "last" properties representing the * indexes of the first and last characters of a matching string. */ getMatchBoundaries: function(subject, search) { var matches = search.exec(subject); if (matches) { return { first: matches.index, last: matches.index + matches[0].length }; } }, /** * Determines which strings of text should be highlighted or not. * * @param {string} subject * The body of text that will be searched for highlighted words. * @param {string} search * The search used to search for highlighted words. * * @return {Array} * An array of ReactElements */ highlightChildren: function(subject, search) { var children = []; var matchElement = this.props.matchElement; var remaining = subject; while (remaining) { if (!search.test(remaining)) { children.push(this.renderPlain(remaining)); return children; } var boundaries = this.getMatchBoundaries(remaining, search); // Capture the string that leads up to a match... var nonMatch = remaining.slice(0, boundaries.first); if (nonMatch) { children.push(this.renderPlain(nonMatch)); } // Now, capture the matching string... var match = remaining.slice(boundaries.first, boundaries.last); if (match) { children.push(this.renderHighlight(match, matchElement)); } // And if there's anything left over, recursively run this method again. remaining = remaining.slice(boundaries.last); } return children; }, /** * Responsible for rending a non-highlighted element. * * @param {string} string * A string value to wrap an element around. * * @return {ReactElement} */ renderPlain: function(string) { this.count++; return React.DOM.span({'key': this.count}, string); }, /** * Responsible for rending a highlighted element. * * @param {string} string * A string value to wrap an element around. * * @return {ReactElement} */ renderHighlight: function(string) { this.count++; return React.DOM[this.props.matchElement]({ key: this.count, className: this.props.matchClass, style: this.props.matchStyle }, string); } }); module.exports = Highlighter; /***/ }, /* 15 */ /***/ function(module, exports) { var regExpPropType = function (props, propName, componentName, location) { if (!(props[propName] instanceof RegExp)) { var propType = typeof props[propName]; return new Error( ("Invalid " + location + " `" + propName + "` of type `" + propType + "` ") + ("supplied to `" + componentName + "`, expected `RegExp`.") ); } }; module.exports = regExpPropType; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var React = __webpack_require__(1); var sizerStyle = { position: 'absolute', top: 0, left: 0, visibility: 'hidden', height: 0, overflow: 'scroll', whiteSpace: 'pre' }; var AutosizeInput = React.createClass({ displayName: 'AutosizeInput', propTypes: { className: React.PropTypes.string, // className for the outer element defaultValue: React.PropTypes.any, // default field value inputClassName: React.PropTypes.string, // className for the input element inputStyle: React.PropTypes.object, // css styles for the input element minWidth: React.PropTypes.oneOfType([// minimum width for input element React.PropTypes.number, React.PropTypes.string]), onChange: React.PropTypes.func, // onChange handler: function(newValue) {} placeholder: React.PropTypes.string, // placeholder text placeholderIsMinWidth: React.PropTypes.bool, // don't collapse size to less than the placeholder style: React.PropTypes.object, // css styles for the outer element value: React.PropTypes.any }, // field value getDefaultProps: function getDefaultProps() { return { minWidth: 1 }; }, getInitialState: function getInitialState() { return { inputWidth: this.props.minWidth }; }, componentDidMount: function componentDidMount() { this.copyInputStyles(); this.updateInputWidth(); }, componentDidUpdate: function componentDidUpdate() { this.updateInputWidth(); }, copyInputStyles: function copyInputStyles() { if (!this.isMounted() || !window.getComputedStyle) { return; } var inputStyle = window.getComputedStyle(this.refs.input); if (!inputStyle) { return; } var widthNode = this.refs.sizer; widthNode.style.fontSize = inputStyle.fontSize; widthNode.style.fontFamily = inputStyle.fontFamily; widthNode.style.fontWeight = inputStyle.fontWeight; widthNode.style.fontStyle = inputStyle.fontStyle; widthNode.style.letterSpacing = inputStyle.letterSpacing; if (this.props.placeholder) { var placeholderNode = this.refs.placeholderSizer; placeholderNode.style.fontSize = inputStyle.fontSize; placeholderNode.style.fontFamily = inputStyle.fontFamily; placeholderNode.style.fontWeight = inputStyle.fontWeight; placeholderNode.style.fontStyle = inputStyle.fontStyle; placeholderNode.style.letterSpacing = inputStyle.letterSpacing; } }, updateInputWidth: function updateInputWidth() { if (!this.isMounted() || typeof this.refs.sizer.scrollWidth === 'undefined') { return; } var newInputWidth = undefined; if (this.props.placeholder && (!this.props.value || this.props.value && this.props.placeholderIsMinWidth)) { newInputWidth = Math.max(this.refs.sizer.scrollWidth, this.refs.placeholderSizer.scrollWidth) + 2; } else { newInputWidth = this.refs.sizer.scrollWidth + 2; } if (newInputWidth < this.props.minWidth) { newInputWidth = this.props.minWidth; } if (newInputWidth !== this.state.inputWidth) { this.setState({ inputWidth: newInputWidth }); } }, getInput: function getInput() { return this.refs.input; }, focus: function focus() { this.refs.input.focus(); }, blur: function blur() { this.refs.input.blur(); }, select: function select() { this.refs.input.select(); }, render: function render() { var sizerValue = this.props.defaultValue || this.props.value || ''; var wrapperStyle = this.props.style || {}; if (!wrapperStyle.display) wrapperStyle.display = 'inline-block'; var inputStyle = _extends({}, this.props.inputStyle); inputStyle.width = this.state.inputWidth + 'px'; inputStyle.boxSizing = 'content-box'; var inputProps = _extends({}, this.props); inputProps.className = this.props.inputClassName; inputProps.style = inputStyle; // ensure props meant for `AutosizeInput` don't end up on the `input` delete inputProps.inputClassName; delete inputProps.inputStyle; delete inputProps.minWidth; delete inputProps.placeholderIsMinWidth; return React.createElement( 'div', { className: this.props.className, style: wrapperStyle }, React.createElement('input', _extends({}, inputProps, { ref: 'input' })), React.createElement( 'div', { ref: 'sizer', style: sizerStyle }, sizerValue ), this.props.placeholder ? React.createElement( 'div', { ref: 'placeholderSizer', style: sizerStyle }, this.props.placeholder ) : null ); } }); module.exports = AutosizeInput; /***/ }, /* 17 */ /***/ function(module, exports) { module.exports = function(module) { if(!module.webpackPolyfill) { module.deprecate = function() {}; module.paths = []; // module.parent = undefined by default module.children = []; module.webpackPolyfill = 1; } return module; } /***/ } /******/ ]) }); ;
pages/photo.js
jubearsun/juliasun.io
import React from 'react'; import { prefixLink } from 'gatsby-helpers'; // eslint-disable-line import Helmet from 'react-helmet'; import _ from 'lodash'; export default class Photo extends React.Component { componentDidMount() {} render() { const works = [ { img: '../img/works/photo/2.jpg', }, { img: '../img/works/photo/1.jpg', }, { img: '../img/works/photo/3.jpg', }, ]; const workElems = _.map(works, (work, index) => <div key={`workElem-${index}`} className="img__wrapper" > <img src={prefixLink(work.img)} alt="work" /> </div>, ); return ( <div> <Helmet title="Julia Sun | Photography" /> <div className="page--photo"> <div className="pinterest__grid--small"> { workElems } </div> </div> </div> ); } }
packages/icons/src/md/editor/FormatUnderlined.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdFormatUnderlined(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M24 34c6.63 0 12-5.37 12-12V6h-5v16c0 3.87-3.13 7-7 7s-7-3.13-7-7V6h-5v16c0 6.63 5.37 12 12 12zm-14 4v4h28v-4H10z" /> </IconBase> ); } export default MdFormatUnderlined;
app/src/components/date/index.js
ajfisher/tourney-tools
import React, { Component } from 'react'; import Moment from 'moment'; class DateFormat extends Component { render() { const date = Moment(this.props.date); return ( <date> { date.format("MMMM Do YYYY") } </date> ) } } export default DateFormat;
src/website/app/pages/Color/ColorRampRow.js
mineral-ui/mineral-ui
/* @flow */ import styled from '@emotion/styled'; import colorable from 'colorable'; import { palette } from 'mineral-ui-tokens'; import readableColor from 'polished/lib/color/readableColor'; import React from 'react'; import type { StyledComponent } from '@emotion/styled-base/src/utils'; type Props = { name: string }; const styles = { row: ({ color, theme }) => ({ backgroundColor: color, display: 'flex', fontSize: theme.fontSize_mouse, justifyContent: 'space-between', padding: theme.space_inset_md, width: '100%' }), colorName: ({ color, theme }) => ({ color, display: 'block', fontWeight: 'bold', marginBottom: theme.space_stack_sm }), hsl: ({ color }) => ({ color, display: 'block', fontWeight: 100, whiteSpace: 'nowrap' }), whiteOnBackground: ({ theme }) => ({ color: 'white', display: 'block', marginBottom: theme.space_stack_sm }), blackonBackground: { color: palette.black, display: 'block' }, accessibilityInfo: { display: 'block', textAlign: 'right', whiteSpace: 'nowrap' } }; const Row: StyledComponent<{ [key: string]: any }> = styled('div')(styles.row); const BlackOnBackground = styled('span')(styles.blackonBackground); const WhiteOnBackground = styled('span')(styles.whiteOnBackground); const ColorName = styled('span')(styles.colorName); const AccessibilityInfo = styled('div')(styles.accessibilityInfo); const HSL = styled('span')(styles.hsl); function getBestAccessibility(access) { if (access.aaa) { return 'AAA'; } else if (access.aa) { return 'AA'; } else if (access.aaaLarge) { return 'AAA Large'; } else if (access.aaLarge) { return 'AA Large'; } // this character is a non-breaking space. return ' '; // should this be an explicit DNP? } export default function ColorRampRow(props: Props) { const { name } = props; // the black here is the color from our theme. const main = palette[name]; const readable = readableColor(main); const accessibility = colorable({ main, black: palette.black, white: palette.white }); const hsl = accessibility.find((result) => result.name === 'main').values.hsl; const blackonBackground = accessibility .find((result) => result.name === 'black') .combinations.find((combo) => combo.name === 'main'); const whiteOnBackground = accessibility .find((result) => result.name === 'white') .combinations.find((combo) => combo.name === 'main'); return ( <Row color={main}> <div> <ColorName color={readable}>{name}</ColorName> <HSL color={readable}>{`hsl(${hsl[0]}, ${hsl[1]}%, ${hsl[2]}%)`}</HSL> </div> <AccessibilityInfo> <WhiteOnBackground> {getBestAccessibility(whiteOnBackground.accessibility)} </WhiteOnBackground> <BlackOnBackground> {getBestAccessibility(blackonBackground.accessibility)} </BlackOnBackground> </AccessibilityInfo> </Row> ); }
app/components/UGBreadcrums/index.js
perry-ugroop/ugroop-react-dup2
/* ************************************************************************** */ /* Created by: Vince (14-12-2016) /* ************************************************************************** */ import React from 'react'; import { Grid, Breadcrumb } from 'react-bootstrap'; import UGBreadcrumbStyle from './UGBreadcrumbStyle'; function UGBreadcrumbs(props) { return ( <UGBreadcrumbStyle> <Grid> <Breadcrumb> <Breadcrumb.Item href="/">Home</Breadcrumb.Item> <Breadcrumb.Item href="#" active>{props.title}</Breadcrumb.Item> </Breadcrumb> </Grid> </UGBreadcrumbStyle> ); } UGBreadcrumbs.propTypes = { title: React.PropTypes.string, }; export default UGBreadcrumbs;
frontend/src/components/welcome/body/SignupForm.js
dimkarakostas/unimeet
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import {Form, FormControl, FormGroup, Button} from 'react-bootstrap'; import SignupModal from './SignupModal'; import * as config from '../../config'; import {Link} from 'react-router-dom'; import axios from 'axios'; axios.defaults.withCredentials = true; class SignupForm extends Component { constructor(props) { super(props); this.state = { email: '', isModalOpen: false, isSignupButtonLoading: false, invalidEmail: false, duplicateEmail: false }; this.forgot = this.forgot.bind(this); } hideModal = () => { this.setState({isModalOpen: false}); } handleEmailChange = (event) => { this.setState({email: event.target.value}); this.setState({ invalidEmail: false, duplicateEmail: false, multipleRegistrations: false }); } signupSubmit = (event) => { event.preventDefault(); this.setState({isSignupButtonLoading: true}); axios.post(config.backendUrl + '/signup', {email: this.state.email}) .then(res => { if (res.status === 200 && res.data === 'Signup OK') { this.setState({ isSignupButtonLoading: false, isModalOpen: true, email: '' }); } }) .catch(error => { this.setState({ isSignupButtonLoading: false, duplicateEmail: false, invalidEmail: false, unknownSignupError: false }); if (error.response) { switch (error.response.status) { case 409: this.setState({ duplicateEmail: true }); break; case 403: this.setState({ multipleRegistrations: true }); break; case 400: this.setState({ invalidEmail: true }); break; default: this.setState({ unknownSignupError: true }); }; } else { this.setState({ unknownSignupError: true }); } var signupEmailElement = ReactDOM.findDOMNode(this.signupEmail); signupEmailElement.focus(); signupEmailElement.select(); console.log(error); }) } forgot(e) { e.preventDefault(); this.props.onforgot(); } render() { return ( <div> <p>Το <b>ακαδημαϊκό</b> σου email:</p> <Form horizontal className="signup-form" onSubmit={this.signupSubmit}> <FormGroup validationState={this.state.invalidEmail ? "warning" : null} ref={(input) => { this.signupForm = input; }} > <FormControl type="text" name="email" autoComplete="off" autoFocus placeholder="[email protected]" ref={(input) => { this.signupEmail = input; }} value={this.state.email} disabled={this.state.isSignupButtonLoading} onChange={this.handleEmailChange} /> </FormGroup> <Button type="submit" bsStyle="primary" id="btn-signup" disabled={this.state.isSignupButtonLoading} onClick={!this.state.isSignupButtonLoading? this.signupSubmit : null} > {this.state.isSignupButtonLoading? 'Εγγραφή...' : 'Εγγραφή'} </Button> {this.state.invalidEmail ? <div className="email-error"> <b>Υπήρξε κάποιο πρόβλημα! Χρησιμοποίησες ένα <Link to="/faq" target="_blank">έγκυρο ακαδημαϊκό</Link> email?</b> </div> : this.state.duplicateEmail ? <div className="email-error"> <b>Το email που επέλεξες χρησιμοποιείται ήδη! <a onClick={this.forgot} href=''>Επανάφερε τον κωδικό σου</a>.</b> </div> : this.state.multipleRegistrations ? <div className="email-error"> <b>Έχουν γίνει πολλές εγγραφές από τον υπολογιστή σου σήμερα. Περίμενε μια μέρα και ξαναδοκίμασε.</b> </div> : this.state.unknownSignupError ? <div className="email-error"> <b>Προσπάθησε ξανά αργότερα.</b> </div> : null} </Form> <div className="copyright text-muted" id="email-disclaimer" >Η διεύθυνση email σου θα χρησιμοποιηθεί <b>μόνο</b> για να επιβεβαιωθεί ότι είσαι φοιτητής.</div> <SignupModal isModalOpen={this.state.isModalOpen} hideModal={this.hideModal} /> </div> ); } } export default SignupForm;
src/DropdownMenu.js
tonylinyy/react-bootstrap
import React, { cloneElement } from 'react'; import classNames from 'classnames'; import createChainedFunction from './utils/createChainedFunction'; import ValidComponentChildren from './utils/ValidComponentChildren'; const DropdownMenu = React.createClass({ propTypes: { pullRight: React.PropTypes.bool, onSelect: React.PropTypes.func }, render() { let classes = { 'dropdown-menu': true, 'dropdown-menu-right': this.props.pullRight }; return ( <ul {...this.props} className={classNames(this.props.className, classes)} role="menu"> {ValidComponentChildren.map(this.props.children, this.renderMenuItem)} </ul> ); }, renderMenuItem(child, index) { return cloneElement( child, { // Capture onSelect events onSelect: createChainedFunction(child.props.onSelect, this.props.onSelect), // Force special props to be transferred key: child.key ? child.key : index } ); } }); export default DropdownMenu;
src/index.js
colevoss/redux-friendlist-demo
import React from 'react'; import App from './containers/App'; React.render(<App />, document.getElementById('root'));
examples/huge-apps/routes/Course/components/Dashboard.js
sleexyz/react-router
import React from 'react'; class Dashboard extends React.Component { render () { return ( <div> <h3>Course Dashboard</h3> </div> ); } } export default Dashboard;
src/components/InfinityMenu/EmptyTree.js
City-of-Helsinki/helerm-ui
import React from 'react'; const EmptyTree = () => { return ( <div className='alert alert-danger'> <p>Ei tuloksia</p> </div> ); }; export default EmptyTree;
packages/wix-style-react/src/StackedBarChart/docs/index.story.js
wix/wix-style-react
import React from 'react'; import { header, tabs, tab, description, importExample, title, divider, code, playground, api, testkit, } from 'wix-storybook-utils/Sections'; import { storySettings } from '../test/storySettings'; import * as examples from './examples'; import StackedBarChart from '..'; import SectionHelper from '../../SectionHelper'; export default { category: storySettings.category, storyName: storySettings.storyName, component: StackedBarChart, componentPath: '..', componentProps: { width: 800, height: 400, margin: { top: 40, bottom: 40, left: 80, right: 10 }, data: [ { label: 'Jan 20', values: [500, 200] }, { label: 'Feb 20', values: [200, 700] }, { label: 'Mar 20', values: [0, 400] }, { label: 'Apr 20', values: [900, 100] }, { label: 'Mai 20', values: [300, 300] }, { label: 'Jun 20', values: [400, 300] }, { label: 'Jul 20', values: [100, 100] }, { label: 'Aug 20', values: [0, 0] }, { label: 'Sep 20', values: [800, 0] }, { label: 'Oct 20', values: [600, 300] }, { label: 'Nov 20', values: [200, 300] }, { label: 'Dec 20', values: [300, 200] }, ], }, exampleProps: { // Put here presets of props, for more info: // https://github.com/wix/wix-ui/blob/master/packages/wix-storybook-utils/docs/usage.md#using-list }, sections: [ header({ sourceUrl: `https://github.com/wix/wix-style-react/tree/master/src/${StackedBarChart.displayName}/`, }), tabs([ tab({ title: 'Description', sections: [ description({ title: 'Description', text: 'This line here should briefly describe component in just a sentence or two. It should be short and easy to read.', }), importExample(), divider(), description({ text: ( <SectionHelper title="WARNING"> This component is work in progress, please don't use this component unless you were instructed to by wsr team. <br /> Note that API is not stable and can change anytime! </SectionHelper> ), }), title('Examples'), code({ compact: true, initiallyOpen: true, source: examples.simple, }), ], }), ...[ { title: 'API', sections: [api()] }, { title: 'Testkit', sections: [testkit()] }, { title: 'Playground', sections: [playground()] }, ].map(tab), ]), ], };
src/components/HeaderBar/CurrentDJ.js
u-wave/web
import React from 'react'; import PropTypes from 'prop-types'; import { useTranslator } from '@u-wave/react-translate'; function CurrentDJ({ className, dj }) { const { t } = useTranslator(); return ( <div className={className}> {t('booth.currentDJ', { user: dj.username })} </div> ); } CurrentDJ.propTypes = { className: PropTypes.string, dj: PropTypes.shape({ username: PropTypes.string.isRequired, }), }; export default CurrentDJ;
app/routes/404.js
hugo/hugo.github.com
import React from 'react' export function meta() { return {title: 'Not Found'} } export default function FourZeroFour() { return ( <div className="error"> <h1>404 :(</h1> </div> ) }
javascript/components/edit-transfer-batch.js
kdoran/moriana-react
import React from 'react' import ClickOutHandler from 'react-onclickout' import { displayItemName, searchItems } from 'store/items' import { getItemTotalQuantity, getTotalAvailableStock } from 'store/stock' import h, {setCursorAtEnd, preventDefault} from 'utils/helpers' import { quantityIsValid } from 'utils/validation' import { mergeTransferQuantityWithStock, getTransferTransactionsFromDisplay } from 'utils/input-transforms' import SearchDrop from 'components/search-drop' import EditTransactionsTable from 'components/edit-transactions-table' import ManualTransferBatch from 'components/manual-transfer-batch' export default class EditTransferBatch extends React.Component { constructor (props) { super(props) this.state = this.getDefaultState() } getDefaultState = () => { return { item: '', category: '', quantity: '', totalAvailableStock: 0, displayTransactions: [], quantityError: false, insufficientStockError: false, isEditing: false, isEditFromShipment: false, changed: false, isManualEditing: false } } componentWillReceiveProps = (newProps) => { if (this.props.itemStockLoading && !newProps.itemStockLoading) { const totalAvailableStock = getTotalAvailableStock(newProps.itemStock) const originalQuantity = getItemTotalQuantity(this.props.transactions, this.state.item, this.state.category) const quantity = originalQuantity || '' this.setState({ totalAvailableStock, originalQuantity, quantity }) this.makeDisplayTransactions(newProps.itemStock, totalAvailableStock, quantity) } } showEdit = ({ item, category }, isEditFromShipment) => { this.setState({ isEditing: true, item, category, isEditFromShipment: isEditFromShipment }) this.props.getStockOnItem(item, category) } hideEdit = () => { this.setState(this.getDefaultState()) } onClickTransaction = (index) => { const { item, category } = this.props.transactions[index] this.showEdit({item, category}, true) } onChangeQuantity = (event) => { const quantity = event.currentTarget.value const quantityError = !quantityIsValid(quantity) this.setState({ quantity, quantityError, insufficientStockError: false }) } onKeyDownQuantity = (event) => { const key = h.keyMap(event.keyCode) if (key === 'ESCAPE') { this.hideEdit() } else if (key === 'ENTER') { this.onSubmitQuantity() } } onSubmitQuantity = (event) => { if (event) event.preventDefault() if (!this.state.quantityError) { const { totalAvailableStock, quantity } = this.state this.setState({ changed: true }) this.makeDisplayTransactions(this.props.itemStock, totalAvailableStock, quantity) } } makeDisplayTransactions = (itemStock, totalAvailableStock, quantity) => { if (quantity > totalAvailableStock) { this.setState({ insufficientStockError: true }) } else { this.setState({ displayTransactions: mergeTransferQuantityWithStock(quantity, itemStock), insufficientStockError: false }) } } onSubmitEdits = () => { const { insufficientStockError, quantityError, displayTransactions, originalQuantity, item, category, quantity } = this.state if (!insufficientStockError && !quantityError) { if (originalQuantity !== Number.parseInt(quantity)) { const editedTransactions = getTransferTransactionsFromDisplay(displayTransactions) this.props.updateShipment('transfer_transactions', { editedTransactions, item, category }, this.props.user.name) } this.hideEdit() } } submitManualEdits = (editedTransactions) => { if (editedTransactions.length) { const {item, category} = this.state this.props.updateShipment('transfer_transactions', { editedTransactions, item, category }, this.props.user.name) this.hideEdit() } else { this.deleteTransactions() } } deleteTransactions = () => { const { item, category } = this.state this.props.updateShipment('transfer_transactions', { deleted: true, item, category }, this.props.user.name) this.hideEdit() } render () { const { items, itemsLoading, transactions, itemStockLoading, showManualEdit } = this.props const { item, category, quantity, totalAvailableStock, displayTransactions, quantityError, insufficientStockError, isEditing, isEditFromShipment, changed, isManualEditing } = this.state return ( <div> <form onSubmit={preventDefault}> <SearchDrop rows={items} loading={itemsLoading} value={{}} valueSelected={this.showEdit} label={'Search Items'} resourceName={'Item'} displayFunction={displayItemName} searchFilterFunction={searchItems} className='search-items' /> </form> <EditTransactionsTable transactions={transactions} onEditClick={this.onClickTransaction} /> {isEditing && ( isManualEditing ? ( <ManualTransferBatch onClickOut={this.hideEdit} item={item} category={category} transactions={displayTransactions} submitEdits={this.submitManualEdits} /> ) : ( <ClickOutHandler onClickOut={this.hideEdit}> <div className='modal edit-batch'> <div> <button className='close' onMouseDown={this.hideEdit}> <span>×</span> </button> <h5>{item} {category}</h5> </div> {itemStockLoading ? (<div className='loader' />) : ( <form onSubmit={this.onSubmitQuantity}> <div className={`${quantityError ? 'error' : ''}`}> <label>Quantity</label> <div className='input-group'> <input type='text' value={quantity} onChange={this.onChangeQuantity} onKeyDown={this.onKeyDownQuantity} onFocus={setCursorAtEnd} autoFocus /> {quantityError && (<p className='error'> Quantity is required and must be numeric. </p>)} {insufficientStockError && (<p className='error'> Insufficient stock. Maximum available quantity is {h.num(totalAvailableStock)}. </p>)} </div> </div> <br /><br /> <button onClick={this.onSubmitQuantity} className='button-primary'>Confirm Quantity</button> <br /><br /> <table className='no-hover center-table'> <thead> <tr> <th>Expiration</th> <th>Lot</th> <th>Stock</th> <th>Transfer Quantity</th> <th>Resulting Stock</th> </tr> </thead> <tbody> {displayTransactions.map((t, i) => ( <tr key={i}> <td>{h.expiration(t.expiration)}</td> <td>{t.lot}</td> <td>{h.num(t.sum)}</td> <td>{h.num(t.quantity)}</td> <td>{h.num(t.resultingQuantity)}</td> </tr> ))} </tbody> </table> <button onMouseDown={this.hideEdit}>Cancel</button> { (changed && !quantityError && !insufficientStockError) ? (<button onClick={this.onSubmitEdits}>Confirm edits</button>) : (<button className='disabled'>Confirm edits</button>) } {isEditFromShipment && ( <button onMouseDown={this.deleteTransactions} className='pull-right'>delete</button> )} {showManualEdit && ( <a href='#' onClick={(e) => { e.preventDefault(); this.setState({ isManualEditing: true }) }} className='pull-right' > Manual Edit </a> )} </form> )} </div> </ClickOutHandler> ) )} </div> ) } }
app/components/IconButton/IconButton.js
zhrkian/SolarDataApp
import s from './IconButton.css' import React from 'react' import IButton from 'material-ui/IconButton' import * as Icons from '../Icons/Icons' const IconButton = props => { const { icon, label, disabled, onClick, link, simple } = props const Icon = Icons[icon] const styles = disabled ? {opacity: 0.5, cursor: 'not-allowed'} : {} const isLink = (element, lvl) => { if (element.nodeName.toLowerCase() === 'a') return element if (lvl === 10) return false lvl += 1 return isLink(element.parentNode, lvl) } const click = e => { let lvl = 0 const linkElement = isLink(e.target, lvl) if (!link) e.preventDefault() return disabled ? null : onClick(linkElement) } if (simple) { return ( <div style={{paddingTop: 10}}> <a href="#0" style={{padding: 5, backgroundColor: 'rgb(224, 224, 224)'}} onClick={click}> {label} </a> </div> ) } return ( <IButton className={s.container} style={styles} href="#0" onClick={click} tooltip={label.length > 12 ? label : null}> <div className={s.icon}> <Icon /> </div> <div className={s.label}> <div className={s.text}>{label}</div> </div> </IButton> ) } export default IconButton
src/admin/client/modules/customers/list/components/head.js
cezerin/cezerin
import React from 'react'; import Subheader from 'material-ui/Subheader'; import Checkbox from 'material-ui/Checkbox'; import messages from 'lib/text'; export default ({ onSelectAll }) => ( <Subheader style={{ paddingRight: 16 }}> <div className="row middle-xs"> <div className="col-xs-1"> <Checkbox onCheck={(event, isInputChecked) => { onSelectAll(isInputChecked); }} /> </div> <div className="col-xs-5">{messages.customers_name}</div> <div className="col-xs-3">{messages.customers_location}</div> <div className="col-xs-1">{messages.customers_orders}</div> <div className="col-xs-2" style={{ textAlign: 'right', paddingRight: 16 }} > {messages.customers_totalSpent} </div> </div> </Subheader> );
packages/material-ui/src/CardActions/CardActions.js
Kagami/material-ui
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import withStyles from '../styles/withStyles'; import { cloneChildrenWithClassName } from '../utils/reactHelpers'; import '../Button'; // So we don't have any override priority issue. export const styles = { /* Styles applied to the root element. */ root: { display: 'flex', alignItems: 'center', boxSizing: 'border-box', padding: '8px 4px', }, /* Styles applied to the root element if `disableActionSpacing={true}`. */ disableActionSpacing: { padding: 8, }, /* Styles applied to the children. */ action: { margin: '0 4px', }, }; function CardActions(props) { const { disableActionSpacing, children, classes, className, ...other } = props; return ( <div className={classNames( classes.root, { [classes.disableActionSpacing]: disableActionSpacing }, className, )} {...other} > {disableActionSpacing ? children : cloneChildrenWithClassName(children, classes.action)} </div> ); } CardActions.propTypes = { /** * The content of the component. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css-api) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * If `true`, the card actions do not have additional margin. */ disableActionSpacing: PropTypes.bool, }; CardActions.defaultProps = { disableActionSpacing: false, }; export default withStyles(styles, { name: 'MuiCardActions' })(CardActions);
test/TabGroup.js
redux-autoform/redux-autoform-material-ui
import React from 'react'; import { shallow } from 'enzyme'; import { expect } from 'chai'; import TabGroup from '../src/components/group/TabGroup'; describe("<TabGroup/> Component", () => { it("TabGroup instance is not null", () => { const props = { layout: { groups: [] }, fields: [], componentFactory: {} }; const wrapper = shallow(<TabGroup {...props}/>); expect(wrapper).to.not.equal('null') }); });
js/jquery-1.11.0.js
hugomarkitt/finalfinal
/*! jQuery v1.11.0 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k="".trim,l={},m="1.11.0",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(n.isPlainObject(c)||(b=n.isArray(c)))?(b?(b=!1,f=a&&n.isArray(a)?a:[]):f=a&&n.isPlainObject(a)?a:{},g[d]=n.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray||function(a){return"array"===n.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(l.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&n.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:k&&!k.call("\ufeff\xa0")?function(a){return null==a?"":k.call(a)}:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),n.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||n.guid++,e):void 0},now:function(){return+new Date},support:l}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s="sizzle"+-new Date,t=a.document,u=0,v=0,w=eb(),x=eb(),y=eb(),z=function(a,b){return a===b&&(j=!0),0},A="undefined",B=1<<31,C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=D.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",M=L.replace("w","w#"),N="\\["+K+"*("+L+")"+K+"*(?:([*^$|!~]?=)"+K+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+M+")|)|)"+K+"*\\]",O=":("+L+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+N.replace(3,8)+")*)|.*)\\)|)",P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(O),U=new RegExp("^"+M+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L.replace("w","w*")+")"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=/'|\\/g,ab=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),bb=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{G.apply(D=H.call(t.childNodes),t.childNodes),D[t.childNodes.length].nodeType}catch(cb){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function db(a,b,d,e){var f,g,h,i,j,m,p,q,u,v;if((b?b.ownerDocument||b:t)!==l&&k(b),b=b||l,d=d||[],!a||"string"!=typeof a)return d;if(1!==(i=b.nodeType)&&9!==i)return[];if(n&&!e){if(f=Z.exec(a))if(h=f[1]){if(9===i){if(g=b.getElementById(h),!g||!g.parentNode)return d;if(g.id===h)return d.push(g),d}else if(b.ownerDocument&&(g=b.ownerDocument.getElementById(h))&&r(b,g)&&g.id===h)return d.push(g),d}else{if(f[2])return G.apply(d,b.getElementsByTagName(a)),d;if((h=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(h)),d}if(c.qsa&&(!o||!o.test(a))){if(q=p=s,u=b,v=9===i&&a,1===i&&"object"!==b.nodeName.toLowerCase()){m=ob(a),(p=b.getAttribute("id"))?q=p.replace(_,"\\$&"):b.setAttribute("id",q),q="[id='"+q+"'] ",j=m.length;while(j--)m[j]=q+pb(m[j]);u=$.test(a)&&mb(b.parentNode)||b,v=m.join(",")}if(v)try{return G.apply(d,u.querySelectorAll(v)),d}catch(w){}finally{p||b.removeAttribute("id")}}}return xb(a.replace(P,"$1"),b,d,e)}function eb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function fb(a){return a[s]=!0,a}function gb(a){var b=l.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function hb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function ib(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||B)-(~a.sourceIndex||B);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function jb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function kb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function lb(a){return fb(function(b){return b=+b,fb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function mb(a){return a&&typeof a.getElementsByTagName!==A&&a}c=db.support={},f=db.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},k=db.setDocument=function(a){var b,e=a?a.ownerDocument||a:t,g=e.defaultView;return e!==l&&9===e.nodeType&&e.documentElement?(l=e,m=e.documentElement,n=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){k()},!1):g.attachEvent&&g.attachEvent("onunload",function(){k()})),c.attributes=gb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=gb(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(e.getElementsByClassName)&&gb(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=gb(function(a){return m.appendChild(a).id=s,!e.getElementsByName||!e.getElementsByName(s).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==A&&n){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){var c=typeof a.getAttributeNode!==A&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==A?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==A&&n?b.getElementsByClassName(a):void 0},p=[],o=[],(c.qsa=Y.test(e.querySelectorAll))&&(gb(function(a){a.innerHTML="<select t=''><option selected=''></option></select>",a.querySelectorAll("[t^='']").length&&o.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||o.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll(":checked").length||o.push(":checked")}),gb(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&o.push("name"+K+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||o.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),o.push(",.*:")})),(c.matchesSelector=Y.test(q=m.webkitMatchesSelector||m.mozMatchesSelector||m.oMatchesSelector||m.msMatchesSelector))&&gb(function(a){c.disconnectedMatch=q.call(a,"div"),q.call(a,"[s!='']:x"),p.push("!=",O)}),o=o.length&&new RegExp(o.join("|")),p=p.length&&new RegExp(p.join("|")),b=Y.test(m.compareDocumentPosition),r=b||Y.test(m.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},z=b?function(a,b){if(a===b)return j=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===t&&r(t,a)?-1:b===e||b.ownerDocument===t&&r(t,b)?1:i?I.call(i,a)-I.call(i,b):0:4&d?-1:1)}:function(a,b){if(a===b)return j=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],k=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:i?I.call(i,a)-I.call(i,b):0;if(f===g)return ib(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)k.unshift(c);while(h[d]===k[d])d++;return d?ib(h[d],k[d]):h[d]===t?-1:k[d]===t?1:0},e):l},db.matches=function(a,b){return db(a,null,null,b)},db.matchesSelector=function(a,b){if((a.ownerDocument||a)!==l&&k(a),b=b.replace(S,"='$1']"),!(!c.matchesSelector||!n||p&&p.test(b)||o&&o.test(b)))try{var d=q.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return db(b,l,null,[a]).length>0},db.contains=function(a,b){return(a.ownerDocument||a)!==l&&k(a),r(a,b)},db.attr=function(a,b){(a.ownerDocument||a)!==l&&k(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!n):void 0;return void 0!==f?f:c.attributes||!n?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},db.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},db.uniqueSort=function(a){var b,d=[],e=0,f=0;if(j=!c.detectDuplicates,i=!c.sortStable&&a.slice(0),a.sort(z),j){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return i=null,a},e=db.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=db.selectors={cacheLength:50,createPseudo:fb,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ab,bb),a[3]=(a[4]||a[5]||"").replace(ab,bb),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||db.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&db.error(a[0]),a},PSEUDO:function(a){var b,c=!a[5]&&a[2];return V.CHILD.test(a[0])?null:(a[3]&&void 0!==a[4]?a[2]=a[4]:c&&T.test(c)&&(b=ob(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ab,bb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=w[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&w(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==A&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=db.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),t=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&t){k=q[s]||(q[s]={}),j=k[a]||[],n=j[0]===u&&j[1],m=j[0]===u&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[u,n,m];break}}else if(t&&(j=(b[s]||(b[s]={}))[a])&&j[0]===u)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(t&&((l[s]||(l[s]={}))[a]=[u,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||db.error("unsupported pseudo: "+a);return e[s]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?fb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:fb(function(a){var b=[],c=[],d=g(a.replace(P,"$1"));return d[s]?fb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:fb(function(a){return function(b){return db(a,b).length>0}}),contains:fb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:fb(function(a){return U.test(a||"")||db.error("unsupported lang: "+a),a=a.replace(ab,bb).toLowerCase(),function(b){var c;do if(c=n?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===m},focus:function(a){return a===l.activeElement&&(!l.hasFocus||l.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:lb(function(){return[0]}),last:lb(function(a,b){return[b-1]}),eq:lb(function(a,b,c){return[0>c?c+b:c]}),even:lb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:lb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:lb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:lb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=jb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=kb(b);function nb(){}nb.prototype=d.filters=d.pseudos,d.setFilters=new nb;function ob(a,b){var c,e,f,g,h,i,j,k=x[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=Q.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=R.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(P," ")}),h=h.slice(c.length));for(g in d.filter)!(e=V[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?db.error(a):x(a,i).slice(0)}function pb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function qb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=v++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[u,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[s]||(b[s]={}),(h=i[d])&&h[0]===u&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function rb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function sb(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function tb(a,b,c,d,e,f){return d&&!d[s]&&(d=tb(d)),e&&!e[s]&&(e=tb(e,f)),fb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||wb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:sb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=sb(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?I.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=sb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ub(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],i=g||d.relative[" "],j=g?1:0,k=qb(function(a){return a===b},i,!0),l=qb(function(a){return I.call(b,a)>-1},i,!0),m=[function(a,c,d){return!g&&(d||c!==h)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>j;j++)if(c=d.relative[a[j].type])m=[qb(rb(m),c)];else{if(c=d.filter[a[j].type].apply(null,a[j].matches),c[s]){for(e=++j;f>e;e++)if(d.relative[a[e].type])break;return tb(j>1&&rb(m),j>1&&pb(a.slice(0,j-1).concat({value:" "===a[j-2].type?"*":""})).replace(P,"$1"),c,e>j&&ub(a.slice(j,e)),f>e&&ub(a=a.slice(e)),f>e&&pb(a))}m.push(c)}return rb(m)}function vb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,i,j,k){var m,n,o,p=0,q="0",r=f&&[],s=[],t=h,v=f||e&&d.find.TAG("*",k),w=u+=null==t?1:Math.random()||.1,x=v.length;for(k&&(h=g!==l&&g);q!==x&&null!=(m=v[q]);q++){if(e&&m){n=0;while(o=a[n++])if(o(m,g,i)){j.push(m);break}k&&(u=w)}c&&((m=!o&&m)&&p--,f&&r.push(m))}if(p+=q,c&&q!==p){n=0;while(o=b[n++])o(r,s,g,i);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=E.call(j));s=sb(s)}G.apply(j,s),k&&!f&&s.length>0&&p+b.length>1&&db.uniqueSort(j)}return k&&(u=w,h=t),r};return c?fb(f):f}g=db.compile=function(a,b){var c,d=[],e=[],f=y[a+" "];if(!f){b||(b=ob(a)),c=b.length;while(c--)f=ub(b[c]),f[s]?d.push(f):e.push(f);f=y(a,vb(e,d))}return f};function wb(a,b,c){for(var d=0,e=b.length;e>d;d++)db(a,b[d],c);return c}function xb(a,b,e,f){var h,i,j,k,l,m=ob(a);if(!f&&1===m.length){if(i=m[0]=m[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&c.getById&&9===b.nodeType&&n&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(ab,bb),b)||[])[0],!b)return e;a=a.slice(i.shift().value.length)}h=V.needsContext.test(a)?0:i.length;while(h--){if(j=i[h],d.relative[k=j.type])break;if((l=d.find[k])&&(f=l(j.matches[0].replace(ab,bb),$.test(i[0].type)&&mb(b.parentNode)||b))){if(i.splice(h,1),a=f.length&&pb(i),!a)return G.apply(e,f),e;break}}}return g(a,m)(f,b,!n,e,$.test(a)&&mb(b.parentNode)||b),e}return c.sortStable=s.split("").sort(z).join("")===s,c.detectDuplicates=!!j,k(),c.sortDetached=gb(function(a){return 1&a.compareDocumentPosition(l.createElement("div"))}),gb(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||hb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&gb(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||hb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),gb(function(a){return null==a.getAttribute("disabled")})||hb(J,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),db}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return n.inArray(a,b)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;e>b;b++)if(n.contains(d[b],this))return!0}));for(b=0;e>b;b++)n.find(a,d[b],c);return c=this.pushStack(e>1?n.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=a.document,A=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,B=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:A.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:z,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=z.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return y.find(a);this.length=1,this[0]=d}return this.context=z,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};B.prototype=n.fn,y=n(z);var C=/^(?:parents|prev(?:Until|All))/,D={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!n(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b,c=n(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(n.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?n.inArray(this[0],n(a)):n.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function E(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return E(a,"nextSibling")},prev:function(a){return E(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return n.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(D[a]||(e=n.unique(e)),C.test(a)&&(e=e.reverse())),this.pushStack(e)}});var F=/\S+/g,G={};function H(a){var b=G[a]={};return n.each(a.match(F)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?G[a]||H(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&n.each(arguments,function(a,c){var d;while((d=n.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&n.isFunction(a.promise)?e:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){if(a===!0?!--n.readyWait:!n.isReady){if(!z.body)return setTimeout(n.ready);n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(z,[n]),n.fn.trigger&&n(z).trigger("ready").off("ready"))}}});function J(){z.addEventListener?(z.removeEventListener("DOMContentLoaded",K,!1),a.removeEventListener("load",K,!1)):(z.detachEvent("onreadystatechange",K),a.detachEvent("onload",K))}function K(){(z.addEventListener||"load"===event.type||"complete"===z.readyState)&&(J(),n.ready())}n.ready.promise=function(b){if(!I)if(I=n.Deferred(),"complete"===z.readyState)setTimeout(n.ready);else if(z.addEventListener)z.addEventListener("DOMContentLoaded",K,!1),a.addEventListener("load",K,!1);else{z.attachEvent("onreadystatechange",K),a.attachEvent("onload",K);var c=!1;try{c=null==a.frameElement&&z.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!n.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}J(),n.ready()}}()}return I.promise(b)};var L="undefined",M;for(M in n(l))break;l.ownLast="0"!==M,l.inlineBlockNeedsLayout=!1,n(function(){var a,b,c=z.getElementsByTagName("body")[0];c&&(a=z.createElement("div"),a.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",b=z.createElement("div"),c.appendChild(a).appendChild(b),typeof b.style.zoom!==L&&(b.style.cssText="border:0;margin:0;width:1px;padding:1px;display:inline;zoom:1",(l.inlineBlockNeedsLayout=3===b.offsetWidth)&&(c.style.zoom=1)),c.removeChild(a),a=b=null)}),function(){var a=z.createElement("div");if(null==l.deleteExpando){l.deleteExpando=!0;try{delete a.test}catch(b){l.deleteExpando=!1}}a=null}(),n.acceptData=function(a){var b=n.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(O,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}n.data(a,b,c)}else c=void 0}return c}function Q(a){var b;for(b in a)if(("data"!==b||!n.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function R(a,b,d,e){if(n.acceptData(a)){var f,g,h=n.expando,i=a.nodeType,j=i?n.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||n.guid++:h),j[k]||(j[k]=i?{}:{toJSON:n.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=n.extend(j[k],b):j[k].data=n.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[n.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[n.camelCase(b)])):f=g,f }}function S(a,b,c){if(n.acceptData(a)){var d,e,f=a.nodeType,g=f?n.cache:a,h=f?a[n.expando]:n.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){n.isArray(b)?b=b.concat(n.map(b,n.camelCase)):b in d?b=[b]:(b=n.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!Q(d):!n.isEmptyObject(d))return}(c||(delete g[h].data,Q(g[h])))&&(f?n.cleanData([a],!0):l.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}n.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?n.cache[a[n.expando]]:a[n.expando],!!a&&!Q(a)},data:function(a,b,c){return R(a,b,c)},removeData:function(a,b){return S(a,b)},_data:function(a,b,c){return R(a,b,c,!0)},_removeData:function(a,b){return S(a,b,!0)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=n.data(f),1===f.nodeType&&!n._data(f,"parsedAttrs"))){c=g.length;while(c--)d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d]));n._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){n.data(this,a)}):arguments.length>1?this.each(function(){n.data(this,a,b)}):f?P(f,a,n.data(f,a)):void 0},removeData:function(a){return this.each(function(){n.removeData(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=n._data(a,b),c&&(!d||n.isArray(c)?d=n._data(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return n._data(a,c)||n._data(a,c,{empty:n.Callbacks("once memory").add(function(){n._removeData(a,b+"queue"),n._removeData(a,c)})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=n._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var T=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,U=["Top","Right","Bottom","Left"],V=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)},W=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},X=/^(?:checkbox|radio)$/i;!function(){var a=z.createDocumentFragment(),b=z.createElement("div"),c=z.createElement("input");if(b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a>",l.leadingWhitespace=3===b.firstChild.nodeType,l.tbody=!b.getElementsByTagName("tbody").length,l.htmlSerialize=!!b.getElementsByTagName("link").length,l.html5Clone="<:nav></:nav>"!==z.createElement("nav").cloneNode(!0).outerHTML,c.type="checkbox",c.checked=!0,a.appendChild(c),l.appendChecked=c.checked,b.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,a.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,l.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){l.noCloneEvent=!1}),b.cloneNode(!0).click()),null==l.deleteExpando){l.deleteExpando=!0;try{delete b.test}catch(d){l.deleteExpando=!1}}a=b=c=null}(),function(){var b,c,d=z.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(l[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),l[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var Y=/^(?:input|select|textarea)$/i,Z=/^key/,$=/^(?:mouse|contextmenu)|click/,_=/^(?:focusinfocus|focusoutblur)$/,ab=/^([^.]*)(?:\.(.+)|)$/;function bb(){return!0}function cb(){return!1}function db(){try{return z.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=n.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof n===L||a&&n.event.triggered===a.type?void 0:n.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(F)||[""],h=b.length;while(h--)f=ab.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=n.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=n.event.special[o]||{},l=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},i),(m=g[o])||(m=g[o]=[],m.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,l):m.push(l),n.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n.hasData(a)&&n._data(a);if(r&&(k=r.events)){b=(b||"").match(F)||[""],j=b.length;while(j--)if(h=ab.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=m.length;while(f--)g=m[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(m.splice(f,1),g.selector&&m.delegateCount--,l.remove&&l.remove.call(a,g));i&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(k)&&(delete r.handle,n._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,m,o=[d||z],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||z,3!==d.nodeType&&8!==d.nodeType&&!_.test(p+n.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[n.expando]?b:new n.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),k=n.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!n.isWindow(d)){for(i=k.delegateType||p,_.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||z)&&o.push(l.defaultView||l.parentWindow||a)}m=0;while((h=o[m++])&&!b.isPropagationStopped())b.type=m>1?i:k.bindType||p,f=(n._data(h,"events")||{})[b.type]&&n._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&n.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&n.acceptData(d)&&g&&d[p]&&!n.isWindow(d)){l=d[g],l&&(d[g]=null),n.event.triggered=p;try{d[p]()}catch(r){}n.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(n._data(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((n.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?n(c,this).index(i)>=0:n.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[n.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=$.test(e)?this.mouseHooks:Z.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new n.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||z),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},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(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||z,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==db()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===db()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return n.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=n.extend(new n.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?n.event.trigger(e,null,b):n.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},n.removeEvent=z.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===L&&(a[d]=null),a.detachEvent(d,c))},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&(a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault())?bb:cb):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={isDefaultPrevented:cb,isPropagationStopped:cb,isImmediatePropagationStopped:cb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=bb,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=bb,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!n.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),l.submitBubbles||(n.event.special.submit={setup:function(){return n.nodeName(this,"form")?!1:void n.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=n.nodeName(b,"input")||n.nodeName(b,"button")?b.form:void 0;c&&!n._data(c,"submitBubbles")&&(n.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),n._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&n.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return n.nodeName(this,"form")?!1:void n.event.remove(this,"._submit")}}),l.changeBubbles||(n.event.special.change={setup:function(){return Y.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(n.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),n.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),n.event.simulate("change",this,a,!0)})),!1):void n.event.add(this,"beforeactivate._change",function(a){var b=a.target;Y.test(b.nodeName)&&!n._data(b,"changeBubbles")&&(n.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||n.event.simulate("change",this.parentNode,a,!0)}),n._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return n.event.remove(this,"._change"),!Y.test(this.nodeName)}}),l.focusinBubbles||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a),!0)};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=n._data(d,b);e||d.addEventListener(a,c,!0),n._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=n._data(d,b)-1;e?n._data(d,b,e):(d.removeEventListener(a,c,!0),n._removeData(d,b))}}}),n.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=cb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return n().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=n.guid++)),this.each(function(){n.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=cb),this.each(function(){n.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}});function eb(a){var b=fb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var fb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gb=/ jQuery\d+="(?:null|\d+)"/g,hb=new RegExp("<(?:"+fb+")[\\s/>]","i"),ib=/^\s+/,jb=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,kb=/<([\w:]+)/,lb=/<tbody/i,mb=/<|&#?\w+;/,nb=/<(?:script|style|link)/i,ob=/checked\s*(?:[^=]|=\s*.checked.)/i,pb=/^$|\/(?:java|ecma)script/i,qb=/^true\/(.*)/,rb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,sb={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>"],_default:l.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},tb=eb(z),ub=tb.appendChild(z.createElement("div"));sb.optgroup=sb.option,sb.tbody=sb.tfoot=sb.colgroup=sb.caption=sb.thead,sb.th=sb.td;function vb(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==L?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==L?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||n.nodeName(d,b)?f.push(d):n.merge(f,vb(d,b));return void 0===b||b&&n.nodeName(a,b)?n.merge([a],f):f}function wb(a){X.test(a.type)&&(a.defaultChecked=a.checked)}function xb(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function yb(a){return a.type=(null!==n.find.attr(a,"type"))+"/"+a.type,a}function zb(a){var b=qb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Ab(a,b){for(var c,d=0;null!=(c=a[d]);d++)n._data(c,"globalEval",!b||n._data(b[d],"globalEval"))}function Bb(a,b){if(1===b.nodeType&&n.hasData(a)){var c,d,e,f=n._data(a),g=n._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)n.event.add(b,c,h[c][d])}g.data&&(g.data=n.extend({},g.data))}}function Cb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!l.noCloneEvent&&b[n.expando]){e=n._data(b);for(d in e.events)n.removeEvent(b,d,e.handle);b.removeAttribute(n.expando)}"script"===c&&b.text!==a.text?(yb(b).text=a.text,zb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),l.html5Clone&&a.innerHTML&&!n.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&X.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}n.extend({clone:function(a,b,c){var d,e,f,g,h,i=n.contains(a.ownerDocument,a);if(l.html5Clone||n.isXMLDoc(a)||!hb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ub.innerHTML=a.outerHTML,ub.removeChild(f=ub.firstChild)),!(l.noCloneEvent&&l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(d=vb(f),h=vb(a),g=0;null!=(e=h[g]);++g)d[g]&&Cb(e,d[g]);if(b)if(c)for(h=h||vb(a),d=d||vb(f),g=0;null!=(e=h[g]);g++)Bb(e,d[g]);else Bb(a,f);return d=vb(f,"script"),d.length>0&&Ab(d,!i&&vb(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k,m=a.length,o=eb(b),p=[],q=0;m>q;q++)if(f=a[q],f||0===f)if("object"===n.type(f))n.merge(p,f.nodeType?[f]:f);else if(mb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(kb.exec(f)||["",""])[1].toLowerCase(),k=sb[i]||sb._default,h.innerHTML=k[1]+f.replace(jb,"<$1></$2>")+k[2],e=k[0];while(e--)h=h.lastChild;if(!l.leadingWhitespace&&ib.test(f)&&p.push(b.createTextNode(ib.exec(f)[0])),!l.tbody){f="table"!==i||lb.test(f)?"<table>"!==k[1]||lb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)n.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}n.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),l.appendChecked||n.grep(vb(p,"input"),wb),q=0;while(f=p[q++])if((!d||-1===n.inArray(f,d))&&(g=n.contains(f.ownerDocument,f),h=vb(o.appendChild(f),"script"),g&&Ab(h),c)){e=0;while(f=h[e++])pb.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=n.expando,j=n.cache,k=l.deleteExpando,m=n.event.special;null!=(d=a[h]);h++)if((b||n.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)m[e]?n.event.remove(d,e):n.removeEvent(d,e,g.handle);j[f]&&(delete j[f],k?delete d[i]:typeof d.removeAttribute!==L?d.removeAttribute(i):d[i]=null,c.push(f))}}}),n.fn.extend({text:function(a){return W(this,function(a){return void 0===a?n.text(this):this.empty().append((this[0]&&this[0].ownerDocument||z).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(vb(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&Ab(vb(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&n.cleanData(vb(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&n.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return W(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(gb,""):void 0;if(!("string"!=typeof a||nb.test(a)||!l.htmlSerialize&&hb.test(a)||!l.leadingWhitespace&&ib.test(a)||sb[(kb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(jb,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(vb(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,n.cleanData(vb(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,k=this.length,m=this,o=k-1,p=a[0],q=n.isFunction(p);if(q||k>1&&"string"==typeof p&&!l.checkClone&&ob.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(k&&(i=n.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=n.map(vb(i,"script"),yb),f=g.length;k>j;j++)d=i,j!==o&&(d=n.clone(d,!0,!0),f&&n.merge(g,vb(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,n.map(g,zb),j=0;f>j;j++)d=g[j],pb.test(d.type||"")&&!n._data(d,"globalEval")&&n.contains(h,d)&&(d.src?n._evalUrl&&n._evalUrl(d.src):n.globalEval((d.text||d.textContent||d.innerHTML||"").replace(rb,"")));i=c=null}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=0,e=[],g=n(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),n(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Db,Eb={};function Fb(b,c){var d=n(c.createElement(b)).appendTo(c.body),e=a.getDefaultComputedStyle?a.getDefaultComputedStyle(d[0]).display:n.css(d[0],"display");return d.detach(),e}function Gb(a){var b=z,c=Eb[a];return c||(c=Fb(a,b),"none"!==c&&c||(Db=(Db||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Db[0].contentWindow||Db[0].contentDocument).document,b.write(),b.close(),c=Fb(a,b),Db.detach()),Eb[a]=c),c}!function(){var a,b,c=z.createElement("div"),d="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";c.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=c.getElementsByTagName("a")[0],a.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(a.style.opacity),l.cssFloat=!!a.style.cssFloat,c.style.backgroundClip="content-box",c.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===c.style.backgroundClip,a=c=null,l.shrinkWrapBlocks=function(){var a,c,e,f;if(null==b){if(a=z.getElementsByTagName("body")[0],!a)return;f="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",c=z.createElement("div"),e=z.createElement("div"),a.appendChild(c).appendChild(e),b=!1,typeof e.style.zoom!==L&&(e.style.cssText=d+";width:1px;padding:1px;zoom:1",e.innerHTML="<div></div>",e.firstChild.style.width="5px",b=3!==e.offsetWidth),a.removeChild(c),a=c=e=null}return b}}();var Hb=/^margin/,Ib=new RegExp("^("+T+")(?!px)[a-z%]+$","i"),Jb,Kb,Lb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Jb=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),Ib.test(g)&&Hb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):z.documentElement.currentStyle&&(Jb=function(a){return a.currentStyle},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ib.test(g)&&!Lb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Mb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h=z.createElement("div"),i="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",j="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";h.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",b=h.getElementsByTagName("a")[0],b.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(b.style.opacity),l.cssFloat=!!b.style.cssFloat,h.style.backgroundClip="content-box",h.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===h.style.backgroundClip,b=h=null,n.extend(l,{reliableHiddenOffsets:function(){if(null!=c)return c;var a,b,d,e=z.createElement("div"),f=z.getElementsByTagName("body")[0];if(f)return e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=z.createElement("div"),a.style.cssText=i,f.appendChild(a).appendChild(e),e.innerHTML="<table><tr><td></td><td>t</td></tr></table>",b=e.getElementsByTagName("td"),b[0].style.cssText="padding:0;margin:0;border:0;display:none",d=0===b[0].offsetHeight,b[0].style.display="",b[1].style.display="none",c=d&&0===b[0].offsetHeight,f.removeChild(a),e=f=null,c},boxSizing:function(){return null==d&&k(),d},boxSizingReliable:function(){return null==e&&k(),e},pixelPosition:function(){return null==f&&k(),f},reliableMarginRight:function(){var b,c,d,e;if(null==g&&a.getComputedStyle){if(b=z.getElementsByTagName("body")[0],!b)return;c=z.createElement("div"),d=z.createElement("div"),c.style.cssText=i,b.appendChild(c).appendChild(d),e=d.appendChild(z.createElement("div")),e.style.cssText=d.style.cssText=j,e.style.marginRight=e.style.width="0",d.style.width="1px",g=!parseFloat((a.getComputedStyle(e,null)||{}).marginRight),b.removeChild(c)}return g}});function k(){var b,c,h=z.getElementsByTagName("body")[0];h&&(b=z.createElement("div"),c=z.createElement("div"),b.style.cssText=i,h.appendChild(b).appendChild(c),c.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:absolute;display:block;padding:1px;border:1px;width:4px;margin-top:1%;top:1%",n.swap(h,null!=h.style.zoom?{zoom:1}:{},function(){d=4===c.offsetWidth}),e=!0,f=!1,g=!0,a.getComputedStyle&&(f="1%"!==(a.getComputedStyle(c,null)||{}).top,e="4px"===(a.getComputedStyle(c,null)||{width:"4px"}).width),h.removeChild(b),c=h=null)}}(),n.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Nb=/alpha\([^)]*\)/i,Ob=/opacity\s*=\s*([^)]*)/,Pb=/^(none|table(?!-c[ea]).+)/,Qb=new RegExp("^("+T+")(.*)$","i"),Rb=new RegExp("^([+-])=("+T+")","i"),Sb={position:"absolute",visibility:"hidden",display:"block"},Tb={letterSpacing:0,fontWeight:400},Ub=["Webkit","O","Moz","ms"];function Vb(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ub.length;while(e--)if(b=Ub[e]+c,b in a)return b;return d}function Wb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=n._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&V(d)&&(f[g]=n._data(d,"olddisplay",Gb(d.nodeName)))):f[g]||(e=V(d),(c&&"none"!==c||!e)&&n._data(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Xb(a,b,c){var d=Qb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Yb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+U[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+U[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+U[f]+"Width",!0,e))):(g+=n.css(a,"padding"+U[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+U[f]+"Width",!0,e)));return g}function Zb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Jb(a),g=l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Kb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ib.test(e))return e;d=g&&(l.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Yb(a,b,c||(g?"border":"content"),d,f)+"px"}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Kb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":l.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;if(b=n.cssProps[h]||(n.cssProps[h]=Vb(i,h)),g=n.cssHooks[b]||n.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Rb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(n.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||n.cssNumber[h]||(c+="px"),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]="",i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Vb(a.style,h)),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Kb(a,b,d)),"normal"===f&&b in Tb&&(f=Tb[b]),""===c||c?(e=parseFloat(f),c===!0||n.isNumeric(e)?e||0:f):f}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?0===a.offsetWidth&&Pb.test(n.css(a,"display"))?n.swap(a,Sb,function(){return Zb(a,b,d)}):Zb(a,b,d):void 0},set:function(a,c,d){var e=d&&Jb(a);return Xb(a,c,d?Yb(a,b,d,l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),l.opacity||(n.cssHooks.opacity={get:function(a,b){return Ob.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=n.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===n.trim(f.replace(Nb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Nb.test(f)?f.replace(Nb,e):f+" "+e)}}),n.cssHooks.marginRight=Mb(l.reliableMarginRight,function(a,b){return b?n.swap(a,{display:"inline-block"},Kb,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+U[d]+b]=f[d]||f[d-2]||f[0];return e}},Hb.test(a)||(n.cssHooks[a+b].set=Xb)}),n.fn.extend({css:function(a,b){return W(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=Jb(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b) },a,b,arguments.length>1)},show:function(){return Wb(this,!0)},hide:function(){return Wb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){V(this)?n(this).show():n(this).hide()})}});function $b(a,b,c,d,e){return new $b.prototype.init(a,b,c,d,e)}n.Tween=$b,$b.prototype={constructor:$b,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=$b.propHooks[this.prop];return a&&a.get?a.get(this):$b.propHooks._default.get(this)},run:function(a){var b,c=$b.propHooks[this.prop];return this.pos=b=this.options.duration?n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):$b.propHooks._default.set(this),this}},$b.prototype.init.prototype=$b.prototype,$b.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[n.cssProps[a.prop]]||n.cssHooks[a.prop])?n.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},$b.propHooks.scrollTop=$b.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},n.fx=$b.prototype.init,n.fx.step={};var _b,ac,bc=/^(?:toggle|show|hide)$/,cc=new RegExp("^(?:([+-])=|)("+T+")([a-z%]*)$","i"),dc=/queueHooks$/,ec=[jc],fc={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=cc.exec(b),f=e&&e[3]||(n.cssNumber[a]?"":"px"),g=(n.cssNumber[a]||"px"!==f&&+d)&&cc.exec(n.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,n.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function gc(){return setTimeout(function(){_b=void 0}),_b=n.now()}function hc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=U[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function ic(a,b,c){for(var d,e=(fc[b]||[]).concat(fc["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function jc(a,b,c){var d,e,f,g,h,i,j,k,m=this,o={},p=a.style,q=a.nodeType&&V(a),r=n._data(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,m.always(function(){m.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=n.css(a,"display"),k=Gb(a.nodeName),"none"===j&&(j=k),"inline"===j&&"none"===n.css(a,"float")&&(l.inlineBlockNeedsLayout&&"inline"!==k?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",l.shrinkWrapBlocks()||m.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],bc.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||n.style(a,d)}if(!n.isEmptyObject(o)){r?"hidden"in r&&(q=r.hidden):r=n._data(a,"fxshow",{}),f&&(r.hidden=!q),q?n(a).show():m.done(function(){n(a).hide()}),m.done(function(){var b;n._removeData(a,"fxshow");for(b in o)n.style(a,b,o[b])});for(d in o)g=ic(q?r[d]:0,d,m),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function kc(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function lc(a,b,c){var d,e,f=0,g=ec.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=_b||gc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:_b||gc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(kc(k,j.opts.specialEasing);g>f;f++)if(d=ec[f].call(j,a,k,j.opts))return d;return n.map(k,ic,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(lc,{tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],fc[c]=fc[c]||[],fc[c].unshift(b)},prefilter:function(a,b){b?ec.unshift(a):ec.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(V).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=lc(this,n.extend({},a),f);(e||n._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=n._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&dc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=n._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(hc(b,!0),a,d,e)}}),n.each({slideDown:hc("show"),slideUp:hc("hide"),slideToggle:hc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=n.timers,c=0;for(_b=n.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||n.fx.stop(),_b=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){ac||(ac=setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){clearInterval(ac),ac=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(a,b){return a=n.fx?n.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e=z.createElement("div");e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=e.getElementsByTagName("a")[0],c=z.createElement("select"),d=c.appendChild(z.createElement("option")),b=e.getElementsByTagName("input")[0],a.style.cssText="top:1px",l.getSetAttribute="t"!==e.className,l.style=/top/.test(a.getAttribute("style")),l.hrefNormalized="/a"===a.getAttribute("href"),l.checkOn=!!b.value,l.optSelected=d.selected,l.enctype=!!z.createElement("form").enctype,c.disabled=!0,l.optDisabled=!d.disabled,b=z.createElement("input"),b.setAttribute("value",""),l.input=""===b.getAttribute("value"),b.value="t",b.setAttribute("type","radio"),l.radioValue="t"===b.value,a=b=c=d=e=null}();var mc=/\r/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(mc,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.text(a)}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(l.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)if(d=e[g],n.inArray(n.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>=0:void 0}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var nc,oc,pc=n.expr.attrHandle,qc=/^(?:checked|selected)$/i,rc=l.getSetAttribute,sc=l.input;n.fn.extend({attr:function(a,b){return W(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===L?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),d=n.attrHooks[b]||(n.expr.match.bool.test(b)?oc:nc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=n.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void n.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(F);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)?sc&&rc||!qc.test(c)?a[d]=!1:a[n.camelCase("default-"+c)]=a[d]=!1:n.attr(a,c,""),a.removeAttribute(rc?c:d)},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),oc={set:function(a,b,c){return b===!1?n.removeAttr(a,c):sc&&rc||!qc.test(c)?a.setAttribute(!rc&&n.propFix[c]||c,c):a[n.camelCase("default-"+c)]=a[c]=!0,c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=pc[b]||n.find.attr;pc[b]=sc&&rc||!qc.test(b)?function(a,b,d){var e,f;return d||(f=pc[b],pc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,pc[b]=f),e}:function(a,b,c){return c?void 0:a[n.camelCase("default-"+b)]?b.toLowerCase():null}}),sc&&rc||(n.attrHooks.value={set:function(a,b,c){return n.nodeName(a,"input")?void(a.defaultValue=b):nc&&nc.set(a,b,c)}}),rc||(nc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},pc.id=pc.name=pc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},n.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:nc.set},n.attrHooks.contenteditable={set:function(a,b,c){nc.set(a,""===b?!1:b,c)}},n.each(["width","height"],function(a,b){n.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),l.style||(n.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var tc=/^(?:input|select|textarea|button|object)$/i,uc=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return W(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return a=n.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),n.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!n.isXMLDoc(a),f&&(b=n.propFix[b]||b,e=n.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=n.find.attr(a,"tabindex");return b?parseInt(b,10):tc.test(a.nodeName)||uc.test(a.nodeName)&&a.href?0:-1}}}}),l.hrefNormalized||n.each(["href","src"],function(a,b){n.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this}),l.enctype||(n.propFix.enctype="encoding");var vc=/[\t\r\n\f]/g;n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=n.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?n.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(n.isFunction(a)?function(c){n(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=n(this),f=a.match(F)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===L||"boolean"===c)&&(this.className&&n._data(this,"__className__",this.className),this.className=this.className||a===!1?"":n._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(vc," ").indexOf(b)>=0)return!0;return!1}}),n.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(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var wc=n.now(),xc=/\?/,yc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;n.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=n.trim(b+"");return e&&!n.trim(e.replace(yc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():n.error("Invalid JSON: "+b)},n.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||n.error("Invalid XML: "+b),c};var zc,Ac,Bc=/#.*$/,Cc=/([?&])_=[^&]*/,Dc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Ec=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Fc=/^(?:GET|HEAD)$/,Gc=/^\/\//,Hc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Ic={},Jc={},Kc="*/".concat("*");try{Ac=location.href}catch(Lc){Ac=z.createElement("a"),Ac.href="",Ac=Ac.href}zc=Hc.exec(Ac.toLowerCase())||[];function Mc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(F)||[];if(n.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Nc(a,b,c,d){var e={},f=a===Jc;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Oc(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&n.extend(!0,a,c),a}function Pc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Qc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ac,type:"GET",isLocal:Ec.test(zc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Kc,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"},converters:{"* text":String,"text html":!0,"text json":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Oc(Oc(a,n.ajaxSettings),b):Oc(n.ajaxSettings,a)},ajaxPrefilter:Mc(Ic),ajaxTransport:Mc(Jc),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=n.ajaxSetup({},b),l=k.context||k,m=k.context&&(l.nodeType||l.jquery)?n(l):n.event,o=n.Deferred(),p=n.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Dc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||Ac)+"").replace(Bc,"").replace(Gc,zc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=n.trim(k.dataType||"*").toLowerCase().match(F)||[""],null==k.crossDomain&&(c=Hc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===zc[1]&&c[2]===zc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(zc[3]||("http:"===zc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=n.param(k.data,k.traditional)),Nc(Ic,k,b,v),2===t)return v;h=k.global,h&&0===n.active++&&n.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Fc.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(xc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Cc.test(e)?e.replace(Cc,"$1_="+wc++):e+(xc.test(e)?"&":"?")+"_="+wc++)),k.ifModified&&(n.lastModified[e]&&v.setRequestHeader("If-Modified-Since",n.lastModified[e]),n.etag[e]&&v.setRequestHeader("If-None-Match",n.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Kc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Nc(Jc,k,b,v)){v.readyState=1,h&&m.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Pc(k,v,c)),u=Qc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(n.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(n.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&m.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(m.trigger("ajaxComplete",[v,k]),--n.active||n.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){if(n.isFunction(a))return this.each(function(b){n(this).wrapAll(a.call(this,b))});if(this[0]){var b=n(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(n.isFunction(a)?function(b){n(this).wrapInner(a.call(this,b))}:function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!l.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||n.css(a,"display"))},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var Rc=/%20/g,Sc=/\[\]$/,Tc=/\r?\n/g,Uc=/^(?:submit|button|image|reset|file)$/i,Vc=/^(?:input|select|textarea|keygen)/i;function Wc(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||Sc.test(a)?d(a,e):Wc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Wc(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Wc(c,a[c],b,e);return d.join("&").replace(Rc,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&Vc.test(this.nodeName)&&!Uc.test(a)&&(this.checked||!X.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(Tc,"\r\n")}}):{name:b.name,value:c.replace(Tc,"\r\n")}}).get()}}),n.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&$c()||_c()}:$c;var Xc=0,Yc={},Zc=n.ajaxSettings.xhr();a.ActiveXObject&&n(a).on("unload",function(){for(var a in Yc)Yc[a](void 0,!0)}),l.cors=!!Zc&&"withCredentials"in Zc,Zc=l.ajax=!!Zc,Zc&&n.ajaxTransport(function(a){if(!a.crossDomain||l.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Xc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Yc[g],b=void 0,f.onreadystatechange=n.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Yc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function $c(){try{return new a.XMLHttpRequest}catch(b){}}function _c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=z.head||n("head")[0]||z.documentElement;return{send:function(d,e){b=z.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var ad=[],bd=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=ad.pop()||n.expando+"_"+wc++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(bd.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&bd.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(bd,"$1"+e):b.jsonp!==!1&&(b.url+=(xc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,ad.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||z;var d=v.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=n.buildFragment([a],b,e),e&&e.length&&n(e).remove(),n.merge([],d.childNodes))};var cd=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&cd)return cd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=a.slice(h,a.length),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&n.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};var dd=a.document.documentElement;function ed(a){return n.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&n.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,n.contains(b,e)?(typeof e.getBoundingClientRect!==L&&(d=e.getBoundingClientRect()),c=ed(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===n.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(c=a.offset()),c.top+=n.css(a[0],"borderTopWidth",!0),c.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-n.css(d,"marginTop",!0),left:b.left-c.left-n.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||dd;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||dd})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);n.fn[a]=function(d){return W(this,function(a,d,e){var f=ed(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?n(f).scrollLeft():e,c?e:n(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=Mb(l.pixelPosition,function(a,c){return c?(c=Kb(a,b),Ib.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return W(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var fd=a.jQuery,gd=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=gd),b&&a.jQuery===n&&(a.jQuery=fd),n},typeof b===L&&(a.jQuery=a.$=n),n});
assets/assets/bootstrap3-editable/bootstrap-editable.js
jeanlucS/Back-office_cas_pratique
/*! X-editable - v1.5.1 * In-place editing with Twitter Bootstrap, jQuery UI or pure jQuery * http://github.com/vitalets/x-editable * Copyright (c) 2013 Vitaliy Potapov; Licensed MIT */ /** Form with single input element, two buttons and two states: normal/loading. Applied as jQuery method to DIV tag (not to form tag!). This is because form can be in loading state when spinner shown. Editableform is linked with one of input types, e.g. 'text', 'select' etc. @class editableform @uses text @uses textarea **/ (function ($) { "use strict"; var EditableForm = function (div, options) { this.options = $.extend({}, $.fn.editableform.defaults, options); this.$div = $(div); //div, containing form. Not form tag. Not editable-element. if(!this.options.scope) { this.options.scope = this; } //nothing shown after init }; EditableForm.prototype = { constructor: EditableForm, initInput: function() { //called once //take input from options (as it is created in editable-element) this.input = this.options.input; //set initial value //todo: may be add check: typeof str === 'string' ? this.value = this.input.str2value(this.options.value); //prerender: get input.$input this.input.prerender(); }, initTemplate: function() { this.$form = $($.fn.editableform.template); }, initButtons: function() { var $btn = this.$form.find('.editable-buttons'); $btn.append($.fn.editableform.buttons); if(this.options.showbuttons === 'bottom') { $btn.addClass('editable-buttons-bottom'); } }, /** Renders editableform @method render **/ render: function() { //init loader this.$loading = $($.fn.editableform.loading); this.$div.empty().append(this.$loading); //init form template and buttons this.initTemplate(); if(this.options.showbuttons) { this.initButtons(); } else { this.$form.find('.editable-buttons').remove(); } //show loading state this.showLoading(); //flag showing is form now saving value to server. //It is needed to wait when closing form. this.isSaving = false; /** Fired when rendering starts @event rendering @param {Object} event event object **/ this.$div.triggerHandler('rendering'); //init input this.initInput(); //append input to form this.$form.find('div.editable-input').append(this.input.$tpl); //append form to container this.$div.append(this.$form); //render input $.when(this.input.render()) .then($.proxy(function () { //setup input to submit automatically when no buttons shown if(!this.options.showbuttons) { this.input.autosubmit(); } //attach 'cancel' handler this.$form.find('.editable-cancel').click($.proxy(this.cancel, this)); if(this.input.error) { this.error(this.input.error); this.$form.find('.editable-submit').attr('disabled', true); this.input.$input.attr('disabled', true); //prevent form from submitting this.$form.submit(function(e){ e.preventDefault(); }); } else { this.error(false); this.input.$input.removeAttr('disabled'); this.$form.find('.editable-submit').removeAttr('disabled'); var value = (this.value === null || this.value === undefined || this.value === '') ? this.options.defaultValue : this.value; this.input.value2input(value); //attach submit handler this.$form.submit($.proxy(this.submit, this)); } /** Fired when form is rendered @event rendered @param {Object} event event object **/ this.$div.triggerHandler('rendered'); this.showForm(); //call postrender method to perform actions required visibility of form if(this.input.postrender) { this.input.postrender(); } }, this)); }, cancel: function() { /** Fired when form was cancelled by user @event cancel @param {Object} event event object **/ this.$div.triggerHandler('cancel'); }, showLoading: function() { var w, h; if(this.$form) { //set loading size equal to form w = this.$form.outerWidth(); h = this.$form.outerHeight(); if(w) { this.$loading.width(w); } if(h) { this.$loading.height(h); } this.$form.hide(); } else { //stretch loading to fill container width w = this.$loading.parent().width(); if(w) { this.$loading.width(w); } } this.$loading.show(); }, showForm: function(activate) { this.$loading.hide(); this.$form.show(); if(activate !== false) { this.input.activate(); } /** Fired when form is shown @event show @param {Object} event event object **/ this.$div.triggerHandler('show'); }, error: function(msg) { var $group = this.$form.find('.control-group'), $block = this.$form.find('.editable-error-block'), lines; if(msg === false) { $group.removeClass($.fn.editableform.errorGroupClass); $block.removeClass($.fn.editableform.errorBlockClass).empty().hide(); } else { //convert newline to <br> for more pretty error display if(msg) { lines = (''+msg).split('\n'); for (var i = 0; i < lines.length; i++) { lines[i] = $('<div>').text(lines[i]).html(); } msg = lines.join('<br>'); } $group.addClass($.fn.editableform.errorGroupClass); $block.addClass($.fn.editableform.errorBlockClass).html(msg).show(); } }, submit: function(e) { e.stopPropagation(); e.preventDefault(); //get new value from input var newValue = this.input.input2value(); //validation: if validate returns string or truthy value - means error //if returns object like {newValue: '...'} => submitted value is reassigned to it var error = this.validate(newValue); if ($.type(error) === 'object' && error.newValue !== undefined) { newValue = error.newValue; this.input.value2input(newValue); if(typeof error.msg === 'string') { this.error(error.msg); this.showForm(); return; } } else if (error) { this.error(error); this.showForm(); return; } //if value not changed --> trigger 'nochange' event and return /*jslint eqeq: true*/ if (!this.options.savenochange && this.input.value2str(newValue) == this.input.value2str(this.value)) { /*jslint eqeq: false*/ /** Fired when value not changed but form is submitted. Requires savenochange = false. @event nochange @param {Object} event event object **/ this.$div.triggerHandler('nochange'); return; } //convert value for submitting to server var submitValue = this.input.value2submit(newValue); this.isSaving = true; //sending data to server $.when(this.save(submitValue)) .done($.proxy(function(response) { this.isSaving = false; //run success callback var res = typeof this.options.success === 'function' ? this.options.success.call(this.options.scope, response, newValue) : null; //if success callback returns false --> keep form open and do not activate input if(res === false) { this.error(false); this.showForm(false); return; } //if success callback returns string --> keep form open, show error and activate input if(typeof res === 'string') { this.error(res); this.showForm(); return; } //if success callback returns object like {newValue: <something>} --> use that value instead of submitted //it is usefull if you want to chnage value in url-function if(res && typeof res === 'object' && res.hasOwnProperty('newValue')) { newValue = res.newValue; } //clear error message this.error(false); this.value = newValue; /** Fired when form is submitted @event save @param {Object} event event object @param {Object} params additional params @param {mixed} params.newValue raw new value @param {mixed} params.submitValue submitted value as string @param {Object} params.response ajax response @example $('#form-div').on('save'), function(e, params){ if(params.newValue === 'username') {...} }); **/ this.$div.triggerHandler('save', {newValue: newValue, submitValue: submitValue, response: response}); }, this)) .fail($.proxy(function(xhr) { this.isSaving = false; var msg; if(typeof this.options.error === 'function') { msg = this.options.error.call(this.options.scope, xhr, newValue); } else { msg = typeof xhr === 'string' ? xhr : xhr.responseText || xhr.statusText || 'Unknown error!'; } this.error(msg); this.showForm(); }, this)); }, save: function(submitValue) { //try parse composite pk defined as json string in data-pk this.options.pk = $.fn.editableutils.tryParseJson(this.options.pk, true); var pk = (typeof this.options.pk === 'function') ? this.options.pk.call(this.options.scope) : this.options.pk, /* send on server in following cases: 1. url is function 2. url is string AND (pk defined OR send option = always) */ send = !!(typeof this.options.url === 'function' || (this.options.url && ((this.options.send === 'always') || (this.options.send === 'auto' && pk !== null && pk !== undefined)))), params; if (send) { //send to server this.showLoading(); //standard params params = { name: this.options.name || '', value: submitValue, pk: pk }; //additional params if(typeof this.options.params === 'function') { params = this.options.params.call(this.options.scope, params); } else { //try parse json in single quotes (from data-params attribute) this.options.params = $.fn.editableutils.tryParseJson(this.options.params, true); $.extend(params, this.options.params); } if(typeof this.options.url === 'function') { //user's function return this.options.url.call(this.options.scope, params); } else { //send ajax to server and return deferred object return $.ajax($.extend({ url : this.options.url, data : params, type : 'POST' }, this.options.ajaxOptions)); } } }, validate: function (value) { if (value === undefined) { value = this.value; } if (typeof this.options.validate === 'function') { return this.options.validate.call(this.options.scope, value); } }, option: function(key, value) { if(key in this.options) { this.options[key] = value; } if(key === 'value') { this.setValue(value); } //do not pass option to input as it is passed in editable-element }, setValue: function(value, convertStr) { if(convertStr) { this.value = this.input.str2value(value); } else { this.value = value; } //if form is visible, update input if(this.$form && this.$form.is(':visible')) { this.input.value2input(this.value); } } }; /* Initialize editableform. Applied to jQuery object. @method $().editableform(options) @params {Object} options @example var $form = $('&lt;div&gt;').editableform({ type: 'text', name: 'username', url: '/post', value: 'vitaliy' }); //to display form you should call 'render' method $form.editableform('render'); */ $.fn.editableform = function (option) { var args = arguments; return this.each(function () { var $this = $(this), data = $this.data('editableform'), options = typeof option === 'object' && option; if (!data) { $this.data('editableform', (data = new EditableForm(this, options))); } if (typeof option === 'string') { //call method data[option].apply(data, Array.prototype.slice.call(args, 1)); } }); }; //keep link to constructor to allow inheritance $.fn.editableform.Constructor = EditableForm; //defaults $.fn.editableform.defaults = { /* see also defaults for input */ /** Type of input. Can be <code>text|textarea|select|date|checklist</code> @property type @type string @default 'text' **/ type: 'text', /** Url for submit, e.g. <code>'/post'</code> If function - it will be called instead of ajax. Function should return deferred object to run fail/done callbacks. @property url @type string|function @default null @example url: function(params) { var d = new $.Deferred; if(params.value === 'abc') { return d.reject('error message'); //returning error via deferred object } else { //async saving data in js model someModel.asyncSaveMethod({ ..., success: function(){ d.resolve(); } }); return d.promise(); } } **/ url:null, /** Additional params for submit. If defined as <code>object</code> - it is **appended** to original ajax data (pk, name and value). If defined as <code>function</code> - returned object **overwrites** original ajax data. @example params: function(params) { //originally params contain pk, name and value params.a = 1; return params; } @property params @type object|function @default null **/ params:null, /** Name of field. Will be submitted on server. Can be taken from <code>id</code> attribute @property name @type string @default null **/ name: null, /** Primary key of editable object (e.g. record id in database). For composite keys use object, e.g. <code>{id: 1, lang: 'en'}</code>. Can be calculated dynamically via function. @property pk @type string|object|function @default null **/ pk: null, /** Initial value. If not defined - will be taken from element's content. For __select__ type should be defined (as it is ID of shown text). @property value @type string|object @default null **/ value: null, /** Value that will be displayed in input if original field value is empty (`null|undefined|''`). @property defaultValue @type string|object @default null @since 1.4.6 **/ defaultValue: null, /** Strategy for sending data on server. Can be `auto|always|never`. When 'auto' data will be sent on server **only if pk and url defined**, otherwise new value will be stored locally. @property send @type string @default 'auto' **/ send: 'auto', /** Function for client-side validation. If returns string - means validation not passed and string showed as error. Since 1.5.1 you can modify submitted value by returning object from `validate`: `{newValue: '...'}` or `{newValue: '...', msg: '...'}` @property validate @type function @default null @example validate: function(value) { if($.trim(value) == '') { return 'This field is required'; } } **/ validate: null, /** Success callback. Called when value successfully sent on server and **response status = 200**. Usefull to work with json response. For example, if your backend response can be <code>{success: true}</code> or <code>{success: false, msg: "server error"}</code> you can check it inside this callback. If it returns **string** - means error occured and string is shown as error message. If it returns **object like** <code>{newValue: &lt;something&gt;}</code> - it overwrites value, submitted by user. Otherwise newValue simply rendered into element. @property success @type function @default null @example success: function(response, newValue) { if(!response.success) return response.msg; } **/ success: null, /** Error callback. Called when request failed (response status != 200). Usefull when you want to parse error response and display a custom message. Must return **string** - the message to be displayed in the error block. @property error @type function @default null @since 1.4.4 @example error: function(response, newValue) { if(response.status === 500) { return 'Service unavailable. Please try later.'; } else { return response.responseText; } } **/ error: null, /** Additional options for submit ajax request. List of values: http://api.jquery.com/jQuery.ajax @property ajaxOptions @type object @default null @since 1.1.1 @example ajaxOptions: { type: 'put', dataType: 'json' } **/ ajaxOptions: null, /** Where to show buttons: left(true)|bottom|false Form without buttons is auto-submitted. @property showbuttons @type boolean|string @default true @since 1.1.1 **/ showbuttons: true, /** Scope for callback methods (success, validate). If <code>null</code> means editableform instance itself. @property scope @type DOMElement|object @default null @since 1.2.0 @private **/ scope: null, /** Whether to save or cancel value when it was not changed but form was submitted @property savenochange @type boolean @default false @since 1.2.0 **/ savenochange: false }; /* Note: following params could redefined in engine: bootstrap or jqueryui: Classes 'control-group' and 'editable-error-block' must always present! */ $.fn.editableform.template = '<form class="form-inline editableform">'+ '<div class="control-group">' + '<div><div class="editable-input"></div><div class="editable-buttons"></div></div>'+ '<div class="editable-error-block"></div>' + '</div>' + '</form>'; //loading div $.fn.editableform.loading = '<div class="editableform-loading"></div>'; //buttons $.fn.editableform.buttons = '<button type="submit" class="editable-submit">ok</button>'+ '<button type="button" class="editable-cancel">cancel</button>'; //error class attached to control-group $.fn.editableform.errorGroupClass = null; //error class attached to editable-error-block $.fn.editableform.errorBlockClass = 'editable-error'; //engine $.fn.editableform.engine = 'jquery'; }(window.jQuery)); /** * EditableForm utilites */ (function ($) { "use strict"; //utils $.fn.editableutils = { /** * classic JS inheritance function */ inherit: function (Child, Parent) { var F = function() { }; F.prototype = Parent.prototype; Child.prototype = new F(); Child.prototype.constructor = Child; Child.superclass = Parent.prototype; }, /** * set caret position in input * see http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area */ setCursorPosition: function(elem, pos) { if (elem.setSelectionRange) { elem.setSelectionRange(pos, pos); } else if (elem.createTextRange) { var range = elem.createTextRange(); range.collapse(true); range.moveEnd('character', pos); range.moveStart('character', pos); range.select(); } }, /** * function to parse JSON in *single* quotes. (jquery automatically parse only double quotes) * That allows such code as: <a data-source="{'a': 'b', 'c': 'd'}"> * safe = true --> means no exception will be thrown * for details see http://stackoverflow.com/questions/7410348/how-to-set-json-format-to-html5-data-attributes-in-the-jquery */ tryParseJson: function(s, safe) { if (typeof s === 'string' && s.length && s.match(/^[\{\[].*[\}\]]$/)) { if (safe) { try { /*jslint evil: true*/ s = (new Function('return ' + s))(); /*jslint evil: false*/ } catch (e) {} finally { return s; } } else { /*jslint evil: true*/ s = (new Function('return ' + s))(); /*jslint evil: false*/ } } return s; }, /** * slice object by specified keys */ sliceObj: function(obj, keys, caseSensitive /* default: false */) { var key, keyLower, newObj = {}; if (!$.isArray(keys) || !keys.length) { return newObj; } for (var i = 0; i < keys.length; i++) { key = keys[i]; if (obj.hasOwnProperty(key)) { newObj[key] = obj[key]; } if(caseSensitive === true) { continue; } //when getting data-* attributes via $.data() it's converted to lowercase. //details: http://stackoverflow.com/questions/7602565/using-data-attributes-with-jquery //workaround is code below. keyLower = key.toLowerCase(); if (obj.hasOwnProperty(keyLower)) { newObj[key] = obj[keyLower]; } } return newObj; }, /* exclude complex objects from $.data() before pass to config */ getConfigData: function($element) { var data = {}; $.each($element.data(), function(k, v) { if(typeof v !== 'object' || (v && typeof v === 'object' && (v.constructor === Object || v.constructor === Array))) { data[k] = v; } }); return data; }, /* returns keys of object */ objectKeys: function(o) { if (Object.keys) { return Object.keys(o); } else { if (o !== Object(o)) { throw new TypeError('Object.keys called on a non-object'); } var k=[], p; for (p in o) { if (Object.prototype.hasOwnProperty.call(o,p)) { k.push(p); } } return k; } }, /** method to escape html. **/ escape: function(str) { return $('<div>').text(str).html(); }, /* returns array items from sourceData having value property equal or inArray of 'value' */ itemsByValue: function(value, sourceData, valueProp) { if(!sourceData || value === null) { return []; } if (typeof(valueProp) !== "function") { var idKey = valueProp || 'value'; valueProp = function (e) { return e[idKey]; }; } var isValArray = $.isArray(value), result = [], that = this; $.each(sourceData, function(i, o) { if(o.children) { result = result.concat(that.itemsByValue(value, o.children, valueProp)); } else { /*jslint eqeq: true*/ if(isValArray) { if($.grep(value, function(v){ return v == (o && typeof o === 'object' ? valueProp(o) : o); }).length) { result.push(o); } } else { var itemValue = (o && (typeof o === 'object')) ? valueProp(o) : o; if(value == itemValue) { result.push(o); } } /*jslint eqeq: false*/ } }); return result; }, /* Returns input by options: type, mode. */ createInput: function(options) { var TypeConstructor, typeOptions, input, type = options.type; //`date` is some kind of virtual type that is transformed to one of exact types //depending on mode and core lib if(type === 'date') { //inline if(options.mode === 'inline') { if($.fn.editabletypes.datefield) { type = 'datefield'; } else if($.fn.editabletypes.dateuifield) { type = 'dateuifield'; } //popup } else { if($.fn.editabletypes.date) { type = 'date'; } else if($.fn.editabletypes.dateui) { type = 'dateui'; } } //if type still `date` and not exist in types, replace with `combodate` that is base input if(type === 'date' && !$.fn.editabletypes.date) { type = 'combodate'; } } //`datetime` should be datetimefield in 'inline' mode if(type === 'datetime' && options.mode === 'inline') { type = 'datetimefield'; } //change wysihtml5 to textarea for jquery UI and plain versions if(type === 'wysihtml5' && !$.fn.editabletypes[type]) { type = 'textarea'; } //create input of specified type. Input will be used for converting value, not in form if(typeof $.fn.editabletypes[type] === 'function') { TypeConstructor = $.fn.editabletypes[type]; typeOptions = this.sliceObj(options, this.objectKeys(TypeConstructor.defaults)); input = new TypeConstructor(typeOptions); return input; } else { $.error('Unknown type: '+ type); return false; } }, //see http://stackoverflow.com/questions/7264899/detect-css-transitions-using-javascript-and-without-modernizr supportsTransitions: function () { var b = document.body || document.documentElement, s = b.style, p = 'transition', v = ['Moz', 'Webkit', 'Khtml', 'O', 'ms']; if(typeof s[p] === 'string') { return true; } // Tests for vendor specific prop p = p.charAt(0).toUpperCase() + p.substr(1); for(var i=0; i<v.length; i++) { if(typeof s[v[i] + p] === 'string') { return true; } } return false; } }; }(window.jQuery)); /** Attaches stand-alone container with editable-form to HTML element. Element is used only for positioning, value is not stored anywhere.<br> This method applied internally in <code>$().editable()</code>. You should subscribe on it's events (save / cancel) to get profit of it.<br> Final realization can be different: bootstrap-popover, jqueryui-tooltip, poshytip, inline-div. It depends on which js file you include.<br> Applied as jQuery method. @class editableContainer @uses editableform **/ (function ($) { "use strict"; var Popup = function (element, options) { this.init(element, options); }; var Inline = function (element, options) { this.init(element, options); }; //methods Popup.prototype = { containerName: null, //method to call container on element containerDataName: null, //object name in element's .data() innerCss: null, //tbd in child class containerClass: 'editable-container editable-popup', //css class applied to container element defaults: {}, //container itself defaults init: function(element, options) { this.$element = $(element); //since 1.4.1 container do not use data-* directly as they already merged into options. this.options = $.extend({}, $.fn.editableContainer.defaults, options); this.splitOptions(); //set scope of form callbacks to element this.formOptions.scope = this.$element[0]; this.initContainer(); //flag to hide container, when saving value will finish this.delayedHide = false; //bind 'destroyed' listener to destroy container when element is removed from dom this.$element.on('destroyed', $.proxy(function(){ this.destroy(); }, this)); //attach document handler to close containers on click / escape if(!$(document).data('editable-handlers-attached')) { //close all on escape $(document).on('keyup.editable', function (e) { if (e.which === 27) { $('.editable-open').editableContainer('hide'); //todo: return focus on element } }); //close containers when click outside //(mousedown could be better than click, it closes everything also on drag drop) $(document).on('click.editable', function(e) { var $target = $(e.target), i, exclude_classes = ['.editable-container', '.ui-datepicker-header', '.datepicker', //in inline mode datepicker is rendered into body '.modal-backdrop', '.bootstrap-wysihtml5-insert-image-modal', '.bootstrap-wysihtml5-insert-link-modal' ]; //check if element is detached. It occurs when clicking in bootstrap datepicker if (!$.contains(document.documentElement, e.target)) { return; } //for some reason FF 20 generates extra event (click) in select2 widget with e.target = document //we need to filter it via construction below. See https://github.com/vitalets/x-editable/issues/199 //Possibly related to http://stackoverflow.com/questions/10119793/why-does-firefox-react-differently-from-webkit-and-ie-to-click-event-on-selec if($target.is(document)) { return; } //if click inside one of exclude classes --> no nothing for(i=0; i<exclude_classes.length; i++) { if($target.is(exclude_classes[i]) || $target.parents(exclude_classes[i]).length) { return; } } //close all open containers (except one - target) Popup.prototype.closeOthers(e.target); }); $(document).data('editable-handlers-attached', true); } }, //split options on containerOptions and formOptions splitOptions: function() { this.containerOptions = {}; this.formOptions = {}; if(!$.fn[this.containerName]) { throw new Error(this.containerName + ' not found. Have you included corresponding js file?'); } //keys defined in container defaults go to container, others go to form for(var k in this.options) { if(k in this.defaults) { this.containerOptions[k] = this.options[k]; } else { this.formOptions[k] = this.options[k]; } } }, /* Returns jquery object of container @method tip() */ tip: function() { return this.container() ? this.container().$tip : null; }, /* returns container object */ container: function() { var container; //first, try get it by `containerDataName` if(this.containerDataName) { if(container = this.$element.data(this.containerDataName)) { return container; } } //second, try `containerName` container = this.$element.data(this.containerName); return container; }, /* call native method of underlying container, e.g. this.$element.popover('method') */ call: function() { this.$element[this.containerName].apply(this.$element, arguments); }, initContainer: function(){ this.call(this.containerOptions); }, renderForm: function() { this.$form .editableform(this.formOptions) .on({ save: $.proxy(this.save, this), //click on submit button (value changed) nochange: $.proxy(function(){ this.hide('nochange'); }, this), //click on submit button (value NOT changed) cancel: $.proxy(function(){ this.hide('cancel'); }, this), //click on calcel button show: $.proxy(function() { if(this.delayedHide) { this.hide(this.delayedHide.reason); this.delayedHide = false; } else { this.setPosition(); } }, this), //re-position container every time form is shown (occurs each time after loading state) rendering: $.proxy(this.setPosition, this), //this allows to place container correctly when loading shown resize: $.proxy(this.setPosition, this), //this allows to re-position container when form size is changed rendered: $.proxy(function(){ /** Fired when container is shown and form is rendered (for select will wait for loading dropdown options). **Note:** Bootstrap popover has own `shown` event that now cannot be separated from x-editable's one. The workaround is to check `arguments.length` that is always `2` for x-editable. @event shown @param {Object} event event object @example $('#username').on('shown', function(e, editable) { editable.input.$input.val('overwriting value of input..'); }); **/ /* TODO: added second param mainly to distinguish from bootstrap's shown event. It's a hotfix that will be solved in future versions via namespaced events. */ this.$element.triggerHandler('shown', $(this.options.scope).data('editable')); }, this) }) .editableform('render'); }, /** Shows container with form @method show() @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true. **/ /* Note: poshytip owerwrites this method totally! */ show: function (closeAll) { this.$element.addClass('editable-open'); if(closeAll !== false) { //close all open containers (except this) this.closeOthers(this.$element[0]); } //show container itself this.innerShow(); this.tip().addClass(this.containerClass); /* Currently, form is re-rendered on every show. The main reason is that we dont know, what will container do with content when closed: remove(), detach() or just hide() - it depends on container. Detaching form itself before hide and re-insert before show is good solution, but visually it looks ugly --> container changes size before hide. */ //if form already exist - delete previous data if(this.$form) { //todo: destroy prev data! //this.$form.destroy(); } this.$form = $('<div>'); //insert form into container body if(this.tip().is(this.innerCss)) { //for inline container this.tip().append(this.$form); } else { this.tip().find(this.innerCss).append(this.$form); } //render form this.renderForm(); }, /** Hides container with form @method hide() @param {string} reason Reason caused hiding. Can be <code>save|cancel|onblur|nochange|undefined (=manual)</code> **/ hide: function(reason) { if(!this.tip() || !this.tip().is(':visible') || !this.$element.hasClass('editable-open')) { return; } //if form is saving value, schedule hide if(this.$form.data('editableform').isSaving) { this.delayedHide = {reason: reason}; return; } else { this.delayedHide = false; } this.$element.removeClass('editable-open'); this.innerHide(); /** Fired when container was hidden. It occurs on both save or cancel. **Note:** Bootstrap popover has own `hidden` event that now cannot be separated from x-editable's one. The workaround is to check `arguments.length` that is always `2` for x-editable. @event hidden @param {object} event event object @param {string} reason Reason caused hiding. Can be <code>save|cancel|onblur|nochange|manual</code> @example $('#username').on('hidden', function(e, reason) { if(reason === 'save' || reason === 'cancel') { //auto-open next editable $(this).closest('tr').next().find('.editable').editable('show'); } }); **/ this.$element.triggerHandler('hidden', reason || 'manual'); }, /* internal show method. To be overwritten in child classes */ innerShow: function () { }, /* internal hide method. To be overwritten in child classes */ innerHide: function () { }, /** Toggles container visibility (show / hide) @method toggle() @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true. **/ toggle: function(closeAll) { if(this.container() && this.tip() && this.tip().is(':visible')) { this.hide(); } else { this.show(closeAll); } }, /* Updates the position of container when content changed. @method setPosition() */ setPosition: function() { //tbd in child class }, save: function(e, params) { /** Fired when new value was submitted. You can use <code>$(this).data('editableContainer')</code> inside handler to access to editableContainer instance @event save @param {Object} event event object @param {Object} params additional params @param {mixed} params.newValue submitted value @param {Object} params.response ajax response @example $('#username').on('save', function(e, params) { //assuming server response: '{success: true}' var pk = $(this).data('editableContainer').options.pk; if(params.response && params.response.success) { alert('value: ' + params.newValue + ' with pk: ' + pk + ' saved!'); } else { alert('error!'); } }); **/ this.$element.triggerHandler('save', params); //hide must be after trigger, as saving value may require methods of plugin, applied to input this.hide('save'); }, /** Sets new option @method option(key, value) @param {string} key @param {mixed} value **/ option: function(key, value) { this.options[key] = value; if(key in this.containerOptions) { this.containerOptions[key] = value; this.setContainerOption(key, value); } else { this.formOptions[key] = value; if(this.$form) { this.$form.editableform('option', key, value); } } }, setContainerOption: function(key, value) { this.call('option', key, value); }, /** Destroys the container instance @method destroy() **/ destroy: function() { this.hide(); this.innerDestroy(); this.$element.off('destroyed'); this.$element.removeData('editableContainer'); }, /* to be overwritten in child classes */ innerDestroy: function() { }, /* Closes other containers except one related to passed element. Other containers can be cancelled or submitted (depends on onblur option) */ closeOthers: function(element) { $('.editable-open').each(function(i, el){ //do nothing with passed element and it's children if(el === element || $(el).find(element).length) { return; } //otherwise cancel or submit all open containers var $el = $(el), ec = $el.data('editableContainer'); if(!ec) { return; } if(ec.options.onblur === 'cancel') { $el.data('editableContainer').hide('onblur'); } else if(ec.options.onblur === 'submit') { $el.data('editableContainer').tip().find('form').submit(); } }); }, /** Activates input of visible container (e.g. set focus) @method activate() **/ activate: function() { if(this.tip && this.tip().is(':visible') && this.$form) { this.$form.data('editableform').input.activate(); } } }; /** jQuery method to initialize editableContainer. @method $().editableContainer(options) @params {Object} options @example $('#edit').editableContainer({ type: 'text', url: '/post', pk: 1, value: 'hello' }); **/ $.fn.editableContainer = function (option) { var args = arguments; return this.each(function () { var $this = $(this), dataKey = 'editableContainer', data = $this.data(dataKey), options = typeof option === 'object' && option, Constructor = (options.mode === 'inline') ? Inline : Popup; if (!data) { $this.data(dataKey, (data = new Constructor(this, options))); } if (typeof option === 'string') { //call method data[option].apply(data, Array.prototype.slice.call(args, 1)); } }); }; //store constructors $.fn.editableContainer.Popup = Popup; $.fn.editableContainer.Inline = Inline; //defaults $.fn.editableContainer.defaults = { /** Initial value of form input @property value @type mixed @default null @private **/ value: null, /** Placement of container relative to element. Can be <code>top|right|bottom|left</code>. Not used for inline container. @property placement @type string @default 'top' **/ placement: 'top', /** Whether to hide container on save/cancel. @property autohide @type boolean @default true @private **/ autohide: true, /** Action when user clicks outside the container. Can be <code>cancel|submit|ignore</code>. Setting <code>ignore</code> allows to have several containers open. @property onblur @type string @default 'cancel' @since 1.1.1 **/ onblur: 'cancel', /** Animation speed (inline mode only) @property anim @type string @default false **/ anim: false, /** Mode of editable, can be `popup` or `inline` @property mode @type string @default 'popup' @since 1.4.0 **/ mode: 'popup' }; /* * workaround to have 'destroyed' event to destroy popover when element is destroyed * see http://stackoverflow.com/questions/2200494/jquery-trigger-event-when-an-element-is-removed-from-the-dom */ jQuery.event.special.destroyed = { remove: function(o) { if (o.handler) { o.handler(); } } }; }(window.jQuery)); /** * Editable Inline * --------------------- */ (function ($) { "use strict"; //copy prototype from EditableContainer //extend methods $.extend($.fn.editableContainer.Inline.prototype, $.fn.editableContainer.Popup.prototype, { containerName: 'editableform', innerCss: '.editable-inline', containerClass: 'editable-container editable-inline', //css class applied to container element initContainer: function(){ //container is <span> element this.$tip = $('<span></span>'); //convert anim to miliseconds (int) if(!this.options.anim) { this.options.anim = 0; } }, splitOptions: function() { //all options are passed to form this.containerOptions = {}; this.formOptions = this.options; }, tip: function() { return this.$tip; }, innerShow: function () { this.$element.hide(); this.tip().insertAfter(this.$element).show(); }, innerHide: function () { this.$tip.hide(this.options.anim, $.proxy(function() { this.$element.show(); this.innerDestroy(); }, this)); }, innerDestroy: function() { if(this.tip()) { this.tip().empty().remove(); } } }); }(window.jQuery)); /** Makes editable any HTML element on the page. Applied as jQuery method. @class editable @uses editableContainer **/ (function ($) { "use strict"; var Editable = function (element, options) { this.$element = $(element); //data-* has more priority over js options: because dynamically created elements may change data-* this.options = $.extend({}, $.fn.editable.defaults, options, $.fn.editableutils.getConfigData(this.$element)); if(this.options.selector) { this.initLive(); } else { this.init(); } //check for transition support if(this.options.highlight && !$.fn.editableutils.supportsTransitions()) { this.options.highlight = false; } }; Editable.prototype = { constructor: Editable, init: function () { var isValueByText = false, doAutotext, finalize; //name this.options.name = this.options.name || this.$element.attr('id'); //create input of specified type. Input needed already here to convert value for initial display (e.g. show text by id for select) //also we set scope option to have access to element inside input specific callbacks (e. g. source as function) this.options.scope = this.$element[0]; this.input = $.fn.editableutils.createInput(this.options); if(!this.input) { return; } //set value from settings or by element's text if (this.options.value === undefined || this.options.value === null) { this.value = this.input.html2value($.trim(this.$element.html())); isValueByText = true; } else { /* value can be string when received from 'data-value' attribute for complext objects value can be set as json string in data-value attribute, e.g. data-value="{city: 'Moscow', street: 'Lenina'}" */ this.options.value = $.fn.editableutils.tryParseJson(this.options.value, true); if(typeof this.options.value === 'string') { this.value = this.input.str2value(this.options.value); } else { this.value = this.options.value; } } //add 'editable' class to every editable element this.$element.addClass('editable'); //specifically for "textarea" add class .editable-pre-wrapped to keep linebreaks if(this.input.type === 'textarea') { this.$element.addClass('editable-pre-wrapped'); } //attach handler activating editable. In disabled mode it just prevent default action (useful for links) if(this.options.toggle !== 'manual') { this.$element.addClass('editable-click'); this.$element.on(this.options.toggle + '.editable', $.proxy(function(e){ //prevent following link if editable enabled if(!this.options.disabled) { e.preventDefault(); } //stop propagation not required because in document click handler it checks event target //e.stopPropagation(); if(this.options.toggle === 'mouseenter') { //for hover only show container this.show(); } else { //when toggle='click' we should not close all other containers as they will be closed automatically in document click listener var closeAll = (this.options.toggle !== 'click'); this.toggle(closeAll); } }, this)); } else { this.$element.attr('tabindex', -1); //do not stop focus on element when toggled manually } //if display is function it's far more convinient to have autotext = always to render correctly on init //see https://github.com/vitalets/x-editable-yii/issues/34 if(typeof this.options.display === 'function') { this.options.autotext = 'always'; } //check conditions for autotext: switch(this.options.autotext) { case 'always': doAutotext = true; break; case 'auto': //if element text is empty and value is defined and value not generated by text --> run autotext doAutotext = !$.trim(this.$element.text()).length && this.value !== null && this.value !== undefined && !isValueByText; break; default: doAutotext = false; } //depending on autotext run render() or just finilize init $.when(doAutotext ? this.render() : true).then($.proxy(function() { if(this.options.disabled) { this.disable(); } else { this.enable(); } /** Fired when element was initialized by `$().editable()` method. Please note that you should setup `init` handler **before** applying `editable`. @event init @param {Object} event event object @param {Object} editable editable instance (as here it cannot accessed via data('editable')) @since 1.2.0 @example $('#username').on('init', function(e, editable) { alert('initialized ' + editable.options.name); }); $('#username').editable(); **/ this.$element.triggerHandler('init', this); }, this)); }, /* Initializes parent element for live editables */ initLive: function() { //store selector var selector = this.options.selector; //modify options for child elements this.options.selector = false; this.options.autotext = 'never'; //listen toggle events this.$element.on(this.options.toggle + '.editable', selector, $.proxy(function(e){ var $target = $(e.target); if(!$target.data('editable')) { //if delegated element initially empty, we need to clear it's text (that was manually set to `empty` by user) //see https://github.com/vitalets/x-editable/issues/137 if($target.hasClass(this.options.emptyclass)) { $target.empty(); } $target.editable(this.options).trigger(e); } }, this)); }, /* Renders value into element's text. Can call custom display method from options. Can return deferred object. @method render() @param {mixed} response server response (if exist) to pass into display function */ render: function(response) { //do not display anything if(this.options.display === false) { return; } //if input has `value2htmlFinal` method, we pass callback in third param to be called when source is loaded if(this.input.value2htmlFinal) { return this.input.value2html(this.value, this.$element[0], this.options.display, response); //if display method defined --> use it } else if(typeof this.options.display === 'function') { return this.options.display.call(this.$element[0], this.value, response); //else use input's original value2html() method } else { return this.input.value2html(this.value, this.$element[0]); } }, /** Enables editable @method enable() **/ enable: function() { this.options.disabled = false; this.$element.removeClass('editable-disabled'); this.handleEmpty(this.isEmpty); if(this.options.toggle !== 'manual') { if(this.$element.attr('tabindex') === '-1') { this.$element.removeAttr('tabindex'); } } }, /** Disables editable @method disable() **/ disable: function() { this.options.disabled = true; this.hide(); this.$element.addClass('editable-disabled'); this.handleEmpty(this.isEmpty); //do not stop focus on this element this.$element.attr('tabindex', -1); }, /** Toggles enabled / disabled state of editable element @method toggleDisabled() **/ toggleDisabled: function() { if(this.options.disabled) { this.enable(); } else { this.disable(); } }, /** Sets new option @method option(key, value) @param {string|object} key option name or object with several options @param {mixed} value option new value @example $('.editable').editable('option', 'pk', 2); **/ option: function(key, value) { //set option(s) by object if(key && typeof key === 'object') { $.each(key, $.proxy(function(k, v){ this.option($.trim(k), v); }, this)); return; } //set option by string this.options[key] = value; //disabled if(key === 'disabled') { return value ? this.disable() : this.enable(); } //value if(key === 'value') { this.setValue(value); } //transfer new option to container! if(this.container) { this.container.option(key, value); } //pass option to input directly (as it points to the same in form) if(this.input.option) { this.input.option(key, value); } }, /* * set emptytext if element is empty */ handleEmpty: function (isEmpty) { //do not handle empty if we do not display anything if(this.options.display === false) { return; } /* isEmpty may be set directly as param of method. It is required when we enable/disable field and can't rely on content as node content is text: "Empty" that is not empty %) */ if(isEmpty !== undefined) { this.isEmpty = isEmpty; } else { //detect empty //for some inputs we need more smart check //e.g. wysihtml5 may have <br>, <p></p>, <img> if(typeof(this.input.isEmpty) === 'function') { this.isEmpty = this.input.isEmpty(this.$element); } else { this.isEmpty = $.trim(this.$element.html()) === ''; } } //emptytext shown only for enabled if(!this.options.disabled) { if (this.isEmpty) { this.$element.html(this.options.emptytext); if(this.options.emptyclass) { this.$element.addClass(this.options.emptyclass); } } else if(this.options.emptyclass) { this.$element.removeClass(this.options.emptyclass); } } else { //below required if element disable property was changed if(this.isEmpty) { this.$element.empty(); if(this.options.emptyclass) { this.$element.removeClass(this.options.emptyclass); } } } }, /** Shows container with form @method show() @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true. **/ show: function (closeAll) { if(this.options.disabled) { return; } //init editableContainer: popover, tooltip, inline, etc.. if(!this.container) { var containerOptions = $.extend({}, this.options, { value: this.value, input: this.input //pass input to form (as it is already created) }); this.$element.editableContainer(containerOptions); //listen `save` event this.$element.on("save.internal", $.proxy(this.save, this)); this.container = this.$element.data('editableContainer'); } else if(this.container.tip().is(':visible')) { return; } //show container this.container.show(closeAll); }, /** Hides container with form @method hide() **/ hide: function () { if(this.container) { this.container.hide(); } }, /** Toggles container visibility (show / hide) @method toggle() @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true. **/ toggle: function(closeAll) { if(this.container && this.container.tip().is(':visible')) { this.hide(); } else { this.show(closeAll); } }, /* * called when form was submitted */ save: function(e, params) { //mark element with unsaved class if needed if(this.options.unsavedclass) { /* Add unsaved css to element if: - url is not user's function - value was not sent to server - params.response === undefined, that means data was not sent - value changed */ var sent = false; sent = sent || typeof this.options.url === 'function'; sent = sent || this.options.display === false; sent = sent || params.response !== undefined; sent = sent || (this.options.savenochange && this.input.value2str(this.value) !== this.input.value2str(params.newValue)); if(sent) { this.$element.removeClass(this.options.unsavedclass); } else { this.$element.addClass(this.options.unsavedclass); } } //highlight when saving if(this.options.highlight) { var $e = this.$element, bgColor = $e.css('background-color'); $e.css('background-color', this.options.highlight); setTimeout(function(){ if(bgColor === 'transparent') { bgColor = ''; } $e.css('background-color', bgColor); $e.addClass('editable-bg-transition'); setTimeout(function(){ $e.removeClass('editable-bg-transition'); }, 1700); }, 10); } //set new value this.setValue(params.newValue, false, params.response); /** Fired when new value was submitted. You can use <code>$(this).data('editable')</code> to access to editable instance @event save @param {Object} event event object @param {Object} params additional params @param {mixed} params.newValue submitted value @param {Object} params.response ajax response @example $('#username').on('save', function(e, params) { alert('Saved value: ' + params.newValue); }); **/ //event itself is triggered by editableContainer. Description here is only for documentation }, validate: function () { if (typeof this.options.validate === 'function') { return this.options.validate.call(this, this.value); } }, /** Sets new value of editable @method setValue(value, convertStr) @param {mixed} value new value @param {boolean} convertStr whether to convert value from string to internal format **/ setValue: function(value, convertStr, response) { if(convertStr) { this.value = this.input.str2value(value); } else { this.value = value; } if(this.container) { this.container.option('value', this.value); } $.when(this.render(response)) .then($.proxy(function() { this.handleEmpty(); }, this)); }, /** Activates input of visible container (e.g. set focus) @method activate() **/ activate: function() { if(this.container) { this.container.activate(); } }, /** Removes editable feature from element @method destroy() **/ destroy: function() { this.disable(); if(this.container) { this.container.destroy(); } this.input.destroy(); if(this.options.toggle !== 'manual') { this.$element.removeClass('editable-click'); this.$element.off(this.options.toggle + '.editable'); } this.$element.off("save.internal"); this.$element.removeClass('editable editable-open editable-disabled'); this.$element.removeData('editable'); } }; /* EDITABLE PLUGIN DEFINITION * ======================= */ /** jQuery method to initialize editable element. @method $().editable(options) @params {Object} options @example $('#username').editable({ type: 'text', url: '/post', pk: 1 }); **/ $.fn.editable = function (option) { //special API methods returning non-jquery object var result = {}, args = arguments, datakey = 'editable'; switch (option) { /** Runs client-side validation for all matched editables @method validate() @returns {Object} validation errors map @example $('#username, #fullname').editable('validate'); // possible result: { username: "username is required", fullname: "fullname should be minimum 3 letters length" } **/ case 'validate': this.each(function () { var $this = $(this), data = $this.data(datakey), error; if (data && (error = data.validate())) { result[data.options.name] = error; } }); return result; /** Returns current values of editable elements. Note that it returns an **object** with name-value pairs, not a value itself. It allows to get data from several elements. If value of some editable is `null` or `undefined` it is excluded from result object. When param `isSingle` is set to **true** - it is supposed you have single element and will return value of editable instead of object. @method getValue() @param {bool} isSingle whether to return just value of single element @returns {Object} object of element names and values @example $('#username, #fullname').editable('getValue'); //result: { username: "superuser", fullname: "John" } //isSingle = true $('#username').editable('getValue', true); //result "superuser" **/ case 'getValue': if(arguments.length === 2 && arguments[1] === true) { //isSingle = true result = this.eq(0).data(datakey).value; } else { this.each(function () { var $this = $(this), data = $this.data(datakey); if (data && data.value !== undefined && data.value !== null) { result[data.options.name] = data.input.value2submit(data.value); } }); } return result; /** This method collects values from several editable elements and submit them all to server. Internally it runs client-side validation for all fields and submits only in case of success. See <a href="#newrecord">creating new records</a> for details. Since 1.5.1 `submit` can be applied to single element to send data programmatically. In that case `url`, `success` and `error` is taken from initial options and you can just call `$('#username').editable('submit')`. @method submit(options) @param {object} options @param {object} options.url url to submit data @param {object} options.data additional data to submit @param {object} options.ajaxOptions additional ajax options @param {function} options.error(obj) error handler @param {function} options.success(obj,config) success handler @returns {Object} jQuery object **/ case 'submit': //collects value, validate and submit to server for creating new record var config = arguments[1] || {}, $elems = this, errors = this.editable('validate'); // validation ok if($.isEmptyObject(errors)) { var ajaxOptions = {}; // for single element use url, success etc from options if($elems.length === 1) { var editable = $elems.data('editable'); //standard params var params = { name: editable.options.name || '', value: editable.input.value2submit(editable.value), pk: (typeof editable.options.pk === 'function') ? editable.options.pk.call(editable.options.scope) : editable.options.pk }; //additional params if(typeof editable.options.params === 'function') { params = editable.options.params.call(editable.options.scope, params); } else { //try parse json in single quotes (from data-params attribute) editable.options.params = $.fn.editableutils.tryParseJson(editable.options.params, true); $.extend(params, editable.options.params); } ajaxOptions = { url: editable.options.url, data: params, type: 'POST' }; // use success / error from options config.success = config.success || editable.options.success; config.error = config.error || editable.options.error; // multiple elements } else { var values = this.editable('getValue'); ajaxOptions = { url: config.url, data: values, type: 'POST' }; } // ajax success callabck (response 200 OK) ajaxOptions.success = typeof config.success === 'function' ? function(response) { config.success.call($elems, response, config); } : $.noop; // ajax error callabck ajaxOptions.error = typeof config.error === 'function' ? function() { config.error.apply($elems, arguments); } : $.noop; // extend ajaxOptions if(config.ajaxOptions) { $.extend(ajaxOptions, config.ajaxOptions); } // extra data if(config.data) { $.extend(ajaxOptions.data, config.data); } // perform ajax request $.ajax(ajaxOptions); } else { //client-side validation error if(typeof config.error === 'function') { config.error.call($elems, errors); } } return this; } //return jquery object return this.each(function () { var $this = $(this), data = $this.data(datakey), options = typeof option === 'object' && option; //for delegated targets do not store `editable` object for element //it's allows several different selectors. //see: https://github.com/vitalets/x-editable/issues/312 if(options && options.selector) { data = new Editable(this, options); return; } if (!data) { $this.data(datakey, (data = new Editable(this, options))); } if (typeof option === 'string') { //call method data[option].apply(data, Array.prototype.slice.call(args, 1)); } }); }; $.fn.editable.defaults = { /** Type of input. Can be <code>text|textarea|select|date|checklist</code> and more @property type @type string @default 'text' **/ type: 'text', /** Sets disabled state of editable @property disabled @type boolean @default false **/ disabled: false, /** How to toggle editable. Can be <code>click|dblclick|mouseenter|manual</code>. When set to <code>manual</code> you should manually call <code>show/hide</code> methods of editable. **Note**: if you call <code>show</code> or <code>toggle</code> inside **click** handler of some DOM element, you need to apply <code>e.stopPropagation()</code> because containers are being closed on any click on document. @example $('#edit-button').click(function(e) { e.stopPropagation(); $('#username').editable('toggle'); }); @property toggle @type string @default 'click' **/ toggle: 'click', /** Text shown when element is empty. @property emptytext @type string @default 'Empty' **/ emptytext: 'Empty', /** Allows to automatically set element's text based on it's value. Can be <code>auto|always|never</code>. Useful for select and date. For example, if dropdown list is <code>{1: 'a', 2: 'b'}</code> and element's value set to <code>1</code>, it's html will be automatically set to <code>'a'</code>. <code>auto</code> - text will be automatically set only if element is empty. <code>always|never</code> - always(never) try to set element's text. @property autotext @type string @default 'auto' **/ autotext: 'auto', /** Initial value of input. If not set, taken from element's text. Note, that if element's text is empty - text is automatically generated from value and can be customized (see `autotext` option). For example, to display currency sign: @example <a id="price" data-type="text" data-value="100"></a> <script> $('#price').editable({ ... display: function(value) { $(this).text(value + '$'); } }) </script> @property value @type mixed @default element's text **/ value: null, /** Callback to perform custom displaying of value in element's text. If `null`, default input's display used. If `false`, no displaying methods will be called, element's text will never change. Runs under element's scope. _**Parameters:**_ * `value` current value to be displayed * `response` server response (if display called after ajax submit), since 1.4.0 For _inputs with source_ (select, checklist) parameters are different: * `value` current value to be displayed * `sourceData` array of items for current input (e.g. dropdown items) * `response` server response (if display called after ajax submit), since 1.4.0 To get currently selected items use `$.fn.editableutils.itemsByValue(value, sourceData)`. @property display @type function|boolean @default null @since 1.2.0 @example display: function(value, sourceData) { //display checklist as comma-separated values var html = [], checked = $.fn.editableutils.itemsByValue(value, sourceData); if(checked.length) { $.each(checked, function(i, v) { html.push($.fn.editableutils.escape(v.text)); }); $(this).html(html.join(', ')); } else { $(this).empty(); } } **/ display: null, /** Css class applied when editable text is empty. @property emptyclass @type string @since 1.4.1 @default editable-empty **/ emptyclass: 'editable-empty', /** Css class applied when value was stored but not sent to server (`pk` is empty or `send = 'never'`). You may set it to `null` if you work with editables locally and submit them together. @property unsavedclass @type string @since 1.4.1 @default editable-unsaved **/ unsavedclass: 'editable-unsaved', /** If selector is provided, editable will be delegated to the specified targets. Usefull for dynamically generated DOM elements. **Please note**, that delegated targets can't be initialized with `emptytext` and `autotext` options, as they actually become editable only after first click. You should manually set class `editable-click` to these elements. Also, if element originally empty you should add class `editable-empty`, set `data-value=""` and write emptytext into element: @property selector @type string @since 1.4.1 @default null @example <div id="user"> <!-- empty --> <a href="#" data-name="username" data-type="text" class="editable-click editable-empty" data-value="" title="Username">Empty</a> <!-- non-empty --> <a href="#" data-name="group" data-type="select" data-source="/groups" data-value="1" class="editable-click" title="Group">Operator</a> </div> <script> $('#user').editable({ selector: 'a', url: '/post', pk: 1 }); </script> **/ selector: null, /** Color used to highlight element after update. Implemented via CSS3 transition, works in modern browsers. @property highlight @type string|boolean @since 1.4.5 @default #FFFF80 **/ highlight: '#FFFF80' }; }(window.jQuery)); /** AbstractInput - base class for all editable inputs. It defines interface to be implemented by any input type. To create your own input you can inherit from this class. @class abstractinput **/ (function ($) { "use strict"; //types $.fn.editabletypes = {}; var AbstractInput = function () { }; AbstractInput.prototype = { /** Initializes input @method init() **/ init: function(type, options, defaults) { this.type = type; this.options = $.extend({}, defaults, options); }, /* this method called before render to init $tpl that is inserted in DOM */ prerender: function() { this.$tpl = $(this.options.tpl); //whole tpl as jquery object this.$input = this.$tpl; //control itself, can be changed in render method this.$clear = null; //clear button this.error = null; //error message, if input cannot be rendered }, /** Renders input from tpl. Can return jQuery deferred object. Can be overwritten in child objects @method render() **/ render: function() { }, /** Sets element's html by value. @method value2html(value, element) @param {mixed} value @param {DOMElement} element **/ value2html: function(value, element) { $(element)[this.options.escape ? 'text' : 'html']($.trim(value)); }, /** Converts element's html to value @method html2value(html) @param {string} html @returns {mixed} **/ html2value: function(html) { return $('<div>').html(html).text(); }, /** Converts value to string (for internal compare). For submitting to server used value2submit(). @method value2str(value) @param {mixed} value @returns {string} **/ value2str: function(value) { return value; }, /** Converts string received from server into value. Usually from `data-value` attribute. @method str2value(str) @param {string} str @returns {mixed} **/ str2value: function(str) { return str; }, /** Converts value for submitting to server. Result can be string or object. @method value2submit(value) @param {mixed} value @returns {mixed} **/ value2submit: function(value) { return value; }, /** Sets value of input. @method value2input(value) @param {mixed} value **/ value2input: function(value) { this.$input.val(value); }, /** Returns value of input. Value can be object (e.g. datepicker) @method input2value() **/ input2value: function() { return this.$input.val(); }, /** Activates input. For text it sets focus. @method activate() **/ activate: function() { if(this.$input.is(':visible')) { this.$input.focus(); } }, /** Creates input. @method clear() **/ clear: function() { this.$input.val(null); }, /** method to escape html. **/ escape: function(str) { return $('<div>').text(str).html(); }, /** attach handler to automatically submit form when value changed (useful when buttons not shown) **/ autosubmit: function() { }, /** Additional actions when destroying element **/ destroy: function() { }, // -------- helper functions -------- setClass: function() { if(this.options.inputclass) { this.$input.addClass(this.options.inputclass); } }, setAttr: function(attr) { if (this.options[attr] !== undefined && this.options[attr] !== null) { this.$input.attr(attr, this.options[attr]); } }, option: function(key, value) { this.options[key] = value; } }; AbstractInput.defaults = { /** HTML template of input. Normally you should not change it. @property tpl @type string @default '' **/ tpl: '', /** CSS class automatically applied to input @property inputclass @type string @default null **/ inputclass: null, /** If `true` - html will be escaped in content of element via $.text() method. If `false` - html will not be escaped, $.html() used. When you use own `display` function, this option obviosly has no effect. @property escape @type boolean @since 1.5.0 @default true **/ escape: true, //scope for external methods (e.g. source defined as function) //for internal use only scope: null, //need to re-declare showbuttons here to get it's value from common config (passed only options existing in defaults) showbuttons: true }; $.extend($.fn.editabletypes, {abstractinput: AbstractInput}); }(window.jQuery)); /** List - abstract class for inputs that have source option loaded from js array or via ajax @class list @extends abstractinput **/ (function ($) { "use strict"; var List = function (options) { }; $.fn.editableutils.inherit(List, $.fn.editabletypes.abstractinput); $.extend(List.prototype, { render: function () { var deferred = $.Deferred(); this.error = null; this.onSourceReady(function () { this.renderList(); deferred.resolve(); }, function () { this.error = this.options.sourceError; deferred.resolve(); }); return deferred.promise(); }, html2value: function (html) { return null; //can't set value by text }, value2html: function (value, element, display, response) { var deferred = $.Deferred(), success = function () { if(typeof display === 'function') { //custom display method display.call(element, value, this.sourceData, response); } else { this.value2htmlFinal(value, element); } deferred.resolve(); }; //for null value just call success without loading source if(value === null) { success.call(this); } else { this.onSourceReady(success, function () { deferred.resolve(); }); } return deferred.promise(); }, // ------------- additional functions ------------ onSourceReady: function (success, error) { //run source if it function var source; if ($.isFunction(this.options.source)) { source = this.options.source.call(this.options.scope); this.sourceData = null; //note: if function returns the same source as URL - sourceData will be taken from cahce and no extra request performed } else { source = this.options.source; } //if allready loaded just call success if(this.options.sourceCache && $.isArray(this.sourceData)) { success.call(this); return; } //try parse json in single quotes (for double quotes jquery does automatically) try { source = $.fn.editableutils.tryParseJson(source, false); } catch (e) { error.call(this); return; } //loading from url if (typeof source === 'string') { //try to get sourceData from cache if(this.options.sourceCache) { var cacheID = source, cache; if (!$(document).data(cacheID)) { $(document).data(cacheID, {}); } cache = $(document).data(cacheID); //check for cached data if (cache.loading === false && cache.sourceData) { //take source from cache this.sourceData = cache.sourceData; this.doPrepend(); success.call(this); return; } else if (cache.loading === true) { //cache is loading, put callback in stack to be called later cache.callbacks.push($.proxy(function () { this.sourceData = cache.sourceData; this.doPrepend(); success.call(this); }, this)); //also collecting error callbacks cache.err_callbacks.push($.proxy(error, this)); return; } else { //no cache yet, activate it cache.loading = true; cache.callbacks = []; cache.err_callbacks = []; } } //ajaxOptions for source. Can be overwritten bt options.sourceOptions var ajaxOptions = $.extend({ url: source, type: 'get', cache: false, dataType: 'json', success: $.proxy(function (data) { if(cache) { cache.loading = false; } this.sourceData = this.makeArray(data); if($.isArray(this.sourceData)) { if(cache) { //store result in cache cache.sourceData = this.sourceData; //run success callbacks for other fields waiting for this source $.each(cache.callbacks, function () { this.call(); }); } this.doPrepend(); success.call(this); } else { error.call(this); if(cache) { //run error callbacks for other fields waiting for this source $.each(cache.err_callbacks, function () { this.call(); }); } } }, this), error: $.proxy(function () { error.call(this); if(cache) { cache.loading = false; //run error callbacks for other fields $.each(cache.err_callbacks, function () { this.call(); }); } }, this) }, this.options.sourceOptions); //loading sourceData from server $.ajax(ajaxOptions); } else { //options as json/array this.sourceData = this.makeArray(source); if($.isArray(this.sourceData)) { this.doPrepend(); success.call(this); } else { error.call(this); } } }, doPrepend: function () { if(this.options.prepend === null || this.options.prepend === undefined) { return; } if(!$.isArray(this.prependData)) { //run prepend if it is function (once) if ($.isFunction(this.options.prepend)) { this.options.prepend = this.options.prepend.call(this.options.scope); } //try parse json in single quotes this.options.prepend = $.fn.editableutils.tryParseJson(this.options.prepend, true); //convert prepend from string to object if (typeof this.options.prepend === 'string') { this.options.prepend = {'': this.options.prepend}; } this.prependData = this.makeArray(this.options.prepend); } if($.isArray(this.prependData) && $.isArray(this.sourceData)) { this.sourceData = this.prependData.concat(this.sourceData); } }, /* renders input list */ renderList: function() { // this method should be overwritten in child class }, /* set element's html by value */ value2htmlFinal: function(value, element) { // this method should be overwritten in child class }, /** * convert data to array suitable for sourceData, e.g. [{value: 1, text: 'abc'}, {...}] */ makeArray: function(data) { var count, obj, result = [], item, iterateItem; if(!data || typeof data === 'string') { return null; } if($.isArray(data)) { //array /* function to iterate inside item of array if item is object. Caclulates count of keys in item and store in obj. */ iterateItem = function (k, v) { obj = {value: k, text: v}; if(count++ >= 2) { return false;// exit from `each` if item has more than one key. } }; for(var i = 0; i < data.length; i++) { item = data[i]; if(typeof item === 'object') { count = 0; //count of keys inside item $.each(item, iterateItem); //case: [{val1: 'text1'}, {val2: 'text2} ...] if(count === 1) { result.push(obj); //case: [{value: 1, text: 'text1'}, {value: 2, text: 'text2'}, ...] } else if(count > 1) { //removed check of existance: item.hasOwnProperty('value') && item.hasOwnProperty('text') if(item.children) { item.children = this.makeArray(item.children); } result.push(item); } } else { //case: ['text1', 'text2' ...] result.push({value: item, text: item}); } } } else { //case: {val1: 'text1', val2: 'text2, ...} $.each(data, function (k, v) { result.push({value: k, text: v}); }); } return result; }, option: function(key, value) { this.options[key] = value; if(key === 'source') { this.sourceData = null; } if(key === 'prepend') { this.prependData = null; } } }); List.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** Source data for list. If **array** - it should be in format: `[{value: 1, text: "text1"}, {value: 2, text: "text2"}, ...]` For compability, object format is also supported: `{"1": "text1", "2": "text2" ...}` but it does not guarantee elements order. If **string** - considered ajax url to load items. In that case results will be cached for fields with the same source and name. See also `sourceCache` option. If **function**, it should return data in format above (since 1.4.0). Since 1.4.1 key `children` supported to render OPTGROUP (for **select** input only). `[{text: "group1", children: [{value: 1, text: "text1"}, {value: 2, text: "text2"}]}, ...]` @property source @type string | array | object | function @default null **/ source: null, /** Data automatically prepended to the beginning of dropdown list. @property prepend @type string | array | object | function @default false **/ prepend: false, /** Error message when list cannot be loaded (e.g. ajax error) @property sourceError @type string @default Error when loading list **/ sourceError: 'Error when loading list', /** if <code>true</code> and source is **string url** - results will be cached for fields with the same source. Usefull for editable column in grid to prevent extra requests. @property sourceCache @type boolean @default true @since 1.2.0 **/ sourceCache: true, /** Additional ajax options to be used in $.ajax() when loading list from server. Useful to send extra parameters (`data` key) or change request method (`type` key). @property sourceOptions @type object|function @default null @since 1.5.0 **/ sourceOptions: null }); $.fn.editabletypes.list = List; }(window.jQuery)); /** Text input @class text @extends abstractinput @final @example <a href="#" id="username" data-type="text" data-pk="1">awesome</a> <script> $(function(){ $('#username').editable({ url: '/post', title: 'Enter username' }); }); </script> **/ (function ($) { "use strict"; var Text = function (options) { this.init('text', options, Text.defaults); }; $.fn.editableutils.inherit(Text, $.fn.editabletypes.abstractinput); $.extend(Text.prototype, { render: function() { this.renderClear(); this.setClass(); this.setAttr('placeholder'); }, activate: function() { if(this.$input.is(':visible')) { this.$input.focus(); $.fn.editableutils.setCursorPosition(this.$input.get(0), this.$input.val().length); if(this.toggleClear) { this.toggleClear(); } } }, //render clear button renderClear: function() { if (this.options.clear) { this.$clear = $('<span class="editable-clear-x"></span>'); this.$input.after(this.$clear) .css('padding-right', 24) .keyup($.proxy(function(e) { //arrows, enter, tab, etc if(~$.inArray(e.keyCode, [40,38,9,13,27])) { return; } clearTimeout(this.t); var that = this; this.t = setTimeout(function() { that.toggleClear(e); }, 100); }, this)) .parent().css('position', 'relative'); this.$clear.click($.proxy(this.clear, this)); } }, postrender: function() { /* //now `clear` is positioned via css if(this.$clear) { //can position clear button only here, when form is shown and height can be calculated // var h = this.$input.outerHeight(true) || 20, var h = this.$clear.parent().height(), delta = (h - this.$clear.height()) / 2; //this.$clear.css({bottom: delta, right: delta}); } */ }, //show / hide clear button toggleClear: function(e) { if(!this.$clear) { return; } var len = this.$input.val().length, visible = this.$clear.is(':visible'); if(len && !visible) { this.$clear.show(); } if(!len && visible) { this.$clear.hide(); } }, clear: function() { this.$clear.hide(); this.$input.val('').focus(); } }); Text.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <input type="text"> **/ tpl: '<input type="text">', /** Placeholder attribute of input. Shown when input is empty. @property placeholder @type string @default null **/ placeholder: null, /** Whether to show `clear` button @property clear @type boolean @default true **/ clear: true }); $.fn.editabletypes.text = Text; }(window.jQuery)); /** Textarea input @class textarea @extends abstractinput @final @example <a href="#" id="comments" data-type="textarea" data-pk="1">awesome comment!</a> <script> $(function(){ $('#comments').editable({ url: '/post', title: 'Enter comments', rows: 10 }); }); </script> **/ (function ($) { "use strict"; var Textarea = function (options) { this.init('textarea', options, Textarea.defaults); }; $.fn.editableutils.inherit(Textarea, $.fn.editabletypes.abstractinput); $.extend(Textarea.prototype, { render: function () { this.setClass(); this.setAttr('placeholder'); this.setAttr('rows'); //ctrl + enter this.$input.keydown(function (e) { if (e.ctrlKey && e.which === 13) { $(this).closest('form').submit(); } }); }, //using `white-space: pre-wrap` solves \n <--> BR conversion very elegant! /* value2html: function(value, element) { var html = '', lines; if(value) { lines = value.split("\n"); for (var i = 0; i < lines.length; i++) { lines[i] = $('<div>').text(lines[i]).html(); } html = lines.join('<br>'); } $(element).html(html); }, html2value: function(html) { if(!html) { return ''; } var regex = new RegExp(String.fromCharCode(10), 'g'); var lines = html.split(/<br\s*\/?>/i); for (var i = 0; i < lines.length; i++) { var text = $('<div>').html(lines[i]).text(); // Remove newline characters (\n) to avoid them being converted by value2html() method // thus adding extra <br> tags text = text.replace(regex, ''); lines[i] = text; } return lines.join("\n"); }, */ activate: function() { $.fn.editabletypes.text.prototype.activate.call(this); } }); Textarea.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <textarea></textarea> **/ tpl:'<textarea></textarea>', /** @property inputclass @default input-large **/ inputclass: 'input-large', /** Placeholder attribute of input. Shown when input is empty. @property placeholder @type string @default null **/ placeholder: null, /** Number of rows in textarea @property rows @type integer @default 7 **/ rows: 7 }); $.fn.editabletypes.textarea = Textarea; }(window.jQuery)); /** Select (dropdown) @class select @extends list @final @example <a href="#" id="status" data-type="select" data-pk="1" data-url="/post" data-title="Select status"></a> <script> $(function(){ $('#status').editable({ value: 2, source: [ {value: 1, text: 'Active'}, {value: 2, text: 'Blocked'}, {value: 3, text: 'Deleted'} ] }); }); </script> **/ (function ($) { "use strict"; var Select = function (options) { this.init('select', options, Select.defaults); }; $.fn.editableutils.inherit(Select, $.fn.editabletypes.list); $.extend(Select.prototype, { renderList: function() { this.$input.empty(); var fillItems = function($el, data) { var attr; if($.isArray(data)) { for(var i=0; i<data.length; i++) { attr = {}; if(data[i].children) { attr.label = data[i].text; $el.append(fillItems($('<optgroup>', attr), data[i].children)); } else { attr.value = data[i].value; if(data[i].disabled) { attr.disabled = true; } $el.append($('<option>', attr).text(data[i].text)); } } } return $el; }; fillItems(this.$input, this.sourceData); this.setClass(); //enter submit this.$input.on('keydown.editable', function (e) { if (e.which === 13) { $(this).closest('form').submit(); } }); }, value2htmlFinal: function(value, element) { var text = '', items = $.fn.editableutils.itemsByValue(value, this.sourceData); if(items.length) { text = items[0].text; } //$(element).text(text); $.fn.editabletypes.abstractinput.prototype.value2html.call(this, text, element); }, autosubmit: function() { this.$input.off('keydown.editable').on('change.editable', function(){ $(this).closest('form').submit(); }); } }); Select.defaults = $.extend({}, $.fn.editabletypes.list.defaults, { /** @property tpl @default <select></select> **/ tpl:'<select></select>' }); $.fn.editabletypes.select = Select; }(window.jQuery)); /** List of checkboxes. Internally value stored as javascript array of values. @class checklist @extends list @final @example <a href="#" id="options" data-type="checklist" data-pk="1" data-url="/post" data-title="Select options"></a> <script> $(function(){ $('#options').editable({ value: [2, 3], source: [ {value: 1, text: 'option1'}, {value: 2, text: 'option2'}, {value: 3, text: 'option3'} ] }); }); </script> **/ (function ($) { "use strict"; var Checklist = function (options) { this.init('checklist', options, Checklist.defaults); }; $.fn.editableutils.inherit(Checklist, $.fn.editabletypes.list); $.extend(Checklist.prototype, { renderList: function() { var $label, $div; this.$tpl.empty(); if(!$.isArray(this.sourceData)) { return; } for(var i=0; i<this.sourceData.length; i++) { $label = $('<label>').append($('<input>', { type: 'checkbox', value: this.sourceData[i].value })) .append($('<span>').text(' '+this.sourceData[i].text)); $('<div>').append($label).appendTo(this.$tpl); } this.$input = this.$tpl.find('input[type="checkbox"]'); this.setClass(); }, value2str: function(value) { return $.isArray(value) ? value.sort().join($.trim(this.options.separator)) : ''; }, //parse separated string str2value: function(str) { var reg, value = null; if(typeof str === 'string' && str.length) { reg = new RegExp('\\s*'+$.trim(this.options.separator)+'\\s*'); value = str.split(reg); } else if($.isArray(str)) { value = str; } else { value = [str]; } return value; }, //set checked on required checkboxes value2input: function(value) { this.$input.prop('checked', false); if($.isArray(value) && value.length) { this.$input.each(function(i, el) { var $el = $(el); // cannot use $.inArray as it performs strict comparison $.each(value, function(j, val){ /*jslint eqeq: true*/ if($el.val() == val) { /*jslint eqeq: false*/ $el.prop('checked', true); } }); }); } }, input2value: function() { var checked = []; this.$input.filter(':checked').each(function(i, el) { checked.push($(el).val()); }); return checked; }, //collect text of checked boxes value2htmlFinal: function(value, element) { var html = [], checked = $.fn.editableutils.itemsByValue(value, this.sourceData), escape = this.options.escape; if(checked.length) { $.each(checked, function(i, v) { var text = escape ? $.fn.editableutils.escape(v.text) : v.text; html.push(text); }); $(element).html(html.join('<br>')); } else { $(element).empty(); } }, activate: function() { this.$input.first().focus(); }, autosubmit: function() { this.$input.on('keydown', function(e){ if (e.which === 13) { $(this).closest('form').submit(); } }); } }); Checklist.defaults = $.extend({}, $.fn.editabletypes.list.defaults, { /** @property tpl @default <div></div> **/ tpl:'<div class="editable-checklist"></div>', /** @property inputclass @type string @default null **/ inputclass: null, /** Separator of values when reading from `data-value` attribute @property separator @type string @default ',' **/ separator: ',' }); $.fn.editabletypes.checklist = Checklist; }(window.jQuery)); /** HTML5 input types. Following types are supported: * password * email * url * tel * number * range * time Learn more about html5 inputs: http://www.w3.org/wiki/HTML5_form_additions To check browser compatibility please see: https://developer.mozilla.org/en-US/docs/HTML/Element/Input @class html5types @extends text @final @since 1.3.0 @example <a href="#" id="email" data-type="email" data-pk="1">[email protected]</a> <script> $(function(){ $('#email').editable({ url: '/post', title: 'Enter email' }); }); </script> **/ /** @property tpl @default depends on type **/ /* Password */ (function ($) { "use strict"; var Password = function (options) { this.init('password', options, Password.defaults); }; $.fn.editableutils.inherit(Password, $.fn.editabletypes.text); $.extend(Password.prototype, { //do not display password, show '[hidden]' instead value2html: function(value, element) { if(value) { $(element).text('[hidden]'); } else { $(element).empty(); } }, //as password not displayed, should not set value by html html2value: function(html) { return null; } }); Password.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="password">' }); $.fn.editabletypes.password = Password; }(window.jQuery)); /* Email */ (function ($) { "use strict"; var Email = function (options) { this.init('email', options, Email.defaults); }; $.fn.editableutils.inherit(Email, $.fn.editabletypes.text); Email.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="email">' }); $.fn.editabletypes.email = Email; }(window.jQuery)); /* Url */ (function ($) { "use strict"; var Url = function (options) { this.init('url', options, Url.defaults); }; $.fn.editableutils.inherit(Url, $.fn.editabletypes.text); Url.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="url">' }); $.fn.editabletypes.url = Url; }(window.jQuery)); /* Tel */ (function ($) { "use strict"; var Tel = function (options) { this.init('tel', options, Tel.defaults); }; $.fn.editableutils.inherit(Tel, $.fn.editabletypes.text); Tel.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="tel">' }); $.fn.editabletypes.tel = Tel; }(window.jQuery)); /* Number */ (function ($) { "use strict"; var NumberInput = function (options) { this.init('number', options, NumberInput.defaults); }; $.fn.editableutils.inherit(NumberInput, $.fn.editabletypes.text); $.extend(NumberInput.prototype, { render: function () { NumberInput.superclass.render.call(this); this.setAttr('min'); this.setAttr('max'); this.setAttr('step'); }, postrender: function() { if(this.$clear) { //increase right ffset for up/down arrows this.$clear.css({right: 24}); /* //can position clear button only here, when form is shown and height can be calculated var h = this.$input.outerHeight(true) || 20, delta = (h - this.$clear.height()) / 2; //add 12px to offset right for up/down arrows this.$clear.css({top: delta, right: delta + 16}); */ } } }); NumberInput.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="number">', inputclass: 'input-mini', min: null, max: null, step: null }); $.fn.editabletypes.number = NumberInput; }(window.jQuery)); /* Range (inherit from number) */ (function ($) { "use strict"; var Range = function (options) { this.init('range', options, Range.defaults); }; $.fn.editableutils.inherit(Range, $.fn.editabletypes.number); $.extend(Range.prototype, { render: function () { this.$input = this.$tpl.filter('input'); this.setClass(); this.setAttr('min'); this.setAttr('max'); this.setAttr('step'); this.$input.on('input', function(){ $(this).siblings('output').text($(this).val()); }); }, activate: function() { this.$input.focus(); } }); Range.defaults = $.extend({}, $.fn.editabletypes.number.defaults, { tpl: '<input type="range"><output style="width: 30px; display: inline-block"></output>', inputclass: 'input-medium' }); $.fn.editabletypes.range = Range; }(window.jQuery)); /* Time */ (function ($) { "use strict"; var Time = function (options) { this.init('time', options, Time.defaults); }; //inherit from abstract, as inheritance from text gives selection error. $.fn.editableutils.inherit(Time, $.fn.editabletypes.abstractinput); $.extend(Time.prototype, { render: function() { this.setClass(); } }); Time.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { tpl: '<input type="time">' }); $.fn.editabletypes.time = Time; }(window.jQuery)); /** Select2 input. Based on amazing work of Igor Vaynberg https://github.com/ivaynberg/select2. Please see [original select2 docs](http://ivaynberg.github.com/select2) for detailed description and options. You should manually download and include select2 distributive: <link href="select2/select2.css" rel="stylesheet" type="text/css"></link> <script src="select2/select2.js"></script> To make it **bootstrap-styled** you can use css from [here](https://github.com/t0m/select2-bootstrap-css): <link href="select2-bootstrap.css" rel="stylesheet" type="text/css"></link> **Note:** currently `autotext` feature does not work for select2 with `ajax` remote source. You need initially put both `data-value` and element's text youself: <a href="#" data-type="select2" data-value="1">Text1</a> @class select2 @extends abstractinput @since 1.4.1 @final @example <a href="#" id="country" data-type="select2" data-pk="1" data-value="ru" data-url="/post" data-title="Select country"></a> <script> $(function(){ //local source $('#country').editable({ source: [ {id: 'gb', text: 'Great Britain'}, {id: 'us', text: 'United States'}, {id: 'ru', text: 'Russia'} ], select2: { multiple: true } }); //remote source (simple) $('#country').editable({ source: '/getCountries', select2: { placeholder: 'Select Country', minimumInputLength: 1 } }); //remote source (advanced) $('#country').editable({ select2: { placeholder: 'Select Country', allowClear: true, minimumInputLength: 3, id: function (item) { return item.CountryId; }, ajax: { url: '/getCountries', dataType: 'json', data: function (term, page) { return { query: term }; }, results: function (data, page) { return { results: data }; } }, formatResult: function (item) { return item.CountryName; }, formatSelection: function (item) { return item.CountryName; }, initSelection: function (element, callback) { return $.get('/getCountryById', { query: element.val() }, function (data) { callback(data); }); } } }); }); </script> **/ (function ($) { "use strict"; var Constructor = function (options) { this.init('select2', options, Constructor.defaults); options.select2 = options.select2 || {}; this.sourceData = null; //placeholder if(options.placeholder) { options.select2.placeholder = options.placeholder; } //if not `tags` mode, use source if(!options.select2.tags && options.source) { var source = options.source; //if source is function, call it (once!) if ($.isFunction(options.source)) { source = options.source.call(options.scope); } if (typeof source === 'string') { options.select2.ajax = options.select2.ajax || {}; //some default ajax params if(!options.select2.ajax.data) { options.select2.ajax.data = function(term) {return { query:term };}; } if(!options.select2.ajax.results) { options.select2.ajax.results = function(data) { return {results:data };}; } options.select2.ajax.url = source; } else { //check format and convert x-editable format to select2 format (if needed) this.sourceData = this.convertSource(source); options.select2.data = this.sourceData; } } //overriding objects in config (as by default jQuery extend() is not recursive) this.options.select2 = $.extend({}, Constructor.defaults.select2, options.select2); //detect whether it is multi-valued this.isMultiple = this.options.select2.tags || this.options.select2.multiple; this.isRemote = ('ajax' in this.options.select2); //store function returning ID of item //should be here as used inautotext for local source this.idFunc = this.options.select2.id; if (typeof(this.idFunc) !== "function") { var idKey = this.idFunc || 'id'; this.idFunc = function (e) { return e[idKey]; }; } //store function that renders text in select2 this.formatSelection = this.options.select2.formatSelection; if (typeof(this.formatSelection) !== "function") { this.formatSelection = function (e) { return e.text; }; } }; $.fn.editableutils.inherit(Constructor, $.fn.editabletypes.abstractinput); $.extend(Constructor.prototype, { render: function() { this.setClass(); //can not apply select2 here as it calls initSelection //over input that does not have correct value yet. //apply select2 only in value2input //this.$input.select2(this.options.select2); //when data is loaded via ajax, we need to know when it's done to populate listData if(this.isRemote) { //listen to loaded event to populate data this.$input.on('select2-loaded', $.proxy(function(e) { this.sourceData = e.items.results; }, this)); } //trigger resize of editableform to re-position container in multi-valued mode if(this.isMultiple) { this.$input.on('change', function() { $(this).closest('form').parent().triggerHandler('resize'); }); } }, value2html: function(value, element) { var text = '', data, that = this; if(this.options.select2.tags) { //in tags mode just assign value data = value; //data = $.fn.editableutils.itemsByValue(value, this.options.select2.tags, this.idFunc); } else if(this.sourceData) { data = $.fn.editableutils.itemsByValue(value, this.sourceData, this.idFunc); } else { //can not get list of possible values //(e.g. autotext for select2 with ajax source) } //data may be array (when multiple values allowed) if($.isArray(data)) { //collect selected data and show with separator text = []; $.each(data, function(k, v){ text.push(v && typeof v === 'object' ? that.formatSelection(v) : v); }); } else if(data) { text = that.formatSelection(data); } text = $.isArray(text) ? text.join(this.options.viewseparator) : text; //$(element).text(text); Constructor.superclass.value2html.call(this, text, element); }, html2value: function(html) { return this.options.select2.tags ? this.str2value(html, this.options.viewseparator) : null; }, value2input: function(value) { // if value array => join it anyway if($.isArray(value)) { value = value.join(this.getSeparator()); } //for remote source just set value, text is updated by initSelection if(!this.$input.data('select2')) { this.$input.val(value); this.$input.select2(this.options.select2); } else { //second argument needed to separate initial change from user's click (for autosubmit) this.$input.val(value).trigger('change', true); //Uncaught Error: cannot call val() if initSelection() is not defined //this.$input.select2('val', value); } // if defined remote source AND no multiple mode AND no user's initSelection provided --> // we should somehow get text for provided id. // The solution is to use element's text as text for that id (exclude empty) if(this.isRemote && !this.isMultiple && !this.options.select2.initSelection) { // customId and customText are methods to extract `id` and `text` from data object // we can use this workaround only if user did not define these methods // otherwise we cant construct data object var customId = this.options.select2.id, customText = this.options.select2.formatSelection; if(!customId && !customText) { var $el = $(this.options.scope); if (!$el.data('editable').isEmpty) { var data = {id: value, text: $el.text()}; this.$input.select2('data', data); } } } }, input2value: function() { return this.$input.select2('val'); }, str2value: function(str, separator) { if(typeof str !== 'string' || !this.isMultiple) { return str; } separator = separator || this.getSeparator(); var val, i, l; if (str === null || str.length < 1) { return null; } val = str.split(separator); for (i = 0, l = val.length; i < l; i = i + 1) { val[i] = $.trim(val[i]); } return val; }, autosubmit: function() { this.$input.on('change', function(e, isInitial){ if(!isInitial) { $(this).closest('form').submit(); } }); }, getSeparator: function() { return this.options.select2.separator || $.fn.select2.defaults.separator; }, /* Converts source from x-editable format: {value: 1, text: "1"} to select2 format: {id: 1, text: "1"} */ convertSource: function(source) { if($.isArray(source) && source.length && source[0].value !== undefined) { for(var i = 0; i<source.length; i++) { if(source[i].value !== undefined) { source[i].id = source[i].value; delete source[i].value; } } } return source; }, destroy: function() { if(this.$input.data('select2')) { this.$input.select2('destroy'); } } }); Constructor.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <input type="hidden"> **/ tpl:'<input type="hidden">', /** Configuration of select2. [Full list of options](http://ivaynberg.github.com/select2). @property select2 @type object @default null **/ select2: null, /** Placeholder attribute of select @property placeholder @type string @default null **/ placeholder: null, /** Source data for select. It will be assigned to select2 `data` property and kept here just for convenience. Please note, that format is different from simple `select` input: use 'id' instead of 'value'. E.g. `[{id: 1, text: "text1"}, {id: 2, text: "text2"}, ...]`. @property source @type array|string|function @default null **/ source: null, /** Separator used to display tags. @property viewseparator @type string @default ', ' **/ viewseparator: ', ' }); $.fn.editabletypes.select2 = Constructor; }(window.jQuery)); /** * Combodate - 1.0.5 * Dropdown date and time picker. * Converts text input into dropdowns to pick day, month, year, hour, minute and second. * Uses momentjs as datetime library http://momentjs.com. * For i18n include corresponding file from https://github.com/timrwood/moment/tree/master/lang * * Confusion at noon and midnight - see http://en.wikipedia.org/wiki/12-hour_clock#Confusion_at_noon_and_midnight * In combodate: * 12:00 pm --> 12:00 (24-h format, midday) * 12:00 am --> 00:00 (24-h format, midnight, start of day) * * Differs from momentjs parse rules: * 00:00 pm, 12:00 pm --> 12:00 (24-h format, day not change) * 00:00 am, 12:00 am --> 00:00 (24-h format, day not change) * * * Author: Vitaliy Potapov * Project page: http://github.com/vitalets/combodate * Copyright (c) 2012 Vitaliy Potapov. Released under MIT License. **/ (function ($) { var Combodate = function (element, options) { this.$element = $(element); if(!this.$element.is('input')) { $.error('Combodate should be applied to INPUT element'); return; } this.options = $.extend({}, $.fn.combodate.defaults, options, this.$element.data()); this.init(); }; Combodate.prototype = { constructor: Combodate, init: function () { this.map = { //key regexp moment.method day: ['D', 'date'], month: ['M', 'month'], year: ['Y', 'year'], hour: ['[Hh]', 'hours'], minute: ['m', 'minutes'], second: ['s', 'seconds'], ampm: ['[Aa]', ''] }; this.$widget = $('<span class="combodate"></span>').html(this.getTemplate()); this.initCombos(); //update original input on change this.$widget.on('change', 'select', $.proxy(function(e) { this.$element.val(this.getValue()).change(); // update days count if month or year changes if (this.options.smartDays) { if ($(e.target).is('.month') || $(e.target).is('.year')) { this.fillCombo('day'); } } }, this)); this.$widget.find('select').css('width', 'auto'); // hide original input and insert widget this.$element.hide().after(this.$widget); // set initial value this.setValue(this.$element.val() || this.options.value); }, /* Replace tokens in template with <select> elements */ getTemplate: function() { var tpl = this.options.template; //first pass $.each(this.map, function(k, v) { v = v[0]; var r = new RegExp(v+'+'), token = v.length > 1 ? v.substring(1, 2) : v; tpl = tpl.replace(r, '{'+token+'}'); }); //replace spaces with &nbsp; tpl = tpl.replace(/ /g, '&nbsp;'); //second pass $.each(this.map, function(k, v) { v = v[0]; var token = v.length > 1 ? v.substring(1, 2) : v; tpl = tpl.replace('{'+token+'}', '<select class="input-sm '+k+'"></select>'); }); return tpl; }, /* Initialize combos that presents in template */ initCombos: function() { for (var k in this.map) { var $c = this.$widget.find('.'+k); // set properties like this.$day, this.$month etc. this['$'+k] = $c.length ? $c : null; // fill with items this.fillCombo(k); } }, /* Fill combo with items */ fillCombo: function(k) { var $combo = this['$'+k]; if (!$combo) { return; } // define method name to fill items, e.g `fillDays` var f = 'fill' + k.charAt(0).toUpperCase() + k.slice(1); var items = this[f](); var value = $combo.val(); $combo.empty(); for(var i=0; i<items.length; i++) { $combo.append('<option value="'+items[i][0]+'">'+items[i][1]+'</option>'); } $combo.val(value); }, /* Initialize items of combos. Handles `firstItem` option */ fillCommon: function(key) { var values = [], relTime; if(this.options.firstItem === 'name') { //need both to support moment ver < 2 and >= 2 relTime = moment.relativeTime || moment.langData()._relativeTime; var header = typeof relTime[key] === 'function' ? relTime[key](1, true, key, false) : relTime[key]; //take last entry (see momentjs lang files structure) header = header.split(' ').reverse()[0]; values.push(['', header]); } else if(this.options.firstItem === 'empty') { values.push(['', '']); } return values; }, /* fill day */ fillDay: function() { var items = this.fillCommon('d'), name, i, twoDigit = this.options.template.indexOf('DD') !== -1, daysCount = 31; // detect days count (depends on month and year) // originally https://github.com/vitalets/combodate/pull/7 if (this.options.smartDays && this.$month && this.$year) { var month = parseInt(this.$month.val(), 10); var year = parseInt(this.$year.val(), 10); if (!isNaN(month) && !isNaN(year)) { daysCount = moment([year, month]).daysInMonth(); } } for (i = 1; i <= daysCount; i++) { name = twoDigit ? this.leadZero(i) : i; items.push([i, name]); } return items; }, /* fill month */ fillMonth: function() { var items = this.fillCommon('M'), name, i, longNames = this.options.template.indexOf('MMMM') !== -1, shortNames = this.options.template.indexOf('MMM') !== -1, twoDigit = this.options.template.indexOf('MM') !== -1; for(i=0; i<=11; i++) { if(longNames) { //see https://github.com/timrwood/momentjs.com/pull/36 name = moment().date(1).month(i).format('MMMM'); } else if(shortNames) { name = moment().date(1).month(i).format('MMM'); } else if(twoDigit) { name = this.leadZero(i+1); } else { name = i+1; } items.push([i, name]); } return items; }, /* fill year */ fillYear: function() { var items = [], name, i, longNames = this.options.template.indexOf('YYYY') !== -1; for(i=this.options.maxYear; i>=this.options.minYear; i--) { name = longNames ? i : (i+'').substring(2); items[this.options.yearDescending ? 'push' : 'unshift']([i, name]); } items = this.fillCommon('y').concat(items); return items; }, /* fill hour */ fillHour: function() { var items = this.fillCommon('h'), name, i, h12 = this.options.template.indexOf('h') !== -1, h24 = this.options.template.indexOf('H') !== -1, twoDigit = this.options.template.toLowerCase().indexOf('hh') !== -1, min = h12 ? 1 : 0, max = h12 ? 12 : 23; for(i=min; i<=max; i++) { name = twoDigit ? this.leadZero(i) : i; items.push([i, name]); } return items; }, /* fill minute */ fillMinute: function() { var items = this.fillCommon('m'), name, i, twoDigit = this.options.template.indexOf('mm') !== -1; for(i=0; i<=59; i+= this.options.minuteStep) { name = twoDigit ? this.leadZero(i) : i; items.push([i, name]); } return items; }, /* fill second */ fillSecond: function() { var items = this.fillCommon('s'), name, i, twoDigit = this.options.template.indexOf('ss') !== -1; for(i=0; i<=59; i+= this.options.secondStep) { name = twoDigit ? this.leadZero(i) : i; items.push([i, name]); } return items; }, /* fill ampm */ fillAmpm: function() { var ampmL = this.options.template.indexOf('a') !== -1, ampmU = this.options.template.indexOf('A') !== -1, items = [ ['am', ampmL ? 'am' : 'AM'], ['pm', ampmL ? 'pm' : 'PM'] ]; return items; }, /* Returns current date value from combos. If format not specified - `options.format` used. If format = `null` - Moment object returned. */ getValue: function(format) { var dt, values = {}, that = this, notSelected = false; //getting selected values $.each(this.map, function(k, v) { if(k === 'ampm') { return; } var def = k === 'day' ? 1 : 0; values[k] = that['$'+k] ? parseInt(that['$'+k].val(), 10) : def; if(isNaN(values[k])) { notSelected = true; return false; } }); //if at least one visible combo not selected - return empty string if(notSelected) { return ''; } //convert hours 12h --> 24h if(this.$ampm) { //12:00 pm --> 12:00 (24-h format, midday), 12:00 am --> 00:00 (24-h format, midnight, start of day) if(values.hour === 12) { values.hour = this.$ampm.val() === 'am' ? 0 : 12; } else { values.hour = this.$ampm.val() === 'am' ? values.hour : values.hour+12; } } dt = moment([values.year, values.month, values.day, values.hour, values.minute, values.second]); //highlight invalid date this.highlight(dt); format = format === undefined ? this.options.format : format; if(format === null) { return dt.isValid() ? dt : null; } else { return dt.isValid() ? dt.format(format) : ''; } }, setValue: function(value) { if(!value) { return; } var dt = typeof value === 'string' ? moment(value, this.options.format) : moment(value), that = this, values = {}; //function to find nearest value in select options function getNearest($select, value) { var delta = {}; $select.children('option').each(function(i, opt){ var optValue = $(opt).attr('value'), distance; if(optValue === '') return; distance = Math.abs(optValue - value); if(typeof delta.distance === 'undefined' || distance < delta.distance) { delta = {value: optValue, distance: distance}; } }); return delta.value; } if(dt.isValid()) { //read values from date object $.each(this.map, function(k, v) { if(k === 'ampm') { return; } values[k] = dt[v[1]](); }); if(this.$ampm) { //12:00 pm --> 12:00 (24-h format, midday), 12:00 am --> 00:00 (24-h format, midnight, start of day) if(values.hour >= 12) { values.ampm = 'pm'; if(values.hour > 12) { values.hour -= 12; } } else { values.ampm = 'am'; if(values.hour === 0) { values.hour = 12; } } } $.each(values, function(k, v) { //call val() for each existing combo, e.g. this.$hour.val() if(that['$'+k]) { if(k === 'minute' && that.options.minuteStep > 1 && that.options.roundTime) { v = getNearest(that['$'+k], v); } if(k === 'second' && that.options.secondStep > 1 && that.options.roundTime) { v = getNearest(that['$'+k], v); } that['$'+k].val(v); } }); // update days count if (this.options.smartDays) { this.fillCombo('day'); } this.$element.val(dt.format(this.options.format)).change(); } }, /* highlight combos if date is invalid */ highlight: function(dt) { if(!dt.isValid()) { if(this.options.errorClass) { this.$widget.addClass(this.options.errorClass); } else { //store original border color if(!this.borderColor) { this.borderColor = this.$widget.find('select').css('border-color'); } this.$widget.find('select').css('border-color', 'red'); } } else { if(this.options.errorClass) { this.$widget.removeClass(this.options.errorClass); } else { this.$widget.find('select').css('border-color', this.borderColor); } } }, leadZero: function(v) { return v <= 9 ? '0' + v : v; }, destroy: function() { this.$widget.remove(); this.$element.removeData('combodate').show(); } //todo: clear method }; $.fn.combodate = function ( option ) { var d, args = Array.apply(null, arguments); args.shift(); //getValue returns date as string / object (not jQuery object) if(option === 'getValue' && this.length && (d = this.eq(0).data('combodate'))) { return d.getValue.apply(d, args); } return this.each(function () { var $this = $(this), data = $this.data('combodate'), options = typeof option == 'object' && option; if (!data) { $this.data('combodate', (data = new Combodate(this, options))); } if (typeof option == 'string' && typeof data[option] == 'function') { data[option].apply(data, args); } }); }; $.fn.combodate.defaults = { //in this format value stored in original input format: 'DD-MM-YYYY HH:mm', //in this format items in dropdowns are displayed template: 'D / MMM / YYYY H : mm', //initial value, can be `new Date()` value: null, minYear: 1970, maxYear: 2015, yearDescending: true, minuteStep: 5, secondStep: 1, firstItem: 'empty', //'name', 'empty', 'none' errorClass: null, roundTime: true, // whether to round minutes and seconds if step > 1 smartDays: false // whether days in combo depend on selected month: 31, 30, 28 }; }(window.jQuery)); /** Combodate input - dropdown date and time picker. Based on [combodate](http://vitalets.github.com/combodate) plugin (included). To use it you should manually include [momentjs](http://momentjs.com). <script src="js/moment.min.js"></script> Allows to input: * only date * only time * both date and time Please note, that format is taken from momentjs and **not compatible** with bootstrap-datepicker / jquery UI datepicker. Internally value stored as `momentjs` object. @class combodate @extends abstractinput @final @since 1.4.0 @example <a href="#" id="dob" data-type="combodate" data-pk="1" data-url="/post" data-value="1984-05-15" data-title="Select date"></a> <script> $(function(){ $('#dob').editable({ format: 'YYYY-MM-DD', viewformat: 'DD.MM.YYYY', template: 'D / MMMM / YYYY', combodate: { minYear: 2000, maxYear: 2015, minuteStep: 1 } } }); }); </script> **/ /*global moment*/ (function ($) { "use strict"; var Constructor = function (options) { this.init('combodate', options, Constructor.defaults); //by default viewformat equals to format if(!this.options.viewformat) { this.options.viewformat = this.options.format; } //try parse combodate config defined as json string in data-combodate options.combodate = $.fn.editableutils.tryParseJson(options.combodate, true); //overriding combodate config (as by default jQuery extend() is not recursive) this.options.combodate = $.extend({}, Constructor.defaults.combodate, options.combodate, { format: this.options.format, template: this.options.template }); }; $.fn.editableutils.inherit(Constructor, $.fn.editabletypes.abstractinput); $.extend(Constructor.prototype, { render: function () { this.$input.combodate(this.options.combodate); if($.fn.editableform.engine === 'bs3') { this.$input.siblings().find('select').addClass('form-control'); } if(this.options.inputclass) { this.$input.siblings().find('select').addClass(this.options.inputclass); } //"clear" link /* if(this.options.clear) { this.$clear = $('<a href="#"></a>').html(this.options.clear).click($.proxy(function(e){ e.preventDefault(); e.stopPropagation(); this.clear(); }, this)); this.$tpl.parent().append($('<div class="editable-clear">').append(this.$clear)); } */ }, value2html: function(value, element) { var text = value ? value.format(this.options.viewformat) : ''; //$(element).text(text); Constructor.superclass.value2html.call(this, text, element); }, html2value: function(html) { return html ? moment(html, this.options.viewformat) : null; }, value2str: function(value) { return value ? value.format(this.options.format) : ''; }, str2value: function(str) { return str ? moment(str, this.options.format) : null; }, value2submit: function(value) { return this.value2str(value); }, value2input: function(value) { this.$input.combodate('setValue', value); }, input2value: function() { return this.$input.combodate('getValue', null); }, activate: function() { this.$input.siblings('.combodate').find('select').eq(0).focus(); }, /* clear: function() { this.$input.data('datepicker').date = null; this.$input.find('.active').removeClass('active'); }, */ autosubmit: function() { } }); Constructor.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <input type="text"> **/ tpl:'<input type="text">', /** @property inputclass @default null **/ inputclass: null, /** Format used for sending value to server. Also applied when converting date from <code>data-value</code> attribute.<br> See list of tokens in [momentjs docs](http://momentjs.com/docs/#/parsing/string-format) @property format @type string @default YYYY-MM-DD **/ format:'YYYY-MM-DD', /** Format used for displaying date. Also applied when converting date from element's text on init. If not specified equals to `format`. @property viewformat @type string @default null **/ viewformat: null, /** Template used for displaying dropdowns. @property template @type string @default D / MMM / YYYY **/ template: 'D / MMM / YYYY', /** Configuration of combodate. Full list of options: http://vitalets.github.com/combodate/#docs @property combodate @type object @default null **/ combodate: null /* (not implemented yet) Text shown as clear date button. If <code>false</code> clear button will not be rendered. @property clear @type boolean|string @default 'x clear' */ //clear: '&times; clear' }); $.fn.editabletypes.combodate = Constructor; }(window.jQuery)); /* Editableform based on Twitter Bootstrap 3 */ (function ($) { "use strict"; //store parent methods var pInitInput = $.fn.editableform.Constructor.prototype.initInput; $.extend($.fn.editableform.Constructor.prototype, { initTemplate: function() { this.$form = $($.fn.editableform.template); this.$form.find('.control-group').addClass('form-group'); this.$form.find('.editable-error-block').addClass('help-block'); }, initInput: function() { pInitInput.apply(this); //for bs3 set default class `input-sm` to standard inputs var emptyInputClass = this.input.options.inputclass === null || this.input.options.inputclass === false; var defaultClass = 'input-sm'; //bs3 add `form-control` class to standard inputs var stdtypes = 'text,select,textarea,password,email,url,tel,number,range,time,typeaheadjs'.split(','); if(~$.inArray(this.input.type, stdtypes)) { this.input.$input.addClass('form-control'); if(emptyInputClass) { this.input.options.inputclass = defaultClass; this.input.$input.addClass(defaultClass); } } //apply bs3 size class also to buttons (to fit size of control) var $btn = this.$form.find('.editable-buttons'); var classes = emptyInputClass ? [defaultClass] : this.input.options.inputclass.split(' '); for(var i=0; i<classes.length; i++) { // `btn-sm` is default now /* if(classes[i].toLowerCase() === 'input-sm') { $btn.find('button').addClass('btn-sm'); } */ if(classes[i].toLowerCase() === 'input-lg') { $btn.find('button').removeClass('btn-sm').addClass('btn-lg'); } } } }); //buttons $.fn.editableform.buttons = '<button type="submit" class="btn btn-sm btn-primary editable-submit">'+ '<i class="fa fa-check"></i>'+ '</button>'+ '<button type="button" class="btn btn-sm btn-default editable-cancel">'+ '<i class="fa fa-times"></i>'+ '</button>'; //error classes $.fn.editableform.errorGroupClass = 'has-error'; $.fn.editableform.errorBlockClass = null; //engine $.fn.editableform.engine = 'bs3'; }(window.jQuery)); /** * Editable Popover3 (for Bootstrap 3) * --------------------- * requires bootstrap-popover.js */ (function ($) { "use strict"; //extend methods $.extend($.fn.editableContainer.Popup.prototype, { containerName: 'popover', containerDataName: 'bs.popover', innerCss: '.popover-content', defaults: $.fn.popover.Constructor.DEFAULTS, initContainer: function(){ $.extend(this.containerOptions, { trigger: 'manual', selector: false, content: ' ', template: this.defaults.template }); //as template property is used in inputs, hide it from popover var t; if(this.$element.data('template')) { t = this.$element.data('template'); this.$element.removeData('template'); } this.call(this.containerOptions); if(t) { //restore data('template') this.$element.data('template', t); } }, /* show */ innerShow: function () { this.call('show'); }, /* hide */ innerHide: function () { this.call('hide'); }, /* destroy */ innerDestroy: function() { this.call('destroy'); }, setContainerOption: function(key, value) { this.container().options[key] = value; }, /** * move popover to new position. This function mainly copied from bootstrap-popover. */ /*jshint laxcomma: true, eqeqeq: false*/ setPosition: function () { (function() { /* var $tip = this.tip() , inside , pos , actualWidth , actualHeight , placement , tp , tpt , tpb , tpl , tpr; placement = typeof this.options.placement === 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement; inside = /in/.test(placement); $tip // .detach() //vitalets: remove any placement class because otherwise they dont influence on re-positioning of visible popover .removeClass('top right bottom left') .css({ top: 0, left: 0, display: 'block' }); // .insertAfter(this.$element); pos = this.getPosition(inside); actualWidth = $tip[0].offsetWidth; actualHeight = $tip[0].offsetHeight; placement = inside ? placement.split(' ')[1] : placement; tpb = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2}; tpt = {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2}; tpl = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth}; tpr = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width}; switch (placement) { case 'bottom': if ((tpb.top + actualHeight) > ($(window).scrollTop() + $(window).height())) { if (tpt.top > $(window).scrollTop()) { placement = 'top'; } else if ((tpr.left + actualWidth) < ($(window).scrollLeft() + $(window).width())) { placement = 'right'; } else if (tpl.left > $(window).scrollLeft()) { placement = 'left'; } else { placement = 'right'; } } break; case 'top': if (tpt.top < $(window).scrollTop()) { if ((tpb.top + actualHeight) < ($(window).scrollTop() + $(window).height())) { placement = 'bottom'; } else if ((tpr.left + actualWidth) < ($(window).scrollLeft() + $(window).width())) { placement = 'right'; } else if (tpl.left > $(window).scrollLeft()) { placement = 'left'; } else { placement = 'right'; } } break; case 'left': if (tpl.left < $(window).scrollLeft()) { if ((tpr.left + actualWidth) < ($(window).scrollLeft() + $(window).width())) { placement = 'right'; } else if (tpt.top > $(window).scrollTop()) { placement = 'top'; } else if (tpt.top > $(window).scrollTop()) { placement = 'bottom'; } else { placement = 'right'; } } break; case 'right': if ((tpr.left + actualWidth) > ($(window).scrollLeft() + $(window).width())) { if (tpl.left > $(window).scrollLeft()) { placement = 'left'; } else if (tpt.top > $(window).scrollTop()) { placement = 'top'; } else if (tpt.top > $(window).scrollTop()) { placement = 'bottom'; } } break; } switch (placement) { case 'bottom': tp = tpb; break; case 'top': tp = tpt; break; case 'left': tp = tpl; break; case 'right': tp = tpr; break; } $tip .offset(tp) .addClass(placement) .addClass('in'); */ var $tip = this.tip(); var placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement; var autoToken = /\s?auto?\s?/i; var autoPlace = autoToken.test(placement); if (autoPlace) { placement = placement.replace(autoToken, '') || 'top'; } var pos = this.getPosition(); var actualWidth = $tip[0].offsetWidth; var actualHeight = $tip[0].offsetHeight; if (autoPlace) { var $parent = this.$element.parent(); var orgPlacement = placement; var docScroll = document.documentElement.scrollTop || document.body.scrollTop; var parentWidth = this.options.container == 'body' ? window.innerWidth : $parent.outerWidth(); var parentHeight = this.options.container == 'body' ? window.innerHeight : $parent.outerHeight(); var parentLeft = this.options.container == 'body' ? 0 : $parent.offset().left; placement = placement == 'bottom' && pos.top + pos.height + actualHeight - docScroll > parentHeight ? 'top' : placement == 'top' && pos.top - docScroll - actualHeight < 0 ? 'bottom' : placement == 'right' && pos.right + actualWidth > parentWidth ? 'left' : placement == 'left' && pos.left - actualWidth < parentLeft ? 'right' : placement; $tip .removeClass(orgPlacement) .addClass(placement); } var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight); this.applyPlacement(calculatedOffset, placement); }).call(this.container()); /*jshint laxcomma: false, eqeqeq: true*/ } }); }(window.jQuery)); /* ========================================================= * bootstrap-datepicker.js * http://www.eyecon.ro/bootstrap-datepicker * ========================================================= * Copyright 2012 Stefan Petre * Improvements by Andrew Rowls * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================= */ (function( $ ) { function UTCDate(){ return new Date(Date.UTC.apply(Date, arguments)); } function UTCToday(){ var today = new Date(); return UTCDate(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate()); } // Picker object var Datepicker = function(element, options) { var that = this; this._process_options(options); this.element = $(element); this.isInline = false; this.isInput = this.element.is('input'); this.component = this.element.is('.date') ? this.element.find('.add-on, .btn') : false; this.hasInput = this.component && this.element.find('input').length; if(this.component && this.component.length === 0) this.component = false; this.picker = $(DPGlobal.template); this._buildEvents(); this._attachEvents(); if(this.isInline) { this.picker.addClass('datepicker-inline').appendTo(this.element); } else { this.picker.addClass('datepicker-dropdown dropdown-menu'); } if (this.o.rtl){ this.picker.addClass('datepicker-rtl'); this.picker.find('.prev i, .next i') .toggleClass('icon-arrow-left icon-arrow-right'); } this.viewMode = this.o.startView; if (this.o.calendarWeeks) this.picker.find('tfoot th.today') .attr('colspan', function(i, val){ return parseInt(val) + 1; }); this._allow_update = false; this.setStartDate(this.o.startDate); this.setEndDate(this.o.endDate); this.setDaysOfWeekDisabled(this.o.daysOfWeekDisabled); this.fillDow(); this.fillMonths(); this._allow_update = true; this.update(); this.showMode(); if(this.isInline) { this.show(); } }; Datepicker.prototype = { constructor: Datepicker, _process_options: function(opts){ // Store raw options for reference this._o = $.extend({}, this._o, opts); // Processed options var o = this.o = $.extend({}, this._o); // Check if "de-DE" style date is available, if not language should // fallback to 2 letter code eg "de" var lang = o.language; if (!dates[lang]) { lang = lang.split('-')[0]; if (!dates[lang]) lang = defaults.language; } o.language = lang; switch(o.startView){ case 2: case 'decade': o.startView = 2; break; case 1: case 'year': o.startView = 1; break; default: o.startView = 0; } switch (o.minViewMode) { case 1: case 'months': o.minViewMode = 1; break; case 2: case 'years': o.minViewMode = 2; break; default: o.minViewMode = 0; } o.startView = Math.max(o.startView, o.minViewMode); o.weekStart %= 7; o.weekEnd = ((o.weekStart + 6) % 7); var format = DPGlobal.parseFormat(o.format) if (o.startDate !== -Infinity) { o.startDate = DPGlobal.parseDate(o.startDate, format, o.language); } if (o.endDate !== Infinity) { o.endDate = DPGlobal.parseDate(o.endDate, format, o.language); } o.daysOfWeekDisabled = o.daysOfWeekDisabled||[]; if (!$.isArray(o.daysOfWeekDisabled)) o.daysOfWeekDisabled = o.daysOfWeekDisabled.split(/[,\s]*/); o.daysOfWeekDisabled = $.map(o.daysOfWeekDisabled, function (d) { return parseInt(d, 10); }); }, _events: [], _secondaryEvents: [], _applyEvents: function(evs){ for (var i=0, el, ev; i<evs.length; i++){ el = evs[i][0]; ev = evs[i][1]; el.on(ev); } }, _unapplyEvents: function(evs){ for (var i=0, el, ev; i<evs.length; i++){ el = evs[i][0]; ev = evs[i][1]; el.off(ev); } }, _buildEvents: function(){ if (this.isInput) { // single input this._events = [ [this.element, { focus: $.proxy(this.show, this), keyup: $.proxy(this.update, this), keydown: $.proxy(this.keydown, this) }] ]; } else if (this.component && this.hasInput){ // component: input + button this._events = [ // For components that are not readonly, allow keyboard nav [this.element.find('input'), { focus: $.proxy(this.show, this), keyup: $.proxy(this.update, this), keydown: $.proxy(this.keydown, this) }], [this.component, { click: $.proxy(this.show, this) }] ]; } else if (this.element.is('div')) { // inline datepicker this.isInline = true; } else { this._events = [ [this.element, { click: $.proxy(this.show, this) }] ]; } this._secondaryEvents = [ [this.picker, { click: $.proxy(this.click, this) }], [$(window), { resize: $.proxy(this.place, this) }], [$(document), { mousedown: $.proxy(function (e) { // Clicked outside the datepicker, hide it if (!( this.element.is(e.target) || this.element.find(e.target).size() || this.picker.is(e.target) || this.picker.find(e.target).size() )) { this.hide(); } }, this) }] ]; }, _attachEvents: function(){ this._detachEvents(); this._applyEvents(this._events); }, _detachEvents: function(){ this._unapplyEvents(this._events); }, _attachSecondaryEvents: function(){ this._detachSecondaryEvents(); this._applyEvents(this._secondaryEvents); }, _detachSecondaryEvents: function(){ this._unapplyEvents(this._secondaryEvents); }, _trigger: function(event, altdate){ var date = altdate || this.date, local_date = new Date(date.getTime() + (date.getTimezoneOffset()*60000)); this.element.trigger({ type: event, date: local_date, format: $.proxy(function(altformat){ var format = altformat || this.o.format; return DPGlobal.formatDate(date, format, this.o.language); }, this) }); }, show: function(e) { if (!this.isInline) this.picker.appendTo('body'); this.picker.show(); this.height = this.component ? this.component.outerHeight() : this.element.outerHeight(); this.place(); this._attachSecondaryEvents(); if (e) { e.preventDefault(); } this._trigger('show'); }, hide: function(e){ if(this.isInline) return; if (!this.picker.is(':visible')) return; this.picker.hide().detach(); this._detachSecondaryEvents(); this.viewMode = this.o.startView; this.showMode(); if ( this.o.forceParse && ( this.isInput && this.element.val() || this.hasInput && this.element.find('input').val() ) ) this.setValue(); this._trigger('hide'); }, remove: function() { this.hide(); this._detachEvents(); this._detachSecondaryEvents(); this.picker.remove(); delete this.element.data().datepicker; if (!this.isInput) { delete this.element.data().date; } }, getDate: function() { var d = this.getUTCDate(); return new Date(d.getTime() + (d.getTimezoneOffset()*60000)); }, getUTCDate: function() { return this.date; }, setDate: function(d) { this.setUTCDate(new Date(d.getTime() - (d.getTimezoneOffset()*60000))); }, setUTCDate: function(d) { this.date = d; this.setValue(); }, setValue: function() { var formatted = this.getFormattedDate(); if (!this.isInput) { if (this.component){ this.element.find('input').val(formatted); } } else { this.element.val(formatted); } }, getFormattedDate: function(format) { if (format === undefined) format = this.o.format; return DPGlobal.formatDate(this.date, format, this.o.language); }, setStartDate: function(startDate){ this._process_options({startDate: startDate}); this.update(); this.updateNavArrows(); }, setEndDate: function(endDate){ this._process_options({endDate: endDate}); this.update(); this.updateNavArrows(); }, setDaysOfWeekDisabled: function(daysOfWeekDisabled){ this._process_options({daysOfWeekDisabled: daysOfWeekDisabled}); this.update(); this.updateNavArrows(); }, place: function(){ if(this.isInline) return; var zIndex = parseInt(this.element.parents().filter(function() { return $(this).css('z-index') != 'auto'; }).first().css('z-index'))+10; var offset = this.component ? this.component.parent().offset() : this.element.offset(); var height = this.component ? this.component.outerHeight(true) : this.element.outerHeight(true); this.picker.css({ top: offset.top + height, left: offset.left, zIndex: zIndex }); }, _allow_update: true, update: function(){ if (!this._allow_update) return; var date, fromArgs = false; if(arguments && arguments.length && (typeof arguments[0] === 'string' || arguments[0] instanceof Date)) { date = arguments[0]; fromArgs = true; } else { date = this.isInput ? this.element.val() : this.element.data('date') || this.element.find('input').val(); delete this.element.data().date; } this.date = DPGlobal.parseDate(date, this.o.format, this.o.language); if(fromArgs) this.setValue(); if (this.date < this.o.startDate) { this.viewDate = new Date(this.o.startDate); } else if (this.date > this.o.endDate) { this.viewDate = new Date(this.o.endDate); } else { this.viewDate = new Date(this.date); } this.fill(); }, fillDow: function(){ var dowCnt = this.o.weekStart, html = '<tr>'; if(this.o.calendarWeeks){ var cell = '<th class="cw">&nbsp;</th>'; html += cell; this.picker.find('.datepicker-days thead tr:first-child').prepend(cell); } while (dowCnt < this.o.weekStart + 7) { html += '<th class="dow">'+dates[this.o.language].daysMin[(dowCnt++)%7]+'</th>'; } html += '</tr>'; this.picker.find('.datepicker-days thead').append(html); }, fillMonths: function(){ var html = '', i = 0; while (i < 12) { html += '<span class="month">'+dates[this.o.language].monthsShort[i++]+'</span>'; } this.picker.find('.datepicker-months td').html(html); }, setRange: function(range){ if (!range || !range.length) delete this.range; else this.range = $.map(range, function(d){ return d.valueOf(); }); this.fill(); }, getClassNames: function(date){ var cls = [], year = this.viewDate.getUTCFullYear(), month = this.viewDate.getUTCMonth(), currentDate = this.date.valueOf(), today = new Date(); if (date.getUTCFullYear() < year || (date.getUTCFullYear() == year && date.getUTCMonth() < month)) { cls.push('old'); } else if (date.getUTCFullYear() > year || (date.getUTCFullYear() == year && date.getUTCMonth() > month)) { cls.push('new'); } // Compare internal UTC date with local today, not UTC today if (this.o.todayHighlight && date.getUTCFullYear() == today.getFullYear() && date.getUTCMonth() == today.getMonth() && date.getUTCDate() == today.getDate()) { cls.push('today'); } if (currentDate && date.valueOf() == currentDate) { cls.push('active'); } if (date.valueOf() < this.o.startDate || date.valueOf() > this.o.endDate || $.inArray(date.getUTCDay(), this.o.daysOfWeekDisabled) !== -1) { cls.push('disabled'); } if (this.range){ if (date > this.range[0] && date < this.range[this.range.length-1]){ cls.push('range'); } if ($.inArray(date.valueOf(), this.range) != -1){ cls.push('selected'); } } return cls; }, fill: function() { var d = new Date(this.viewDate), year = d.getUTCFullYear(), month = d.getUTCMonth(), startYear = this.o.startDate !== -Infinity ? this.o.startDate.getUTCFullYear() : -Infinity, startMonth = this.o.startDate !== -Infinity ? this.o.startDate.getUTCMonth() : -Infinity, endYear = this.o.endDate !== Infinity ? this.o.endDate.getUTCFullYear() : Infinity, endMonth = this.o.endDate !== Infinity ? this.o.endDate.getUTCMonth() : Infinity, currentDate = this.date && this.date.valueOf(), tooltip; this.picker.find('.datepicker-days thead th.datepicker-switch') .text(dates[this.o.language].months[month]+' '+year); this.picker.find('tfoot th.today') .text(dates[this.o.language].today) .toggle(this.o.todayBtn !== false); this.picker.find('tfoot th.clear') .text(dates[this.o.language].clear) .toggle(this.o.clearBtn !== false); this.updateNavArrows(); this.fillMonths(); var prevMonth = UTCDate(year, month-1, 28,0,0,0,0), day = DPGlobal.getDaysInMonth(prevMonth.getUTCFullYear(), prevMonth.getUTCMonth()); prevMonth.setUTCDate(day); prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.o.weekStart + 7)%7); var nextMonth = new Date(prevMonth); nextMonth.setUTCDate(nextMonth.getUTCDate() + 42); nextMonth = nextMonth.valueOf(); var html = []; var clsName; while(prevMonth.valueOf() < nextMonth) { if (prevMonth.getUTCDay() == this.o.weekStart) { html.push('<tr>'); if(this.o.calendarWeeks){ // ISO 8601: First week contains first thursday. // ISO also states week starts on Monday, but we can be more abstract here. var // Start of current week: based on weekstart/current date ws = new Date(+prevMonth + (this.o.weekStart - prevMonth.getUTCDay() - 7) % 7 * 864e5), // Thursday of this week th = new Date(+ws + (7 + 4 - ws.getUTCDay()) % 7 * 864e5), // First Thursday of year, year from thursday yth = new Date(+(yth = UTCDate(th.getUTCFullYear(), 0, 1)) + (7 + 4 - yth.getUTCDay())%7*864e5), // Calendar week: ms between thursdays, div ms per day, div 7 days calWeek = (th - yth) / 864e5 / 7 + 1; html.push('<td class="cw">'+ calWeek +'</td>'); } } clsName = this.getClassNames(prevMonth); clsName.push('day'); var before = this.o.beforeShowDay(prevMonth); if (before === undefined) before = {}; else if (typeof(before) === 'boolean') before = {enabled: before}; else if (typeof(before) === 'string') before = {classes: before}; if (before.enabled === false) clsName.push('disabled'); if (before.classes) clsName = clsName.concat(before.classes.split(/\s+/)); if (before.tooltip) tooltip = before.tooltip; clsName = $.unique(clsName); html.push('<td class="'+clsName.join(' ')+'"' + (tooltip ? ' title="'+tooltip+'"' : '') + '>'+prevMonth.getUTCDate() + '</td>'); if (prevMonth.getUTCDay() == this.o.weekEnd) { html.push('</tr>'); } prevMonth.setUTCDate(prevMonth.getUTCDate()+1); } this.picker.find('.datepicker-days tbody').empty().append(html.join('')); var currentYear = this.date && this.date.getUTCFullYear(); var months = this.picker.find('.datepicker-months') .find('th:eq(1)') .text(year) .end() .find('span').removeClass('active'); if (currentYear && currentYear == year) { months.eq(this.date.getUTCMonth()).addClass('active'); } if (year < startYear || year > endYear) { months.addClass('disabled'); } if (year == startYear) { months.slice(0, startMonth).addClass('disabled'); } if (year == endYear) { months.slice(endMonth+1).addClass('disabled'); } html = ''; year = parseInt(year/10, 10) * 10; var yearCont = this.picker.find('.datepicker-years') .find('th:eq(1)') .text(year + '-' + (year + 9)) .end() .find('td'); year -= 1; for (var i = -1; i < 11; i++) { html += '<span class="year'+(i == -1 ? ' old' : i == 10 ? ' new' : '')+(currentYear == year ? ' active' : '')+(year < startYear || year > endYear ? ' disabled' : '')+'">'+year+'</span>'; year += 1; } yearCont.html(html); }, updateNavArrows: function() { if (!this._allow_update) return; var d = new Date(this.viewDate), year = d.getUTCFullYear(), month = d.getUTCMonth(); switch (this.viewMode) { case 0: if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear() && month <= this.o.startDate.getUTCMonth()) { this.picker.find('.prev').css({visibility: 'hidden'}); } else { this.picker.find('.prev').css({visibility: 'visible'}); } if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear() && month >= this.o.endDate.getUTCMonth()) { this.picker.find('.next').css({visibility: 'hidden'}); } else { this.picker.find('.next').css({visibility: 'visible'}); } break; case 1: case 2: if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear()) { this.picker.find('.prev').css({visibility: 'hidden'}); } else { this.picker.find('.prev').css({visibility: 'visible'}); } if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear()) { this.picker.find('.next').css({visibility: 'hidden'}); } else { this.picker.find('.next').css({visibility: 'visible'}); } break; } }, click: function(e) { e.preventDefault(); var target = $(e.target).closest('span, td, th'); if (target.length == 1) { switch(target[0].nodeName.toLowerCase()) { case 'th': switch(target[0].className) { case 'datepicker-switch': this.showMode(1); break; case 'prev': case 'next': var dir = DPGlobal.modes[this.viewMode].navStep * (target[0].className == 'prev' ? -1 : 1); switch(this.viewMode){ case 0: this.viewDate = this.moveMonth(this.viewDate, dir); break; case 1: case 2: this.viewDate = this.moveYear(this.viewDate, dir); break; } this.fill(); break; case 'today': var date = new Date(); date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0); this.showMode(-2); var which = this.o.todayBtn == 'linked' ? null : 'view'; this._setDate(date, which); break; case 'clear': var element; if (this.isInput) element = this.element; else if (this.component) element = this.element.find('input'); if (element) element.val("").change(); this._trigger('changeDate'); this.update(); if (this.o.autoclose) this.hide(); break; } break; case 'span': if (!target.is('.disabled')) { this.viewDate.setUTCDate(1); if (target.is('.month')) { var day = 1; var month = target.parent().find('span').index(target); var year = this.viewDate.getUTCFullYear(); this.viewDate.setUTCMonth(month); this._trigger('changeMonth', this.viewDate); if (this.o.minViewMode === 1) { this._setDate(UTCDate(year, month, day,0,0,0,0)); } } else { var year = parseInt(target.text(), 10)||0; var day = 1; var month = 0; this.viewDate.setUTCFullYear(year); this._trigger('changeYear', this.viewDate); if (this.o.minViewMode === 2) { this._setDate(UTCDate(year, month, day,0,0,0,0)); } } this.showMode(-1); this.fill(); } break; case 'td': if (target.is('.day') && !target.is('.disabled')){ var day = parseInt(target.text(), 10)||1; var year = this.viewDate.getUTCFullYear(), month = this.viewDate.getUTCMonth(); if (target.is('.old')) { if (month === 0) { month = 11; year -= 1; } else { month -= 1; } } else if (target.is('.new')) { if (month == 11) { month = 0; year += 1; } else { month += 1; } } this._setDate(UTCDate(year, month, day,0,0,0,0)); } break; } } }, _setDate: function(date, which){ if (!which || which == 'date') this.date = new Date(date); if (!which || which == 'view') this.viewDate = new Date(date); this.fill(); this.setValue(); this._trigger('changeDate'); var element; if (this.isInput) { element = this.element; } else if (this.component){ element = this.element.find('input'); } if (element) { element.change(); if (this.o.autoclose && (!which || which == 'date')) { this.hide(); } } }, moveMonth: function(date, dir){ if (!dir) return date; var new_date = new Date(date.valueOf()), day = new_date.getUTCDate(), month = new_date.getUTCMonth(), mag = Math.abs(dir), new_month, test; dir = dir > 0 ? 1 : -1; if (mag == 1){ test = dir == -1 // If going back one month, make sure month is not current month // (eg, Mar 31 -> Feb 31 == Feb 28, not Mar 02) ? function(){ return new_date.getUTCMonth() == month; } // If going forward one month, make sure month is as expected // (eg, Jan 31 -> Feb 31 == Feb 28, not Mar 02) : function(){ return new_date.getUTCMonth() != new_month; }; new_month = month + dir; new_date.setUTCMonth(new_month); // Dec -> Jan (12) or Jan -> Dec (-1) -- limit expected date to 0-11 if (new_month < 0 || new_month > 11) new_month = (new_month + 12) % 12; } else { // For magnitudes >1, move one month at a time... for (var i=0; i<mag; i++) // ...which might decrease the day (eg, Jan 31 to Feb 28, etc)... new_date = this.moveMonth(new_date, dir); // ...then reset the day, keeping it in the new month new_month = new_date.getUTCMonth(); new_date.setUTCDate(day); test = function(){ return new_month != new_date.getUTCMonth(); }; } // Common date-resetting loop -- if date is beyond end of month, make it // end of month while (test()){ new_date.setUTCDate(--day); new_date.setUTCMonth(new_month); } return new_date; }, moveYear: function(date, dir){ return this.moveMonth(date, dir*12); }, dateWithinRange: function(date){ return date >= this.o.startDate && date <= this.o.endDate; }, keydown: function(e){ if (this.picker.is(':not(:visible)')){ if (e.keyCode == 27) // allow escape to hide and re-show picker this.show(); return; } var dateChanged = false, dir, day, month, newDate, newViewDate; switch(e.keyCode){ case 27: // escape this.hide(); e.preventDefault(); break; case 37: // left case 39: // right if (!this.o.keyboardNavigation) break; dir = e.keyCode == 37 ? -1 : 1; if (e.ctrlKey){ newDate = this.moveYear(this.date, dir); newViewDate = this.moveYear(this.viewDate, dir); } else if (e.shiftKey){ newDate = this.moveMonth(this.date, dir); newViewDate = this.moveMonth(this.viewDate, dir); } else { newDate = new Date(this.date); newDate.setUTCDate(this.date.getUTCDate() + dir); newViewDate = new Date(this.viewDate); newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir); } if (this.dateWithinRange(newDate)){ this.date = newDate; this.viewDate = newViewDate; this.setValue(); this.update(); e.preventDefault(); dateChanged = true; } break; case 38: // up case 40: // down if (!this.o.keyboardNavigation) break; dir = e.keyCode == 38 ? -1 : 1; if (e.ctrlKey){ newDate = this.moveYear(this.date, dir); newViewDate = this.moveYear(this.viewDate, dir); } else if (e.shiftKey){ newDate = this.moveMonth(this.date, dir); newViewDate = this.moveMonth(this.viewDate, dir); } else { newDate = new Date(this.date); newDate.setUTCDate(this.date.getUTCDate() + dir * 7); newViewDate = new Date(this.viewDate); newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir * 7); } if (this.dateWithinRange(newDate)){ this.date = newDate; this.viewDate = newViewDate; this.setValue(); this.update(); e.preventDefault(); dateChanged = true; } break; case 13: // enter this.hide(); e.preventDefault(); break; case 9: // tab this.hide(); break; } if (dateChanged){ this._trigger('changeDate'); var element; if (this.isInput) { element = this.element; } else if (this.component){ element = this.element.find('input'); } if (element) { element.change(); } } }, showMode: function(dir) { if (dir) { this.viewMode = Math.max(this.o.minViewMode, Math.min(2, this.viewMode + dir)); } /* vitalets: fixing bug of very special conditions: jquery 1.7.1 + webkit + show inline datepicker in bootstrap popover. Method show() does not set display css correctly and datepicker is not shown. Changed to .css('display', 'block') solve the problem. See https://github.com/vitalets/x-editable/issues/37 In jquery 1.7.2+ everything works fine. */ //this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show(); this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).css('display', 'block'); this.updateNavArrows(); } }; var DateRangePicker = function(element, options){ this.element = $(element); this.inputs = $.map(options.inputs, function(i){ return i.jquery ? i[0] : i; }); delete options.inputs; $(this.inputs) .datepicker(options) .bind('changeDate', $.proxy(this.dateUpdated, this)); this.pickers = $.map(this.inputs, function(i){ return $(i).data('datepicker'); }); this.updateDates(); }; DateRangePicker.prototype = { updateDates: function(){ this.dates = $.map(this.pickers, function(i){ return i.date; }); this.updateRanges(); }, updateRanges: function(){ var range = $.map(this.dates, function(d){ return d.valueOf(); }); $.each(this.pickers, function(i, p){ p.setRange(range); }); }, dateUpdated: function(e){ var dp = $(e.target).data('datepicker'), new_date = dp.getUTCDate(), i = $.inArray(e.target, this.inputs), l = this.inputs.length; if (i == -1) return; if (new_date < this.dates[i]){ // Date being moved earlier/left while (i>=0 && new_date < this.dates[i]){ this.pickers[i--].setUTCDate(new_date); } } else if (new_date > this.dates[i]){ // Date being moved later/right while (i<l && new_date > this.dates[i]){ this.pickers[i++].setUTCDate(new_date); } } this.updateDates(); }, remove: function(){ $.map(this.pickers, function(p){ p.remove(); }); delete this.element.data().datepicker; } }; function opts_from_el(el, prefix){ // Derive options from element data-attrs var data = $(el).data(), out = {}, inkey, replace = new RegExp('^' + prefix.toLowerCase() + '([A-Z])'), prefix = new RegExp('^' + prefix.toLowerCase()); for (var key in data) if (prefix.test(key)){ inkey = key.replace(replace, function(_,a){ return a.toLowerCase(); }); out[inkey] = data[key]; } return out; } function opts_from_locale(lang){ // Derive options from locale plugins var out = {}; // Check if "de-DE" style date is available, if not language should // fallback to 2 letter code eg "de" if (!dates[lang]) { lang = lang.split('-')[0] if (!dates[lang]) return; } var d = dates[lang]; $.each(locale_opts, function(i,k){ if (k in d) out[k] = d[k]; }); return out; } var old = $.fn.datepicker; var datepicker = $.fn.datepicker = function ( option ) { var args = Array.apply(null, arguments); args.shift(); var internal_return, this_return; this.each(function () { var $this = $(this), data = $this.data('datepicker'), options = typeof option == 'object' && option; if (!data) { var elopts = opts_from_el(this, 'date'), // Preliminary otions xopts = $.extend({}, defaults, elopts, options), locopts = opts_from_locale(xopts.language), // Options priority: js args, data-attrs, locales, defaults opts = $.extend({}, defaults, locopts, elopts, options); if ($this.is('.input-daterange') || opts.inputs){ var ropts = { inputs: opts.inputs || $this.find('input').toArray() }; $this.data('datepicker', (data = new DateRangePicker(this, $.extend(opts, ropts)))); } else{ $this.data('datepicker', (data = new Datepicker(this, opts))); } } if (typeof option == 'string' && typeof data[option] == 'function') { internal_return = data[option].apply(data, args); if (internal_return !== undefined) return false; } }); if (internal_return !== undefined) return internal_return; else return this; }; var defaults = $.fn.datepicker.defaults = { autoclose: false, beforeShowDay: $.noop, calendarWeeks: false, clearBtn: false, daysOfWeekDisabled: [], endDate: Infinity, forceParse: true, format: 'mm/dd/yyyy', keyboardNavigation: true, language: 'en', minViewMode: 0, rtl: false, startDate: -Infinity, startView: 0, todayBtn: false, todayHighlight: false, weekStart: 0 }; var locale_opts = $.fn.datepicker.locale_opts = [ 'format', 'rtl', 'weekStart' ]; $.fn.datepicker.Constructor = Datepicker; var dates = $.fn.datepicker.dates = { en: { days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"], daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"], months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], today: "Today", clear: "Clear" } }; var DPGlobal = { modes: [ { clsName: 'days', navFnc: 'Month', navStep: 1 }, { clsName: 'months', navFnc: 'FullYear', navStep: 1 }, { clsName: 'years', navFnc: 'FullYear', navStep: 10 }], isLeapYear: function (year) { return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)); }, getDaysInMonth: function (year, month) { return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]; }, validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g, nonpunctuation: /[^ -\/:-@\[\u3400-\u9fff-`{-~\t\n\r]+/g, parseFormat: function(format){ // IE treats \0 as a string end in inputs (truncating the value), // so it's a bad format delimiter, anyway var separators = format.replace(this.validParts, '\0').split('\0'), parts = format.match(this.validParts); if (!separators || !separators.length || !parts || parts.length === 0){ throw new Error("Invalid date format."); } return {separators: separators, parts: parts}; }, parseDate: function(date, format, language) { if (date instanceof Date) return date; if (typeof format === 'string') format = DPGlobal.parseFormat(format); if (/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(date)) { var part_re = /([\-+]\d+)([dmwy])/, parts = date.match(/([\-+]\d+)([dmwy])/g), part, dir; date = new Date(); for (var i=0; i<parts.length; i++) { part = part_re.exec(parts[i]); dir = parseInt(part[1]); switch(part[2]){ case 'd': date.setUTCDate(date.getUTCDate() + dir); break; case 'm': date = Datepicker.prototype.moveMonth.call(Datepicker.prototype, date, dir); break; case 'w': date.setUTCDate(date.getUTCDate() + dir * 7); break; case 'y': date = Datepicker.prototype.moveYear.call(Datepicker.prototype, date, dir); break; } } return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), 0, 0, 0); } var parts = date && date.match(this.nonpunctuation) || [], date = new Date(), parsed = {}, setters_order = ['yyyy', 'yy', 'M', 'MM', 'm', 'mm', 'd', 'dd'], setters_map = { yyyy: function(d,v){ return d.setUTCFullYear(v); }, yy: function(d,v){ return d.setUTCFullYear(2000+v); }, m: function(d,v){ v -= 1; while (v<0) v += 12; v %= 12; d.setUTCMonth(v); while (d.getUTCMonth() != v) d.setUTCDate(d.getUTCDate()-1); return d; }, d: function(d,v){ return d.setUTCDate(v); } }, val, filtered, part; setters_map['M'] = setters_map['MM'] = setters_map['mm'] = setters_map['m']; setters_map['dd'] = setters_map['d']; date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0); var fparts = format.parts.slice(); // Remove noop parts if (parts.length != fparts.length) { fparts = $(fparts).filter(function(i,p){ return $.inArray(p, setters_order) !== -1; }).toArray(); } // Process remainder if (parts.length == fparts.length) { for (var i=0, cnt = fparts.length; i < cnt; i++) { val = parseInt(parts[i], 10); part = fparts[i]; if (isNaN(val)) { switch(part) { case 'MM': filtered = $(dates[language].months).filter(function(){ var m = this.slice(0, parts[i].length), p = parts[i].slice(0, m.length); return m == p; }); val = $.inArray(filtered[0], dates[language].months) + 1; break; case 'M': filtered = $(dates[language].monthsShort).filter(function(){ var m = this.slice(0, parts[i].length), p = parts[i].slice(0, m.length); return m == p; }); val = $.inArray(filtered[0], dates[language].monthsShort) + 1; break; } } parsed[part] = val; } for (var i=0, s; i<setters_order.length; i++){ s = setters_order[i]; if (s in parsed && !isNaN(parsed[s])) setters_map[s](date, parsed[s]); } } return date; }, formatDate: function(date, format, language){ if (typeof format === 'string') format = DPGlobal.parseFormat(format); var val = { d: date.getUTCDate(), D: dates[language].daysShort[date.getUTCDay()], DD: dates[language].days[date.getUTCDay()], m: date.getUTCMonth() + 1, M: dates[language].monthsShort[date.getUTCMonth()], MM: dates[language].months[date.getUTCMonth()], yy: date.getUTCFullYear().toString().substring(2), yyyy: date.getUTCFullYear() }; val.dd = (val.d < 10 ? '0' : '') + val.d; val.mm = (val.m < 10 ? '0' : '') + val.m; var date = [], seps = $.extend([], format.separators); for (var i=0, cnt = format.parts.length; i <= cnt; i++) { if (seps.length) date.push(seps.shift()); date.push(val[format.parts[i]]); } return date.join(''); }, headTemplate: '<thead>'+ '<tr>'+ '<th class="prev"><i class="icon-arrow-left"/></th>'+ '<th colspan="5" class="datepicker-switch"></th>'+ '<th class="next"><i class="icon-arrow-right"/></th>'+ '</tr>'+ '</thead>', contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>', footTemplate: '<tfoot><tr><th colspan="7" class="today"></th></tr><tr><th colspan="7" class="clear"></th></tr></tfoot>' }; DPGlobal.template = '<div class="datepicker">'+ '<div class="datepicker-days">'+ '<table class=" table-condensed">'+ DPGlobal.headTemplate+ '<tbody></tbody>'+ DPGlobal.footTemplate+ '</table>'+ '</div>'+ '<div class="datepicker-months">'+ '<table class="table-condensed">'+ DPGlobal.headTemplate+ DPGlobal.contTemplate+ DPGlobal.footTemplate+ '</table>'+ '</div>'+ '<div class="datepicker-years">'+ '<table class="table-condensed">'+ DPGlobal.headTemplate+ DPGlobal.contTemplate+ DPGlobal.footTemplate+ '</table>'+ '</div>'+ '</div>'; $.fn.datepicker.DPGlobal = DPGlobal; /* DATEPICKER NO CONFLICT * =================== */ $.fn.datepicker.noConflict = function(){ $.fn.datepicker = old; return this; }; /* DATEPICKER DATA-API * ================== */ $(document).on( 'focus.datepicker.data-api click.datepicker.data-api', '[data-provide="datepicker"]', function(e){ var $this = $(this); if ($this.data('datepicker')) return; e.preventDefault(); // component click requires us to explicitly show it datepicker.call($this, 'show'); } ); $(function(){ //$('[data-provide="datepicker-inline"]').datepicker(); //vit: changed to support noConflict() datepicker.call($('[data-provide="datepicker-inline"]')); }); }( window.jQuery )); /** Bootstrap-datepicker. Description and examples: https://github.com/eternicode/bootstrap-datepicker. For **i18n** you should include js file from here: https://github.com/eternicode/bootstrap-datepicker/tree/master/js/locales and set `language` option. Since 1.4.0 date has different appearance in **popup** and **inline** modes. @class date @extends abstractinput @final @example <a href="#" id="dob" data-type="date" data-pk="1" data-url="/post" data-title="Select date">15/05/1984</a> <script> $(function(){ $('#dob').editable({ format: 'yyyy-mm-dd', viewformat: 'dd/mm/yyyy', datepicker: { weekStart: 1 } } }); }); </script> **/ (function ($) { "use strict"; //store bootstrap-datepicker as bdateicker to exclude conflict with jQuery UI one $.fn.bdatepicker = $.fn.datepicker.noConflict(); if(!$.fn.datepicker) { //if there were no other datepickers, keep also original name $.fn.datepicker = $.fn.bdatepicker; } var Date = function (options) { this.init('date', options, Date.defaults); this.initPicker(options, Date.defaults); }; $.fn.editableutils.inherit(Date, $.fn.editabletypes.abstractinput); $.extend(Date.prototype, { initPicker: function(options, defaults) { //'format' is set directly from settings or data-* attributes //by default viewformat equals to format if(!this.options.viewformat) { this.options.viewformat = this.options.format; } //try parse datepicker config defined as json string in data-datepicker options.datepicker = $.fn.editableutils.tryParseJson(options.datepicker, true); //overriding datepicker config (as by default jQuery extend() is not recursive) //since 1.4 datepicker internally uses viewformat instead of format. Format is for submit only this.options.datepicker = $.extend({}, defaults.datepicker, options.datepicker, { format: this.options.viewformat }); //language this.options.datepicker.language = this.options.datepicker.language || 'en'; //store DPglobal this.dpg = $.fn.bdatepicker.DPGlobal; //store parsed formats this.parsedFormat = this.dpg.parseFormat(this.options.format); this.parsedViewFormat = this.dpg.parseFormat(this.options.viewformat); }, render: function () { this.$input.bdatepicker(this.options.datepicker); //"clear" link if(this.options.clear) { this.$clear = $('<a href="#"></a>').html(this.options.clear).click($.proxy(function(e){ e.preventDefault(); e.stopPropagation(); this.clear(); }, this)); this.$tpl.parent().append($('<div class="editable-clear">').append(this.$clear)); } }, value2html: function(value, element) { var text = value ? this.dpg.formatDate(value, this.parsedViewFormat, this.options.datepicker.language) : ''; Date.superclass.value2html.call(this, text, element); }, html2value: function(html) { return this.parseDate(html, this.parsedViewFormat); }, value2str: function(value) { return value ? this.dpg.formatDate(value, this.parsedFormat, this.options.datepicker.language) : ''; }, str2value: function(str) { return this.parseDate(str, this.parsedFormat); }, value2submit: function(value) { return this.value2str(value); }, value2input: function(value) { this.$input.bdatepicker('update', value); }, input2value: function() { return this.$input.data('datepicker').date; }, activate: function() { }, clear: function() { this.$input.data('datepicker').date = null; this.$input.find('.active').removeClass('active'); if(!this.options.showbuttons) { this.$input.closest('form').submit(); } }, autosubmit: function() { this.$input.on('mouseup', '.day', function(e){ if($(e.currentTarget).is('.old') || $(e.currentTarget).is('.new')) { return; } var $form = $(this).closest('form'); setTimeout(function() { $form.submit(); }, 200); }); //changedate is not suitable as it triggered when showing datepicker. see #149 /* this.$input.on('changeDate', function(e){ var $form = $(this).closest('form'); setTimeout(function() { $form.submit(); }, 200); }); */ }, /* For incorrect date bootstrap-datepicker returns current date that is not suitable for datefield. This function returns null for incorrect date. */ parseDate: function(str, format) { var date = null, formattedBack; if(str) { date = this.dpg.parseDate(str, format, this.options.datepicker.language); if(typeof str === 'string') { formattedBack = this.dpg.formatDate(date, format, this.options.datepicker.language); if(str !== formattedBack) { date = null; } } } return date; } }); Date.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <div></div> **/ tpl:'<div class="editable-date well"></div>', /** @property inputclass @default null **/ inputclass: null, /** Format used for sending value to server. Also applied when converting date from <code>data-value</code> attribute.<br> Possible tokens are: <code>d, dd, m, mm, yy, yyyy</code> @property format @type string @default yyyy-mm-dd **/ format:'yyyy-mm-dd', /** Format used for displaying date. Also applied when converting date from element's text on init. If not specified equals to <code>format</code> @property viewformat @type string @default null **/ viewformat: null, /** Configuration of datepicker. Full list of options: http://bootstrap-datepicker.readthedocs.org/en/latest/options.html @property datepicker @type object @default { weekStart: 0, startView: 0, minViewMode: 0, autoclose: false } **/ datepicker:{ weekStart: 0, startView: 0, minViewMode: 0, autoclose: false }, /** Text shown as clear date button. If <code>false</code> clear button will not be rendered. @property clear @type boolean|string @default 'x clear' **/ clear: '&times; clear' }); $.fn.editabletypes.date = Date; }(window.jQuery)); /** Bootstrap datefield input - modification for inline mode. Shows normal <input type="text"> and binds popup datepicker. Automatically shown in inline mode. @class datefield @extends date @since 1.4.0 **/ (function ($) { "use strict"; var DateField = function (options) { this.init('datefield', options, DateField.defaults); this.initPicker(options, DateField.defaults); }; $.fn.editableutils.inherit(DateField, $.fn.editabletypes.date); $.extend(DateField.prototype, { render: function () { this.$input = this.$tpl.find('input'); this.setClass(); this.setAttr('placeholder'); //bootstrap-datepicker is set `bdateicker` to exclude conflict with jQuery UI one. (in date.js) this.$tpl.bdatepicker(this.options.datepicker); //need to disable original event handlers this.$input.off('focus keydown'); //update value of datepicker this.$input.keyup($.proxy(function(){ this.$tpl.removeData('date'); this.$tpl.bdatepicker('update'); }, this)); }, value2input: function(value) { this.$input.val(value ? this.dpg.formatDate(value, this.parsedViewFormat, this.options.datepicker.language) : ''); this.$tpl.bdatepicker('update'); }, input2value: function() { return this.html2value(this.$input.val()); }, activate: function() { $.fn.editabletypes.text.prototype.activate.call(this); }, autosubmit: function() { //reset autosubmit to empty } }); DateField.defaults = $.extend({}, $.fn.editabletypes.date.defaults, { /** @property tpl **/ tpl:'<div class="input-append date"><input type="text"/><span class="add-on"><i class="icon-th"></i></span></div>', /** @property inputclass @default 'input-small' **/ inputclass: 'input-small', /* datepicker config */ datepicker: { weekStart: 0, startView: 0, minViewMode: 0, autoclose: true } }); $.fn.editabletypes.datefield = DateField; }(window.jQuery)); /** Bootstrap-datetimepicker. Based on [smalot bootstrap-datetimepicker plugin](https://github.com/smalot/bootstrap-datetimepicker). Before usage you should manually include dependent js and css: <link href="css/datetimepicker.css" rel="stylesheet" type="text/css"></link> <script src="js/bootstrap-datetimepicker.js"></script> For **i18n** you should include js file from here: https://github.com/smalot/bootstrap-datetimepicker/tree/master/js/locales and set `language` option. @class datetime @extends abstractinput @final @since 1.4.4 @example <a href="#" id="last_seen" data-type="datetime" data-pk="1" data-url="/post" title="Select date & time">15/03/2013 12:45</a> <script> $(function(){ $('#last_seen').editable({ format: 'yyyy-mm-dd hh:ii', viewformat: 'dd/mm/yyyy hh:ii', datetimepicker: { weekStart: 1 } } }); }); </script> **/ (function ($) { "use strict"; var DateTime = function (options) { this.init('datetime', options, DateTime.defaults); this.initPicker(options, DateTime.defaults); }; $.fn.editableutils.inherit(DateTime, $.fn.editabletypes.abstractinput); $.extend(DateTime.prototype, { initPicker: function(options, defaults) { //'format' is set directly from settings or data-* attributes //by default viewformat equals to format if(!this.options.viewformat) { this.options.viewformat = this.options.format; } //try parse datetimepicker config defined as json string in data-datetimepicker options.datetimepicker = $.fn.editableutils.tryParseJson(options.datetimepicker, true); //overriding datetimepicker config (as by default jQuery extend() is not recursive) //since 1.4 datetimepicker internally uses viewformat instead of format. Format is for submit only this.options.datetimepicker = $.extend({}, defaults.datetimepicker, options.datetimepicker, { format: this.options.viewformat }); //language this.options.datetimepicker.language = this.options.datetimepicker.language || 'en'; //store DPglobal this.dpg = $.fn.datetimepicker.DPGlobal; //store parsed formats this.parsedFormat = this.dpg.parseFormat(this.options.format, this.options.formatType); this.parsedViewFormat = this.dpg.parseFormat(this.options.viewformat, this.options.formatType); }, render: function () { this.$input.datetimepicker(this.options.datetimepicker); //adjust container position when viewMode changes //see https://github.com/smalot/bootstrap-datetimepicker/pull/80 this.$input.on('changeMode', function(e) { var f = $(this).closest('form').parent(); //timeout here, otherwise container changes position before form has new size setTimeout(function(){ f.triggerHandler('resize'); }, 0); }); //"clear" link if(this.options.clear) { this.$clear = $('<a href="#"></a>').html(this.options.clear).click($.proxy(function(e){ e.preventDefault(); e.stopPropagation(); this.clear(); }, this)); this.$tpl.parent().append($('<div class="editable-clear">').append(this.$clear)); } }, value2html: function(value, element) { //formatDate works with UTCDate! var text = value ? this.dpg.formatDate(this.toUTC(value), this.parsedViewFormat, this.options.datetimepicker.language, this.options.formatType) : ''; if(element) { DateTime.superclass.value2html.call(this, text, element); } else { return text; } }, html2value: function(html) { //parseDate return utc date! var value = this.parseDate(html, this.parsedViewFormat); return value ? this.fromUTC(value) : null; }, value2str: function(value) { //formatDate works with UTCDate! return value ? this.dpg.formatDate(this.toUTC(value), this.parsedFormat, this.options.datetimepicker.language, this.options.formatType) : ''; }, str2value: function(str) { //parseDate return utc date! var value = this.parseDate(str, this.parsedFormat); return value ? this.fromUTC(value) : null; }, value2submit: function(value) { return this.value2str(value); }, value2input: function(value) { if(value) { this.$input.data('datetimepicker').setDate(value); } }, input2value: function() { //date may be cleared, in that case getDate() triggers error var dt = this.$input.data('datetimepicker'); return dt.date ? dt.getDate() : null; }, activate: function() { }, clear: function() { this.$input.data('datetimepicker').date = null; this.$input.find('.active').removeClass('active'); if(!this.options.showbuttons) { this.$input.closest('form').submit(); } }, autosubmit: function() { this.$input.on('mouseup', '.minute', function(e){ var $form = $(this).closest('form'); setTimeout(function() { $form.submit(); }, 200); }); }, //convert date from local to utc toUTC: function(value) { return value ? new Date(value.valueOf() - value.getTimezoneOffset() * 60000) : value; }, //convert date from utc to local fromUTC: function(value) { return value ? new Date(value.valueOf() + value.getTimezoneOffset() * 60000) : value; }, /* For incorrect date bootstrap-datetimepicker returns current date that is not suitable for datetimefield. This function returns null for incorrect date. */ parseDate: function(str, format) { var date = null, formattedBack; if(str) { date = this.dpg.parseDate(str, format, this.options.datetimepicker.language, this.options.formatType); if(typeof str === 'string') { formattedBack = this.dpg.formatDate(date, format, this.options.datetimepicker.language, this.options.formatType); if(str !== formattedBack) { date = null; } } } return date; } }); DateTime.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <div></div> **/ tpl:'<div class="editable-date well"></div>', /** @property inputclass @default null **/ inputclass: null, /** Format used for sending value to server. Also applied when converting date from <code>data-value</code> attribute.<br> Possible tokens are: <code>d, dd, m, mm, yy, yyyy, h, i</code> @property format @type string @default yyyy-mm-dd hh:ii **/ format:'yyyy-mm-dd hh:ii', formatType:'standard', /** Format used for displaying date. Also applied when converting date from element's text on init. If not specified equals to <code>format</code> @property viewformat @type string @default null **/ viewformat: null, /** Configuration of datetimepicker. Full list of options: https://github.com/smalot/bootstrap-datetimepicker @property datetimepicker @type object @default { } **/ datetimepicker:{ todayHighlight: false, autoclose: false }, /** Text shown as clear date button. If <code>false</code> clear button will not be rendered. @property clear @type boolean|string @default 'x clear' **/ clear: '&times; clear' }); $.fn.editabletypes.datetime = DateTime; }(window.jQuery)); /** Bootstrap datetimefield input - datetime input for inline mode. Shows normal <input type="text"> and binds popup datetimepicker. Automatically shown in inline mode. @class datetimefield @extends datetime **/ (function ($) { "use strict"; var DateTimeField = function (options) { this.init('datetimefield', options, DateTimeField.defaults); this.initPicker(options, DateTimeField.defaults); }; $.fn.editableutils.inherit(DateTimeField, $.fn.editabletypes.datetime); $.extend(DateTimeField.prototype, { render: function () { this.$input = this.$tpl.find('input'); this.setClass(); this.setAttr('placeholder'); this.$tpl.datetimepicker(this.options.datetimepicker); //need to disable original event handlers this.$input.off('focus keydown'); //update value of datepicker this.$input.keyup($.proxy(function(){ this.$tpl.removeData('date'); this.$tpl.datetimepicker('update'); }, this)); }, value2input: function(value) { this.$input.val(this.value2html(value)); this.$tpl.datetimepicker('update'); }, input2value: function() { return this.html2value(this.$input.val()); }, activate: function() { $.fn.editabletypes.text.prototype.activate.call(this); }, autosubmit: function() { //reset autosubmit to empty } }); DateTimeField.defaults = $.extend({}, $.fn.editabletypes.datetime.defaults, { /** @property tpl **/ tpl:'<div class="input-append date"><input type="text"/><span class="add-on"><i class="icon-th"></i></span></div>', /** @property inputclass @default 'input-medium' **/ inputclass: 'input-medium', /* datetimepicker config */ datetimepicker:{ todayHighlight: false, autoclose: true } }); $.fn.editabletypes.datetimefield = DateTimeField; }(window.jQuery));
ajax/libs/core-js/0.1.2/library.js
tresni/cdnjs
/** * Core.js 0.1.1 * https://github.com/zloirock/core-js * License: http://rock.mit-license.org * © 2014 Denis Pushkarev */ !function(returnThis, framework, undefined){ 'use strict'; /****************************************************************************** * Module : common * ******************************************************************************/ var global = returnThis() // Shortcuts for [[Class]] & property names , OBJECT = 'Object' , FUNCTION = 'Function' , ARRAY = 'Array' , STRING = 'String' , NUMBER = 'Number' , REGEXP = 'RegExp' , DATE = 'Date' , MAP = 'Map' , SET = 'Set' , WEAKMAP = 'WeakMap' , WEAKSET = 'WeakSet' , SYMBOL = 'Symbol' , PROMISE = 'Promise' , MATH = 'Math' , ARGUMENTS = 'Arguments' , PROTOTYPE = 'prototype' , CONSTRUCTOR = 'constructor' , TO_STRING = 'toString' , TO_LOCALE = 'toLocaleString' , HAS_OWN = 'hasOwnProperty' , FOR_EACH = 'forEach' , PROCESS = 'process' , CREATE_ELEMENT = 'createElement' // Aliases global objects and prototypes , Function = global[FUNCTION] , Object = global[OBJECT] , Array = global[ARRAY] , String = global[STRING] , Number = global[NUMBER] , RegExp = global[REGEXP] , Date = global[DATE] , Map = global[MAP] , Set = global[SET] , WeakMap = global[WEAKMAP] , WeakSet = global[WEAKSET] , Symbol = global[SYMBOL] , Math = global[MATH] , TypeError = global.TypeError , setTimeout = global.setTimeout , clearTimeout = global.clearTimeout , setImmediate = global.setImmediate , clearImmediate = global.clearImmediate , process = global[PROCESS] , nextTick = process && process.nextTick , document = global.document , navigator = global.navigator , define = global.define , ArrayProto = Array[PROTOTYPE] , ObjectProto = Object[PROTOTYPE] , FunctionProto = Function[PROTOTYPE] , Infinity = 1 / 0 , core = {} , path = framework ? global : core; // http://jsperf.com/core-js-isobject function isObject(it){ return it != null && (typeof it == 'object' || typeof it == 'function'); } function isFunction(it){ return typeof it == 'function'; } // Native function? var isNative = ctx(/./.test, /\[native code\]\s*\}\s*$/, 1); // Object internal [[Class]] or toStringTag // http://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring var toString = ObjectProto[TO_STRING]; var buildIn = { Undefined: 1, Null: 1, Array: 1, String: 1, Arguments: 1, Function: 1, Error: 1, Boolean: 1, Number: 1, Date: 1, RegExp: 1 } , TO_STRING_TAG = TO_STRING + 'Tag'; function setToStringTag(it, tag, stat){ if(it)has(it = stat ? it : it[PROTOTYPE], SYMBOL_TAG) || hidden(it, SYMBOL_TAG, tag); } function cof(it){ return it == undefined ? it === undefined ? 'Undefined' : 'Null' : toString.call(it).slice(8, -1); } function classof(it){ var klass = cof(it), tag; return klass == OBJECT && (tag = it[SYMBOL_TAG]) ? has(buildIn, tag) ? '~' + tag : tag : klass; } // Function var apply = FunctionProto.apply , call = FunctionProto.call; // Placeholder core._ = path._ = framework ? path._ || {} : {}; // Partial apply function part(/* ...args */){ var length = arguments.length , args = Array(length) , i = 0 , _ = path._ , holder = false; while(length > i)if((args[i] = arguments[i++]) === _)holder = true; return partial(this, args, length, holder, _, false); } // Internal partial application & context binding function partial(fn, argsPart, lengthPart, holder, _, bind, context){ assertFunction(fn); return function(/* ...args */){ var that = bind ? context : this , length = arguments.length , i = 0, j = 0, args; if(!holder && !length)return invoke(fn, argsPart, that); args = argsPart.slice(); if(holder)for(;lengthPart > i; i++)if(args[i] === _)args[i] = arguments[j++]; while(length > j)args.push(arguments[j++]); return invoke(fn, args, that); } } // Optional / simple context binding function ctx(fn, that, length){ assertFunction(fn); if(~length && that === undefined)return fn; switch(length){ case 1: return function(a){ return fn.call(that, a); } case 2: return function(a, b){ return fn.call(that, a, b); } case 3: return function(a, b, c){ return fn.call(that, a, b, c); } } return function(/* ...args */){ return fn.apply(that, arguments); } } // Fast apply // http://jsperf.lnkit.com/fast-apply/5 function invoke(fn, args, that){ var un = that === undefined; switch(args.length | 0){ case 0: return un ? fn() : fn.call(that); case 1: return un ? fn(args[0]) : fn.call(that, args[0]); case 2: return un ? fn(args[0], args[1]) : fn.call(that, args[0], args[1]); case 3: return un ? fn(args[0], args[1], args[2]) : fn.call(that, args[0], args[1], args[2]); case 4: return un ? fn(args[0], args[1], args[2], args[3]) : fn.call(that, args[0], args[1], args[2], args[3]); case 5: return un ? fn(args[0], args[1], args[2], args[3], args[4]) : fn.call(that, args[0], args[1], args[2], args[3], args[4]); } return fn.apply(that, args); } // Object: var create = Object.create , getPrototypeOf = Object.getPrototypeOf , defineProperty = Object.defineProperty , defineProperties = Object.defineProperties , getOwnDescriptor = Object.getOwnPropertyDescriptor , getKeys = Object.keys , getNames = Object.getOwnPropertyNames , getSymbols = Object.getOwnPropertySymbols , ownKeys = function(it){ return getSymbols ? getNames(it).concat(getSymbols(it)) : getNames(it); } , has = ctx(call, ObjectProto[HAS_OWN], 2) // Dummy, fix for not array-like ES3 string in es5 module , ES5Object = Object; // 19.1.2.1 Object.assign(target, source, ...) var assign = Object.assign || function(target, source){ var T = Object(target) , l = arguments.length , i = 1; while(l > i){ var S = ES5Object(arguments[i++]) , keys = getKeys(S) , length = keys.length , j = 0 , key; while(length > j)T[key = keys[j++]] = S[key]; } return T; } function createObjectToArray(isEntries){ return function(object){ var O = ES5Object(object) , keys = getKeys(object) , length = keys.length , i = 0 , result = Array(length) , key; if(isEntries)while(length > i)result[i] = [key = keys[i++], O[key]]; else while(length > i)result[i] = O[keys[i++]]; return result; } } function keyOf(object, el){ var O = ES5Object(object) , keys = getKeys(O) , length = keys.length , index = 0 , key; while(length > index)if(O[key = keys[index++]] === el)return key; } // Array // array('str1,str2,str3') => ['str1', 'str2', 'str3'] function array(it){ return String(it).split(','); } var push = ArrayProto.push , unshift = ArrayProto.unshift , slice = ArrayProto.slice , splice = ArrayProto.splice , indexOf = ArrayProto.indexOf , forEach = ArrayProto[FOR_EACH]; /* * 0 -> forEach * 1 -> map * 2 -> filter * 3 -> some * 4 -> every * 5 -> find * 6 -> findIndex */ function createArrayMethod(type){ var isMap = type == 1 , isFilter = type == 2 , isSome = type == 3 , isEvery = type == 4 , isFindIndex = type == 6 , noholes = type == 5 || isFindIndex; return function(callbackfn, that /* = undefined */){ var f = ctx(callbackfn, that, 3) , O = Object(this) , self = ES5Object(O) , length = toLength(self.length) , index = 0 , result = isMap ? Array(length) : isFilter ? [] : undefined , val, res; for(;length > index; index++)if(noholes || index in self){ val = self[index]; res = f(val, index, O); if(type){ if(isMap)result[index] = res; // map else if(res)switch(type){ case 3: return true; // some case 5: return val; // find case 6: return index; // findIndex case 2: result.push(val); // filter } else if(isEvery)return false; // every } } return isFindIndex ? -1 : isSome || isEvery ? isEvery : result; } } function createArrayContains(isContains){ return function(el, fromIndex /* = 0 */){ var O = ES5Object(this) , length = toLength(O.length) , index = max(getPositiveIndex(O, fromIndex), 0); if(isContains && el != el){ for(;length > index; index++)if(sameNaN(O[index]))return index; } else for(;length > index; index++)if(isContains || index in O){ if(O[index] === el)return isContains ? true : index; } return isContains ? false : -1; } } // Simple reduce to object function turn(mapfn, target /* = [] */){ assertFunction(mapfn); var memo = target == undefined ? [] : Object(target) , O = ES5Object(this) , length = toLength(O.length) , index = 0; for(;length > index; index++){ if(mapfn(memo, O[index], index, this) === false)break; } return memo; } function generic(A, B){ // strange IE quirks mode bug -> use typeof vs isFunction return typeof A == 'function' ? A : B; } // Math var MAX_SAFE_INTEGER = 0x1fffffffffffff // pow(2, 53) - 1 == 9007199254740991 , ceil = Math.ceil , floor = Math.floor , max = Math.max , min = Math.min , pow = Math.pow , random = Math.random , trunc = Math.trunc || function(it){ return (it > 0 ? floor : ceil)(it); } // 7.2.3 SameValue(x, y) function same(x, y){ return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; } // 20.1.2.4 Number.isNaN(number) function sameNaN(number){ return number != number; } // 7.1.4 ToInteger function toInteger(it){ return isNaN(it) ? 0 : trunc(it); } // 7.1.15 ToLength function toLength(it){ return it > 0 ? min(toInteger(it), MAX_SAFE_INTEGER) : 0; } function getPositiveIndex(O, index){ var index = toInteger(index); if(index < 0)index += toLength(O.length); return index; } function createReplacer(regExp, replace, isStatic){ var replacer = isObject(replace) ? function(part){ return replace[part]; } : replace; return function(it){ return String(isStatic ? it : this).replace(regExp, replacer); } } // Assertion & errors var REDUCE_ERROR = 'Reduce of empty object with no initial value'; function assert(condition, msg1, msg2){ if(!condition)throw TypeError(msg2 ? msg1 + msg2 : msg1); } function assertFunction(it){ assert(isFunction(it), it, ' is not a function!'); return it; } function assertObject(it){ assert(isObject(it), it, ' is not an object!'); return it; } function assertInstance(it, Constructor, name){ assert(it instanceof Constructor, name, ": use the 'new' operator!"); } // Property descriptors & Symbol function descriptor(bitmap, value){ return { enumerable : !(bitmap & 1), configurable: !(bitmap & 2), writable : !(bitmap & 4), value : value } } function simpleSet(object, key, value){ object[key] = value; return object; } function createDefiner(bitmap){ return DESC ? function(object, key, value){ return defineProperty(object, key, descriptor(bitmap, value)); } : simpleSet; } function uid(key){ return SYMBOL + '(' + key + ')_' + (++sid + random())[TO_STRING](36); } // The engine works fine with descriptors? Thank's IE8 for his funny defineProperty. var DESC = !!function(){try{return defineProperty({}, 0, ObjectProto)}catch(e){}}() , sid = 0 , hidden = createDefiner(1) , symbol = Symbol || uid , set = Symbol ? simpleSet : hidden; // Iterators var ITERATOR = 'iterator' , SYMBOL_ITERATOR = Symbol && ITERATOR in Symbol ? Symbol[ITERATOR] : uid(SYMBOL + '.' + ITERATOR) , SYMBOL_TAG = Symbol && TO_STRING_TAG in Symbol ? Symbol[TO_STRING_TAG] : uid(SYMBOL + '.' + TO_STRING_TAG) , FF_ITERATOR = '@@' + ITERATOR , SUPPORT_FF_ITER = FF_ITERATOR in ArrayProto , ITER = symbol('iter') , SHIM = symbol('shim') , KEY = 1 , VALUE = 2 , Iterators = {} , IteratorPrototype = {} , COLLECTION_KEYS; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() setIterator(IteratorPrototype, returnThis); function setIterator(O, value){ hidden(O, SYMBOL_ITERATOR, value); // Add iterator for FF iterator protocol SUPPORT_FF_ITER && hidden(O, FF_ITERATOR, value); } function createIterator(Constructor, NAME, next, proto){ Constructor[PROTOTYPE] = create(proto || IteratorPrototype, {next: descriptor(1, next)}); // 22.1.5.2.3 %ArrayIteratorPrototype%[@@toStringTag] // 23.1.5.2.3 %MapIteratorPrototype%[@@toStringTag] // 23.2.5.2.3 %SetIteratorPrototype%[@@toStringTag] setToStringTag(Constructor, NAME + ' Iterator'); } function defineIterator(Constructor, NAME, value){ var proto = Constructor[PROTOTYPE] , HAS_FF_ITER = has(proto, FF_ITERATOR); var iter = has(proto, SYMBOL_ITERATOR) ? proto[SYMBOL_ITERATOR] : HAS_FF_ITER ? proto[FF_ITERATOR] : value; if(framework){ // Define iterator setIterator(proto, iter); // FF fix if(HAS_FF_ITER)setIterator(getPrototypeOf(iter.call(new Constructor)), returnThis); } // Plug for library Iterators[NAME] = iter; // FF & v8 fix Iterators[NAME + ' Iterator'] = returnThis; } function iterResult(done, value){ return {value: value, done: !!done}; } function isIterable(it){ return (it != undefined && SYMBOL_ITERATOR in it) || has(Iterators, classof(it)); } function getIterator(it){ return assertObject((it[SYMBOL_ITERATOR] || Iterators[classof(it)]).call(it)); } function stepCall(fn, value, entries){ return entries ? invoke(fn, value) : fn(value); } function forOf(iterable, entries, fn, that){ var iterator = getIterator(iterable) , f = ctx(fn, that, entries ? 2 : 1) , step; while(!(step = iterator.next()).done)if(stepCall(f, step.value, entries) === false)return; } // DOM var html = document && document.documentElement; // core var NODE = cof(process) == PROCESS , old = global.core // type bitmap , FORCED = 1 , GLOBAL = 2 , STATIC = 4 , PROTO = 8 , BIND = 16 , WRAP = 32; function $define(type, name, source){ var key, own, out, exp , isGlobal = type & GLOBAL , target = isGlobal ? global : (type & STATIC) ? global[name] : (global[name] || ObjectProto)[PROTOTYPE] , exports = isGlobal ? core : core[name] || (core[name] = {}); if(isGlobal)source = name; for(key in source){ // there is a similar native own = !(type & FORCED) && target && key in target && (!isFunction(target[key]) || isNative(target[key])); // export native or passed out = (own ? target : source)[key]; // bind timers to global for call from export context if(type & BIND && own)exp = ctx(out, global); // wrap global constructors for prevent change them in library else if(type & WRAP && !framework && target[key] == out){ exp = function(param){ return this instanceof out ? new out(param) : out(param); } exp[PROTOTYPE] = out[PROTOTYPE]; } else exp = type & PROTO && isFunction(out) ? ctx(call, out) : out; // export if(exports[key] != out)exports[key] = exp; // extend global framework && target && !own && (isGlobal || delete target[key]) && hidden(target, key, out); } } // CommonJS export if(NODE)module.exports = core; // RequireJS export if(isFunction(define) && define.amd)define(function(){return core}); // Export to global object if(!NODE || framework){ core.noConflict = function(){ global.core = old; return core; } global.core = core; } /****************************************************************************** * Module : es5 * ******************************************************************************/ // ECMAScript 5 shim !function(IS_ENUMERABLE, Empty, _classof, $PROTO){ if(!DESC){ getOwnDescriptor = function(O, P){ if(has(O, P))return descriptor(!ObjectProto[IS_ENUMERABLE].call(O, P), O[P]); }; defineProperty = function(O, P, Attributes){ if('value' in Attributes)assertObject(O)[P] = Attributes.value; return O; }; defineProperties = function(O, Properties){ assertObject(O); var keys = getKeys(Properties) , length = keys.length , i = 0 , P, Attributes; while(length > i){ P = keys[i++]; Attributes = Properties[P]; if('value' in Attributes)O[P] = Attributes.value; } return O; }; } $define(STATIC + FORCED * !DESC, OBJECT, { // 19.1.2.6 / 15.2.3.3 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: getOwnDescriptor, // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) defineProperty: defineProperty, // 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties) defineProperties: defineProperties }); // IE 8- don't enum bug keys var keys1 = [CONSTRUCTOR, HAS_OWN, 'isPrototypeOf', IS_ENUMERABLE, TO_LOCALE, TO_STRING, 'valueOf'] // Additional keys for getOwnPropertyNames , keys2 = keys1.concat('length', PROTOTYPE) , keysLen1 = keys1.length; // Create object with `null` prototype: use iframe Object with cleared prototype function createDict(){ // Thrash, waste and sodomy: IE GC bug var iframe = document[CREATE_ELEMENT]('iframe') , i = keysLen1 , iframeDocument; iframe.style.display = 'none'; html.appendChild(iframe); iframe.src = 'javascript:'; // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write('<script>document.F=Object</script>'); iframeDocument.close(); createDict = iframeDocument.F; while(i--)delete createDict[PROTOTYPE][keys1[i]]; return createDict(); } function createGetKeys(names, length, isNames){ return function(object){ var O = ES5Object(object) , i = 0 , result = [] , key; for(key in O)if(key != $PROTO)has(O, key) && result.push(key); // Don't enum bug & hidden keys while(length > i)if(has(O, key = names[i++])){ ~indexOf.call(result, key) || result.push(key); } return result; } } $define(STATIC, OBJECT, { // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) getPrototypeOf: getPrototypeOf = getPrototypeOf || function(O){ if(has(assertObject(O), $PROTO))return O[$PROTO]; if(isFunction(O[CONSTRUCTOR]) && O instanceof O[CONSTRUCTOR]){ return O[CONSTRUCTOR][PROTOTYPE]; } return O instanceof Object ? ObjectProto : null; }, // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) getOwnPropertyNames: getNames = getNames || createGetKeys(keys2, keys2.length, true), // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) create: create = create || function(O, /*?*/Properties){ var result if(O !== null){ Empty[PROTOTYPE] = assertObject(O); result = new Empty(); Empty[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf shim result[CONSTRUCTOR][PROTOTYPE] === O || (result[$PROTO] = O); } else result = createDict(); return Properties === undefined ? result : defineProperties(result, Properties); }, // 19.1.2.14 / 15.2.3.14 Object.keys(O) keys: getKeys = getKeys || createGetKeys(keys1, keysLen1, false) }); // 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...) $define(PROTO, FUNCTION, { bind: function(that /*, args... */){ var fn = assertFunction(this) , partArgs = slice.call(arguments, 1); function bound(/* args... */){ var args = partArgs.concat(slice.call(arguments)); if(this instanceof bound){ var instance = create(fn[PROTOTYPE]) , result = invoke(fn, args, instance); return isObject(result) ? result : instance; } return invoke(fn, args, that); } return bound; } }); // Fix for not array-like ES3 string function arrayMethodFix(fn){ return function(){ return fn.apply(ES5Object(this), arguments); } } if(!(0 in Object('q') && 'q'[0] == 'q')){ ES5Object = function(it){ return cof(it) == STRING ? it.split('') : Object(it); } slice = arrayMethodFix(slice); } $define(PROTO + FORCED * (ES5Object != Object), ARRAY, { slice: slice, join: arrayMethodFix(ArrayProto.join) }); // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) $define(STATIC, ARRAY, { isArray: function(arg){ return cof(arg) == ARRAY } }); function createArrayReduce(isRight){ return function(callbackfn, memo){ assertFunction(callbackfn); var O = ES5Object(this) , length = toLength(O.length) , index = isRight ? length - 1 : 0 , i = isRight ? -1 : 1; if(2 > arguments.length)for(;;){ if(index in O){ memo = O[index]; index += i; break; } index += i; assert(isRight ? index >= 0 : length > index, REDUCE_ERROR); } for(;isRight ? index >= 0 : length > index; index += i)if(index in O){ memo = callbackfn(memo, O[index], index, this); } return memo; } } $define(PROTO, ARRAY, { // 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg]) forEach: forEach = forEach || createArrayMethod(0), // 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg]) map: createArrayMethod(1), // 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg]) filter: createArrayMethod(2), // 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg]) some: createArrayMethod(3), // 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg]) every: createArrayMethod(4), // 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue]) reduce: createArrayReduce(false), // 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue]) reduceRight: createArrayReduce(true), // 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex]) indexOf: indexOf = indexOf || createArrayContains(false), // 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex]) lastIndexOf: function(el, fromIndex /* = @[*-1] */){ var O = ES5Object(this) , length = toLength(O.length) , index = length - 1; if(arguments.length > 1)index = min(index, toInteger(fromIndex)); if(index < 0)index = toLength(length + index); for(;index >= 0; index--)if(index in O)if(O[index] === el)return index; return -1; } }); // 21.1.3.25 / 15.5.4.20 String.prototype.trim() $define(PROTO, STRING, {trim: createReplacer(/^\s*([\s\S]*\S)?\s*$/, '$1')}); // 20.3.3.1 / 15.9.4.4 Date.now() $define(STATIC, DATE, {now: function(){ return +new Date; }}); if(_classof(function(){return arguments}()) == OBJECT)classof = function(it){ var cof = _classof(it); return cof == OBJECT && isFunction(it.callee) ? ARGUMENTS : cof; } }('propertyIsEnumerable', Function(), classof, symbol(PROTOTYPE)); /****************************************************************************** * Module : global * ******************************************************************************/ $define(GLOBAL, {global: global}); /****************************************************************************** * Module : es6_symbol * ******************************************************************************/ // ECMAScript 6 symbols shim !function(TAG, SymbolRegistry){ // 19.4.1.1 Symbol([description]) if(!isNative(Symbol)){ Symbol = function(description){ assert(!(this instanceof Symbol), SYMBOL + ' is not a ' + CONSTRUCTOR); var tag = uid(description); defineProperty(ObjectProto, tag, { configurable: true, set: function(value){ hidden(this, tag, value); } }); return set(create(Symbol[PROTOTYPE]), TAG, tag); } hidden(Symbol[PROTOTYPE], TO_STRING, function(){ return this[TAG]; }); } $define(GLOBAL + WRAP, {Symbol: Symbol}); $define(STATIC, SYMBOL, { // 19.4.2.2 Symbol.for(key) 'for': function(key){ return has(SymbolRegistry, key += '') ? SymbolRegistry[key] : SymbolRegistry[key] = Symbol(key); }, // 19.4.2.6 Symbol.iterator iterator: SYMBOL_ITERATOR, // 19.4.2.7 Symbol.keyFor(sym) keyFor: part.call(keyOf, SymbolRegistry), // 19.4.2.10 Symbol.toStringTag toStringTag: SYMBOL_TAG = TO_STRING_TAG in Symbol ? Symbol[TO_STRING_TAG] : Symbol(SYMBOL + '.' + TO_STRING_TAG), pure: symbol, set: set }); setToStringTag(Symbol, SYMBOL); // 26.1.11 Reflect.ownKeys (target) $define(GLOBAL, {Reflect: {ownKeys: ownKeys}}); }(symbol('tag'), {}); /****************************************************************************** * Module : es6 * ******************************************************************************/ // ECMAScript 6 shim !function(isFinite, tmp){ $define(STATIC, OBJECT, { // 19.1.3.1 Object.assign(target, source) assign: assign, // 19.1.3.10 Object.is(value1, value2) is: same }); // 19.1.3.19 Object.setPrototypeOf(O, proto) // Works with __proto__ only. Old v8 can't works with null proto objects. '__proto__' in ObjectProto && function(buggy, set){ try { set = ctx(call, getOwnDescriptor(ObjectProto, '__proto__').set, 2); set({}, ArrayProto); } catch(e){ buggy = true } $define(STATIC, OBJECT, { setPrototypeOf: function(O, proto){ assertObject(O); assert(proto === null || isObject(proto), proto, ": can't set as prototype!"); if(buggy)O.__proto__ = proto; else set(O, proto); return O; } }); }(); // 20.1.2.3 Number.isInteger(number) var isInteger = Number.isInteger || function(it){ return isFinite(it) && floor(it) === it; } // 20.2.2.28 Math.sign(x) , sign = Math.sign || function sign(it){ return (it = +it) == 0 || it != it ? it : it < 0 ? -1 : 1; } , abs = Math.abs , exp = Math.exp , log = Math.log , sqrt = Math.sqrt; // 20.2.2.5 Math.asinh(x) function asinh(x){ return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : log(x + sqrt(x * x + 1)); } $define(STATIC, NUMBER, { // 20.1.2.1 Number.EPSILON EPSILON: pow(2, -52), // 20.1.2.2 Number.isFinite(number) isFinite: function(it){ return typeof it == 'number' && isFinite(it); }, // 20.1.2.3 Number.isInteger(number) isInteger: isInteger, // 20.1.2.4 Number.isNaN(number) isNaN: sameNaN, // 20.1.2.5 Number.isSafeInteger(number) isSafeInteger: function(number){ return isInteger(number) && abs(number) <= MAX_SAFE_INTEGER; }, // 20.1.2.6 Number.MAX_SAFE_INTEGER MAX_SAFE_INTEGER: MAX_SAFE_INTEGER, // 20.1.2.10 Number.MIN_SAFE_INTEGER MIN_SAFE_INTEGER: -MAX_SAFE_INTEGER, // 20.1.2.12 Number.parseFloat(string) parseFloat: parseFloat, // 20.1.2.13 Number.parseInt(string, radix) parseInt: parseInt }); $define(STATIC, MATH, { // 20.2.2.3 Math.acosh(x) acosh: function(x){ return log(x + sqrt(x * x - 1)); }, // 20.2.2.5 Math.asinh(x) asinh: asinh, // 20.2.2.7 Math.atanh(x) atanh: function(x){ return x == 0 ? +x : log((1 + +x) / (1 - x)) / 2; }, // 20.2.2.9 Math.cbrt(x) cbrt: function(x){ return sign(x) * pow(abs(x), 1 / 3); }, // 20.2.2.11 Math.clz32 (x) clz32: function(x){ return (x >>>= 0) ? 32 - x[TO_STRING](2).length : 32; }, // 20.2.2.12 Math.cosh(x) cosh: function(x){ return (exp(x) + exp(-x)) / 2; }, // 20.2.2.14 Math.expm1(x) expm1: function(x){ return x == 0 ? +x : x > -1e-6 && x < 1e-6 ? +x + x * x / 2 : exp(x) - 1; }, // 20.2.2.16 Math.fround(x) // TODO // 20.2.2.17 Math.hypot([value1[, value2[, … ]]]) hypot: function(value1, value2){ var sum = 0 , length = arguments.length , value; while(length--){ value = +arguments[length]; if(value == Infinity || value == -Infinity)return Infinity; sum += value * value; } return sqrt(sum); }, // 20.2.2.18 Math.imul(x, y) imul: function(x, y){ var UInt16 = 0xffff , xh = UInt16 & x >>> 16 , xl = UInt16 & x , yh = UInt16 & y >>> 16 , yl = UInt16 & y; return 0 | xl * yl + (xh * yl + xl * yh << 16 >>> 0); }, // 20.2.2.20 Math.log1p(x) log1p: function(x){ return x > -1e-8 && x < 1e-8 ? x - x * x / 2 : log(1 + +x); }, // 20.2.2.21 Math.log10(x) log10: function(x){ return log(x) / Math.LN10; }, // 20.2.2.22 Math.log2(x) log2: function(x){ return log(x) / Math.LN2; }, // 20.2.2.28 Math.sign(x) sign: sign, // 20.2.2.30 Math.sinh(x) sinh: function(x){ return x == 0 ? +x : (exp(x) - exp(-x)) / 2; }, // 20.2.2.33 Math.tanh(x) tanh: function(x){ return isFinite(x) ? x == 0 ? +x : (exp(x) - exp(-x)) / (exp(x) + exp(-x)) : sign(x); }, // 20.2.2.34 Math.trunc(x) trunc: trunc }); // 20.2.1.9 Math[@@toStringTag] setToStringTag(Math, MATH, true); // 21.1.2.2 String.fromCodePoint(...codePoints) // TODO // 21.1.2.4 String.raw(callSite, ...substitutions) // TODO $define(PROTO, STRING, { // 21.1.3.3 String.prototype.codePointAt(pos) // TODO // 21.1.3.6 String.prototype.contains(searchString, position = 0) contains: function(searchString, position /* = 0 */){ return !!~String(this).indexOf(searchString, position); }, // 21.1.3.7 String.prototype.endsWith(searchString [, endPosition]) endsWith: function(searchString, endPosition /* = @length */){ var length = this.length , end = toLength(min(endPosition === undefined ? length : endPosition, length)); searchString += ''; return String(this).slice(end - searchString.length, end) === searchString; }, // 21.1.3.13 String.prototype.repeat(count) repeat: function(count){ var str = '' + this , result = '' , n = toInteger(count); assert(0 <= n, "Count can't be negative"); for(;n > 0; (n >>>= 1) && (str += str))if(n & 1)result += str; return result; }, // 21.1.3.18 String.prototype.startsWith(searchString [, position ]) startsWith: function(searchString, position /* = 0 */){ var index = toLength(min(position, this.length)); searchString += ''; return String(this).slice(index, index + searchString.length) === searchString; } }); $define(STATIC, ARRAY, { // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) from: function(arrayLike, mapfn /* -> it */, that /* = undefind */){ var O = ES5Object(arrayLike) , result = new (generic(this, Array)) , mapping = mapfn !== undefined , f = mapping ? ctx(mapfn, that, 2) : undefined , index = 0 , length; if(isIterable(O))for(var iter = getIterator(O), step; !(step = iter.next()).done;){ result[index] = mapping ? f(step.value, index) : step.value; index++; } else for(length = toLength(O.length); length > index; index++){ result[index] = mapping ? f(O[index], index) : O[index]; } result.length = index; return result; }, // 22.1.2.3 Array.of( ...items) of: function(/* ...args */){ var index = 0 , length = arguments.length , result = new (generic(this, Array))(length); while(length > index)result[index] = arguments[index++]; result.length = length; return result; } }); $define(PROTO, ARRAY, { // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) // TODO // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) fill: function(value, start /* = 0 */, end /* = @length */){ var length = toLength(this.length) , index = max(getPositiveIndex(this, start), 0) , endPos; if(end === undefined)endPos = length; else { endPos = toInteger(end); if(endPos < 0)endPos += length; endPos = min(endPos, length); } while(endPos > index)this[index++] = value; return this; }, // 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined) find: createArrayMethod(5), // 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined) findIndex: createArrayMethod(6) }); // 24.3.3 JSON[@@toStringTag] setToStringTag(global.JSON, 'JSON', true); // 19.1.3.6 Object.prototype.toString() if(framework){ tmp[SYMBOL_TAG] = 'x'; if(cof(tmp) != 'x')hidden(ObjectProto, TO_STRING, function(){ return '[object ' + classof(this) + ']'; }); } }(isFinite, {}); /****************************************************************************** * Module : immediate * ******************************************************************************/ // setImmediate shim // Node.js 0.9+ & IE10+ has setImmediate, else: isFunction(setImmediate) && isFunction(clearImmediate) || function(ONREADYSTATECHANGE){ var postMessage = global.postMessage , addEventListener = global.addEventListener , MessageChannel = global.MessageChannel , counter = 0 , queue = {} , defer, channel, port; setImmediate = function(fn){ var args = [], i = 1; while(arguments.length > i)args.push(arguments[i++]); queue[++counter] = function(){ invoke(isFunction(fn) ? fn : Function(fn), args); } defer(counter); return counter; } clearImmediate = function(id){ delete queue[id]; } function run(id){ if(has(queue, id)){ var fn = queue[id]; delete queue[id]; fn(); } } function listner(event){ run(event.data); } // Node.js 0.8- if(NODE){ defer = function(id){ nextTick(part.call(run, id)); } // Modern browsers, skip implementation for WebWorkers // IE8 has postMessage, but it's sync & typeof its postMessage is object } else if(addEventListener && isFunction(postMessage) && !global.importScripts){ defer = function(id){ postMessage(id, '*'); } addEventListener('message', listner, false); // WebWorkers } else if(isFunction(MessageChannel)){ channel = new MessageChannel; port = channel.port2; channel.port1.onmessage = listner; defer = ctx(port.postMessage, port, 1); // IE8- } else if(document && ONREADYSTATECHANGE in document[CREATE_ELEMENT]('script')){ defer = function(id){ html.appendChild(document[CREATE_ELEMENT]('script'))[ONREADYSTATECHANGE] = function(){ html.removeChild(this); run(id); } } // Rest old browsers } else { defer = function(id){ setTimeout(part.call(run, id), 0); } } }('onreadystatechange'); $define(GLOBAL + BIND, { setImmediate: setImmediate, clearImmediate: clearImmediate }); /****************************************************************************** * Module : es6_promise * ******************************************************************************/ // ES6 promises shim // Based on https://github.com/getify/native-promise-only/ !function(Promise, test){ isFunction(Promise) && isFunction(Promise.resolve) && Promise.resolve(test = new Promise(Function())) == test || function(asap, DEF){ function isThenable(o){ var then; if(isObject(o))then = o.then; return isFunction(then) ? then : false; } function notify(def){ var chain = def.chain; chain.length && asap(function(){ var msg = def.msg , ok = def.state == 1 , i = 0; while(chain.length > i)!function(react){ var cb = ok ? react.ok : react.fail , ret, then; try { if(cb){ ret = cb === true ? msg : cb(msg); if(ret === react.P){ react.rej(TypeError(PROMISE + '-chain cycle')); } else if(then = isThenable(ret)){ then.call(ret, react.res, react.rej); } else react.res(ret); } else react.rej(msg); } catch(err){ react.rej(err); } }(chain[i++]); chain.length = 0; }); } function resolve(msg){ var def = this , then, wrapper; if(def.done)return; def.done = true; def = def.def || def; // unwrap try { if(then = isThenable(msg)){ wrapper = {def: def, done: false}; // wrap then.call(msg, ctx(resolve, wrapper, 1), ctx(reject, wrapper, 1)); } else { def.msg = msg; def.state = 1; notify(def); } } catch(err){ reject.call(wrapper || {def: def, done: false}, err); // wrap } } function reject(msg){ var def = this; if(def.done)return; def.done = true; def = def.def || def; // unwrap def.msg = msg; def.state = 2; notify(def); } // 25.4.3.1 Promise(executor) Promise = function(executor){ assertFunction(executor); assertInstance(this, Promise, PROMISE); var def = {chain: [], state: 0, done: false, msg: undefined}; hidden(this, DEF, def); try { executor(ctx(resolve, def, 1), ctx(reject, def, 1)); } catch(err){ reject.call(def, err); } } // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) hidden(Promise[PROTOTYPE], 'then', function(onFulfilled, onRejected){ var react = { ok: isFunction(onFulfilled) ? onFulfilled : true, fail: isFunction(onRejected) ? onRejected : false } , P = react.P = new this[CONSTRUCTOR](function(resolve, reject){ react.res = assertFunction(resolve); react.rej = assertFunction(reject); }), def = this[DEF]; def.chain.push(react); def.state && notify(def); return P; }); // 25.4.5.1 Promise.prototype.catch(onRejected) hidden(Promise[PROTOTYPE], 'catch', function(onRejected){ return this.then(undefined, onRejected); }); // 25.4.4.1 Promise.all(iterable) hidden(Promise, 'all', function(iterable){ var Promise = this , values = []; return new Promise(function(resolve, reject){ forOf(iterable, false, push, values); var remaining = values.length , results = Array(remaining); if(remaining)forEach.call(values, function(promise, index){ Promise.resolve(promise).then(function(value){ results[index] = value; --remaining || resolve(results); }, reject); }); else resolve(results); }); }); // 25.4.4.4 Promise.race(iterable) hidden(Promise, 'race', function(iterable){ var Promise = this; return new Promise(function(resolve, reject){ forOf(iterable, false, function(promise){ Promise.resolve(promise).then(resolve, reject); }); }); }); // 25.4.4.5 Promise.reject(r) hidden(Promise, 'reject', function(r){ return new this(function(resolve, reject){ reject(r); }); }); // 25.4.4.6 Promise.resolve(x) hidden(Promise, 'resolve', function(x){ return isObject(x) && getPrototypeOf(x) === this[PROTOTYPE] ? x : new this(function(resolve, reject){ resolve(x); }); }); }(nextTick || setImmediate, symbol('def')); setToStringTag(Promise, PROMISE); $define(GLOBAL + FORCED * !isNative(Promise), {Promise: Promise}); }(global[PROMISE]); /****************************************************************************** * Module : es6_collections * ******************************************************************************/ // ECMAScript 6 collections shim !function(){ var KEYS = COLLECTION_KEYS = symbol('keys') , VALUES = symbol('values') , STOREID = symbol('storeId') , WEAKDATA = symbol('weakData') , WEAKID = symbol('weakId') , SIZE = DESC ? symbol('size') : 'size' , uid = 0 , wid = 0; function getCollection(C, NAME, test, methods, commonMethods, isMap, isWeak){ var ADDER_KEY = isMap ? 'set' : 'add' , init = commonMethods.clear; function initFromIterable(that, iterable){ if(iterable != undefined)forOf(iterable, isMap, that[ADDER_KEY], that); return that; } if(!test){ // create collection constructor C = function(iterable){ assertInstance(this, C, NAME); init.call(this); initFromIterable(this, iterable); } set(C, SHIM, true); assign(C[PROTOTYPE], methods, commonMethods); isWeak || defineProperty(C[PROTOTYPE], 'size', {get: function(){ return this[SIZE]; }}); } else { var Native = C , test_key = {} , collection = new C , adder = collection[ADDER_KEY]; // wrap to init collections from iterable if(!(SYMBOL_ITERATOR in ArrayProto && C.length)){ C = function(iterable){ assertInstance(this, C, NAME); return initFromIterable(new Native, iterable); } C[PROTOTYPE] = Native[PROTOTYPE]; } // fix .add & .set for chaining if(framework && collection[ADDER_KEY](test_key, 1) !== collection){ hidden(C[PROTOTYPE], ADDER_KEY, function(a, b){ adder.call(this, a, b); return this; }); } } setToStringTag(C, NAME); var O = {}; O[NAME] = C; $define(GLOBAL + WRAP + FORCED * !isNative(C), O); return C; } function fastKey(it, create){ // return it with 'S' prefix if it's string or with 'P' prefix for over primitives if(!isObject(it))return (typeof it == 'string' ? 'S' : 'P') + it; // if it hasn't object id - add next if(!has(it, STOREID)){ if(create)hidden(it, STOREID, ++uid); else return ''; } // return object id with 'O' prefix return 'O' + it[STOREID]; } function collectionMethods($VALUES){ return { // 23.1.3.1 Map.prototype.clear() // 23.2.3.2 Set.prototype.clear() clear: function(){ hidden(this, SIZE, 0); hidden(this, KEYS, create(null)); if($VALUES == VALUES)hidden(this, VALUES, create(null)); }, // 23.1.3.3 Map.prototype.delete(key) // 23.2.3.4 Set.prototype.delete(value) 'delete': function(key){ var index = fastKey(key) , keys = this[KEYS] , contains = index in keys; if(contains){ delete keys[index]; if($VALUES == VALUES)delete this[VALUES][index]; this[SIZE]--; } return contains; }, // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) forEach: function(callbackfn, that /* = undefined */){ var f = ctx(callbackfn, that, 3) , values = this[$VALUES] , keys = this[KEYS] , done = {} , k, index; do { for(index in keys){ if(index in done)continue; done[index] = true; f(values[index], keys[index], this); } } while(index != undefined && index != (k = getKeys(keys))[k.length - 1]); }, // 23.1.3.7 Map.prototype.has(key) // 23.2.3.7 Set.prototype.has(value) has: function(key){ return fastKey(key) in this[KEYS]; } } } // 23.1 Map Objects Map = getCollection(Map, MAP, isNative(Map) && has(Map[PROTOTYPE], FOR_EACH), { // 23.1.3.6 Map.prototype.get(key) get: function(key){ return this[VALUES][fastKey(key)]; }, // 23.1.3.9 Map.prototype.set(key, value) set: function(key, value){ var index = fastKey(key, true) , values = this[VALUES]; if(!(index in values)){ this[KEYS][index] = same(key, -0) ? 0 : key; this[SIZE]++; } values[index] = value; return this; } }, collectionMethods(VALUES), true); // 23.2 Set Objects Set = getCollection(Set, SET, isNative(Set) && has(Set[PROTOTYPE], FOR_EACH), { // 23.2.3.1 Set.prototype.add(value) add: function(value){ var index = fastKey(value, true) , values = this[KEYS]; if(!(index in values)){ values[index] = same(value, -0) ? 0 : value; this[SIZE]++; } return this; } }, collectionMethods(KEYS)); function getWeakData(it){ has(it, WEAKDATA) || hidden(it, WEAKDATA, {}); return it[WEAKDATA]; } function weakCollectionHas(key){ return isObject(key) && has(key, WEAKDATA) && has(key[WEAKDATA], this[WEAKID]); } var weakCollectionMethods = { // 23.3.3.1 WeakMap.prototype.clear() // 23.4.3.2 WeakSet.prototype.clear() clear: function(){ hidden(this, WEAKID, wid++); }, // 23.3.3.3 WeakMap.prototype.delete(key) // 23.4.3.4 WeakSet.prototype.delete(value) 'delete': function(key){ return weakCollectionHas.call(this, key) && delete key[WEAKDATA][this[WEAKID]]; }, // 23.3.3.5 WeakMap.prototype.has(key) // 23.4.3.5 WeakSet.prototype.has(value) has: weakCollectionHas }; // 23.3 WeakMap Objects WeakMap = getCollection(WeakMap, WEAKMAP, isNative(WeakMap) && has(WeakMap[PROTOTYPE], 'clear'), { // 23.3.3.4 WeakMap.prototype.get(key) get: function(key){ if(isObject(key) && has(key, WEAKDATA))return key[WEAKDATA][this[WEAKID]]; }, // 23.3.3.6 WeakMap.prototype.set(key, value) set: function(key, value){ getWeakData(assertObject(key))[this[WEAKID]] = value; return this; } }, weakCollectionMethods, true, true); // 23.4 WeakSet Objects WeakSet = getCollection(WeakSet, WEAKSET, isNative(WeakSet), { // 23.4.3.1 WeakSet.prototype.add(value) add: function(value){ getWeakData(assertObject(value))[this[WEAKID]] = true; return this; } }, weakCollectionMethods, false, true); }(); /****************************************************************************** * Module : $for * ******************************************************************************/ !function(ENTRIES, FN){ function $for(iterable, entries){ if(!(this instanceof $for))return new $for(iterable, entries); this[ITER] = getIterator(iterable); this[ENTRIES] = !!entries; } createIterator($for, 'Wrapper', function(){ return this[ITER].next(); }); var $forProto = $for[PROTOTYPE]; setIterator($forProto, function(){ return this[ITER]; // unwrap }); function createChainIterator(next){ function Iter(I, fn, that){ this[ITER] = getIterator(I); this[ENTRIES] = I[ENTRIES]; this[FN] = ctx(fn, that, I[ENTRIES] ? 2 : 1); } createIterator(Iter, 'Chain', next, $forProto); setIterator(Iter[PROTOTYPE], returnThis); // override $forProto iterator return Iter; } var MapIter = createChainIterator(function(){ var step = this[ITER].next(); return step.done ? step : iterResult(0, stepCall(this[FN], step.value, this[ENTRIES])); }); var FilterIter = createChainIterator(function(){ for(;;){ var step = this[ITER].next(); if(step.done || stepCall(this[FN], step.value, this[ENTRIES]))return step; } }); assign($forProto, { of: function(fn, that){ forOf(this, this[ENTRIES], fn, that); }, array: function(fn, that){ var result = []; forOf(fn != undefined ? this.map(fn, that) : this, false, push, result); return result; }, filter: function(fn, that){ return new FilterIter(this, fn, that); }, map: function(fn, that){ return new MapIter(this, fn, that); } }); $for.isIterable = isIterable; $for.getIterator = getIterator; $define(GLOBAL + FORCED, {$for: $for}); }('entries', symbol('fn')); /****************************************************************************** * Module : es6_iterators * ******************************************************************************/ // ECMAScript 6 iterators shim !function(){ var getValues = createObjectToArray(false) // Safari define byggy iterators w/o `next` , buggy = 'keys' in ArrayProto && !('next' in [].keys()); function defineStdIterators(Base, NAME, DEFAULT, Constructor, next){ function createIter(kind){ return function(){ return new Constructor(this, kind); } } createIterator(Constructor, NAME, next); $define(PROTO + FORCED * buggy, NAME, { // 22.1.3.4 Array.prototype.entries() // 23.1.3.4 Map.prototype.entries() // 23.2.3.5 Set.prototype.entries() entries: createIter(KEY+VALUE), // 22.1.3.13 Array.prototype.keys() // 23.1.3.8 Map.prototype.keys() // 23.2.3.8 Set.prototype.keys() keys: createIter(KEY), // 22.1.3.29 Array.prototype.values() // 23.1.3.11 Map.prototype.values() // 23.2.3.10 Set.prototype.values() values: createIter(VALUE) }); // 22.1.3.30 Array.prototype[@@iterator]() // 23.1.3.12 Map.prototype[@@iterator]() // 23.2.3.11 Set.prototype[@@iterator]() Base && defineIterator(Base, NAME, createIter(DEFAULT)); } // 22.1.5.1 CreateArrayIterator Abstract Operation defineStdIterators(Array, ARRAY, VALUE, function(iterated, kind){ set(this, ITER, {o: ES5Object(iterated), i: 0, k: kind}); // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, function(){ var iter = this[ITER] , iterated = iter.o , index = iter.i++ , kind = iter.k , value; if(index >= iterated.length)return iterResult(1); if(kind == KEY) value = index; else if(kind == VALUE)value = iterated[index]; else value = [index, iterated[index]]; return iterResult(0, value); }); // 21.1.3.27 String.prototype[@@iterator]() - SHAM, TODO defineIterator(String, STRING, Iterators[ARRAY]); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) Iterators[ARGUMENTS] = Iterators[ARRAY]; // 23.1.5.1 CreateMapIterator Abstract Operation defineStdIterators(Map, MAP, KEY+VALUE, function(iterated, kind){ var keys; if(Map[SHIM])keys = getValues(iterated[COLLECTION_KEYS]); else Map[PROTOTYPE][FOR_EACH].call(iterated, function(val, key){ this.push(key); }, keys = []); set(this, ITER, {o: iterated, k: kind, a: keys, i: 0}); // 23.1.5.2.1 %MapIteratorPrototype%.next() }, function(){ var iter = this[ITER] , iterated = iter.o , keys = iter.a , index = iter.i++ , kind = iter.k , key, value; if(index >= keys.length)return iterResult(1); key = keys[index]; if(kind == KEY) value = key; else if(kind == VALUE)value = iterated.get(key); else value = [key, iterated.get(key)]; return iterResult(0, value); }); // 23.2.5.1 CreateSetIterator Abstract Operation defineStdIterators(Set, SET, VALUE, function(iterated, kind){ var keys; if(Set[SHIM])keys = getValues(iterated[COLLECTION_KEYS]); else Set[PROTOTYPE][FOR_EACH].call(iterated, function(val){ this.push(val); }, keys = []); set(this, ITER, {k: kind, a: keys.reverse(), l: keys.length}); // 23.2.5.2.1 %SetIteratorPrototype%.next() }, function(){ var iter = this[ITER] , keys = iter.a , key; if(!keys.length)return iterResult(1); key = keys.pop(); return iterResult(0, iter.k == KEY+VALUE ? [key, key] : key); }); }(); /****************************************************************************** * Module : dict * ******************************************************************************/ !function(){ function Dict(iterable){ var dict = create(null); if(iterable != undefined){ if(isIterable(iterable)){ for(var iter = getIterator(iterable), step, value; !(step = iter.next()).done;){ value = step.value; dict[value[0]] = value[1]; } } else assign(dict, iterable); } return dict; } Dict[PROTOTYPE] = null; function DictIterator(iterated, kind){ set(this, ITER, {o: ES5Object(iterated), a: getKeys(iterated), i: 0, k: kind}); } createIterator(DictIterator, 'Dict', function(){ var iter = this[ITER] , index = iter.i++ , keys = iter.a , kind = iter.k , key, value; if(index >= keys.length)return iterResult(1); key = keys[index]; if(kind == KEY) value = key; else if(kind == VALUE)value = iter.o[key]; else value = [key, iter.o[key]]; return iterResult(0, value); }); function createDictIter(kind){ return function(it){ return new DictIterator(it, kind); } } /* * 0 -> forEach * 1 -> map * 2 -> filter * 3 -> some * 4 -> every * 5 -> find * 6 -> findKey */ function createDictMethod(type){ var isMap = type == 1 , isFilter = type == 2 , isSome = type == 3 , isEvery = type == 4; return function(object, callbackfn, that /* = undefined */){ var f = ctx(callbackfn, that, 3) , O = ES5Object(object) , keys = getKeys(O) , length = keys.length , i = 0 , result = isMap || isFilter ? new (generic(this, Dict)) : undefined , key, val, res; while(length > i){ key = keys[i++]; val = O[key]; res = f(val, key, object); if(type){ if(isMap)result[key] = res; // map else if(res)switch(type){ case 3: return true; // some case 5: return val; // find case 6: return key; // findKey case 2: result[key] = val; // filter } else if(isEvery)return false; // every } } return isSome || isEvery ? isEvery : result; } } function createDictReduce(isTurn){ return function(object, mapfn, init){ assertFunction(mapfn); var O = ES5Object(object) , keys = getKeys(O) , length = keys.length , i = 0 , memo, key, result; if(isTurn)memo = init == undefined ? new (generic(this, Dict)) : Object(init); else if(arguments.length < 3){ assert(length, REDUCE_ERROR); memo = O[keys[i++]]; } else memo = Object(init); while(length > i){ result = mapfn(memo, O[key = keys[i++]], key, object); if(isTurn){ if(result === false)break; } else memo = result; } return memo; } } var findKey = createDictMethod(6); assign(Dict, { keys: createDictIter(KEY), values: createDictIter(VALUE), entries: createDictIter(KEY+VALUE), forEach: createDictMethod(0), map: createDictMethod(1), filter: createDictMethod(2), some: createDictMethod(3), every: createDictMethod(4), find: createDictMethod(5), findKey: findKey, reduce: createDictReduce(false), turn: createDictReduce(true), keyOf: keyOf, contains: function(object, el){ return (el == el ? keyOf(object, el) : findKey(object, sameNaN)) !== undefined; }, // Has / get / set own property has: has, get: function(object, key){ if(has(object, key))return object[key]; }, set: createDefiner(0), isDict: function(it){ return isObject(it) && getPrototypeOf(it) === Dict[PROTOTYPE]; } }); $define(STATIC, OBJECT, { // ~ ES7 : http://esdiscuss.org/topic/april-8-2014-meeting-notes#content-1 values: createObjectToArray(false), // ~ ES7 : http://esdiscuss.org/topic/april-8-2014-meeting-notes#content-1 entries: createObjectToArray(true) }); $define(GLOBAL + FORCED, {Dict: Dict}); }(); /****************************************************************************** * Module : timers * ******************************************************************************/ // ie9- setTimeout & setInterval additional parameters fix !function(MSIE){ function wrap(set){ return MSIE ? function(fn, time /*, ...args */){ return set(invoke(part, slice.call(arguments, 2), isFunction(fn) ? fn : Function(fn)), time); } : set; } $define(GLOBAL + BIND + FORCED * MSIE, { setTimeout: setTimeout = wrap(setTimeout), setInterval: wrap(setInterval) }); // ie9- dirty check }(!!navigator && /MSIE .\./.test(navigator.userAgent)); /****************************************************************************** * Module : binding * ******************************************************************************/ !function(_, toLocaleString){ $define(PROTO + FORCED, FUNCTION, { part: part, by: function(that){ var fn = this , _ = path._ , holder = false , length = arguments.length , isThat = that === _ , i = +!isThat , indent = i , it, args; if(isThat){ it = fn; fn = call; } else it = that; if(length < 2)return ctx(fn, it, -1); args = Array(length - indent); while(length > i)if((args[i - indent] = arguments[i++]) === _)holder = true; return partial(fn, args, length, holder, _, true, it); }, only: function(numberArguments, that /* = @ */){ var fn = assertFunction(this) , n = toLength(numberArguments) , isThat = arguments.length > 1; return function(/* ...args */){ var length = min(n, arguments.length) , args = Array(length) , i = 0; while(length > i)args[i] = arguments[i++]; return invoke(fn, args, isThat ? that : this); } } }); function tie(key){ var that = this , bound = {}; return hidden(that, _, function(key){ if(key === undefined || !(key in that))return toLocaleString.call(that); return has(bound, key) ? bound[key] : (bound[key] = ctx(that[key], that, -1)); })[_](key); } hidden(path._, TO_STRING, function(){ return _; }); hidden(ObjectProto, _, tie); DESC || hidden(ArrayProto, _, tie); // IE8- dirty hack - redefined toLocaleString is not enumerable }(DESC ? uid('tie') : TO_LOCALE, ObjectProto[TO_LOCALE]); /****************************************************************************** * Module : object * ******************************************************************************/ !function(){ function define(target, mixin){ var keys = ownKeys(ES5Object(mixin)) , length = keys.length , i = 0, key; while(length > i)defineProperty(target, key = keys[i++], getOwnDescriptor(mixin, key)); return target; }; $define(STATIC + FORCED, OBJECT, { isObject: isObject, classof: classof, define: define, make: function(proto, mixin){ return define(create(proto), mixin); } }); }(); /****************************************************************************** * Module : array * ******************************************************************************/ $define(PROTO, ARRAY, { // ~ ES7 : https://github.com/domenic/Array.prototype.contains contains: createArrayContains(true) }); $define(PROTO + FORCED, ARRAY, { turn: turn }); /****************************************************************************** * Module : array_statics * ******************************************************************************/ // JavaScript 1.6 / Strawman array statics shim !function(){ function setArrayStatics(keys, length){ $define(STATIC, ARRAY, turn.call( array(keys), function(memo, key){ if(key in ArrayProto)memo[key] = ctx(call, ArrayProto[key], length); }, {} )); } setArrayStatics('pop,reverse,shift,keys,values,entries', 1); setArrayStatics('indexOf,every,some,forEach,map,filter,find,findIndex,contains', 3); setArrayStatics('join,slice,concat,push,splice,unshift,sort,' + 'lastIndexOf,reduce,reduceRight,fill,turn'); }(); /****************************************************************************** * Module : number * ******************************************************************************/ !function(){ function NumberIterator(iterated){ set(this, ITER, {l: toLength(iterated), i: 0}); } createIterator(NumberIterator, NUMBER, function(){ var iter = this[ITER] , i = iter.i++; return i < iter.l ? iterResult(0, i) : iterResult(1); }); defineIterator(Number, NUMBER, function(){ return new NumberIterator(this); }); $define(PROTO + FORCED, NUMBER, { random: function(lim /* = 0 */){ var a = +this , b = lim == undefined ? 0 : +lim , m = min(a, b); return random() * (max(a, b) - m) + m; } }); $define(PROTO + FORCED, NUMBER, turn.call( array( // ES3: 'round,floor,ceil,abs,sin,asin,cos,acos,tan,atan,exp,sqrt,max,min,pow,atan2,' + // ES6: 'acosh,asinh,atanh,cbrt,clz32,cosh,expm1,hypot,imul,log1p,log10,log2,sign,sinh,tanh,trunc' ), function(memo, key){ var fn = Math[key]; if(fn)memo[key] = function(/* ...args */){ // ie9- dont support strict mode & convert `this` to object -> convert it to number var args = [+this] , i = 0; while(arguments.length > i)args.push(arguments[i++]); return invoke(fn, args); } }, {} )); }(); /****************************************************************************** * Module : string * ******************************************************************************/ !function(){ var escapeHTMLDict = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;' }, unescapeHTMLDict = {}, key; for(key in escapeHTMLDict)unescapeHTMLDict[escapeHTMLDict[key]] = key; $define(PROTO + FORCED, STRING, { escapeHTML: createReplacer(/[&<>"']/g, escapeHTMLDict), unescapeHTML: createReplacer(/&(?:amp|lt|gt|quot|apos);/g, unescapeHTMLDict) }); }(); /****************************************************************************** * Module : regexp * ******************************************************************************/ // ~ES7 : https://gist.github.com/kangax/9698100 $define(STATIC, REGEXP, { escape: createReplacer(/([\\\-[\]{}()*+?.,^$|])/g, '\\$1', true) }); /****************************************************************************** * Module : date * ******************************************************************************/ !function(formatRegExp, flexioRegExp, locales, current, SECONDS, MINUTES, HOURS, MONTH, YEAR){ function createFormat(prefix){ return function(template, locale /* = current */){ var that = this , dict = locales[has(locales, locale) ? locale : current]; function get(unit){ return that[prefix + unit](); } return String(template).replace(formatRegExp, function(part){ switch(part){ case 's' : return get(SECONDS); // Seconds : 0-59 case 'ss' : return lz(get(SECONDS)); // Seconds : 00-59 case 'm' : return get(MINUTES); // Minutes : 0-59 case 'mm' : return lz(get(MINUTES)); // Minutes : 00-59 case 'h' : return get(HOURS); // Hours : 0-23 case 'hh' : return lz(get(HOURS)); // Hours : 00-23 case 'D' : return get(DATE); // Date : 1-31 case 'DD' : return lz(get(DATE)); // Date : 01-31 case 'W' : return dict[0][get('Day')]; // Day : Понедельник case 'N' : return get(MONTH) + 1; // Month : 1-12 case 'NN' : return lz(get(MONTH) + 1); // Month : 01-12 case 'M' : return dict[2][get(MONTH)]; // Month : Январь case 'MM' : return dict[1][get(MONTH)]; // Month : Января case 'Y' : return get(YEAR); // Year : 2014 case 'YY' : return lz(get(YEAR) % 100); // Year : 14 } return part; }); } } function lz(num){ return num > 9 ? num : '0' + num; } function addLocale(lang, locale){ function split(index){ return turn.call(array(locale.months), function(memo, it){ memo.push(it.replace(flexioRegExp, '$' + index)); }); } locales[lang] = [array(locale.weekdays), split(1), split(2)]; return core; } $define(PROTO + FORCED, DATE, { format: createFormat('get'), formatUTC: createFormat('getUTC') }); addLocale(current, { weekdays: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday', months: 'January,February,March,April,May,June,July,August,September,October,November,December' }); addLocale('ru', { weekdays: 'Воскресенье,Понедельник,Вторник,Среда,Четверг,Пятница,Суббота', months: 'Январ:я|ь,Феврал:я|ь,Март:а|,Апрел:я|ь,Ма:я|й,Июн:я|ь,' + 'Июл:я|ь,Август:а|,Сентябр:я|ь,Октябр:я|ь,Ноябр:я|ь,Декабр:я|ь' }); core.locale = function(locale){ return has(locales, locale) ? current = locale : current; }; core.addLocale = addLocale; }(/\b\w\w?\b/g, /:(.*)\|(.*)$/, {}, 'en', 'Seconds', 'Minutes', 'Hours', 'Month', 'FullYear'); /****************************************************************************** * Module : console * ******************************************************************************/ !function(console){ var $console = turn.call( /** * Methods from: * https://github.com/DeveloperToolsWG/console-object/blob/master/api.md * https://developer.mozilla.org/en-US/docs/Web/API/console */ array('assert,clear,count,debug,dir,dirxml,error,exception,group,groupCollapsed,' + 'groupEnd,info,isIndependentlyComposed,log,markTimeline,profile,profileEnd,' + 'table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn'), function(memo, key){ var fn = console[key]; memo[key] = function(){ if(enabled && fn)return apply.call(fn, console, arguments); }; }, { enable: function(){ enabled = true; }, disable: function(){ enabled = false; } } ), enabled = true; try { framework && delete global.console; } catch(e){} $define(GLOBAL + FORCED, {console: assign($console.log, $console)}); }(global.console || {}); }(Function('return this'), false);
views/fulfillmentsForUserMadeRequests.io.js
princesadie/SnapDrop-react
/** * Sample React Native App * https://github.com/facebook/react-native */ var fulfillmentsForUserMadeRequestsStyles = require('../stylsheets/fulfillmentsForUserMadeRequestsStyle.ios') import React, { AppRegistry, Component, ListView, Text, View, } from 'react-native'; class FulfillRequest extends Component { constructor(props) { super(props); this.state = { fulfillments: [], dataSource: new ListView.DataSource({ rowHasChanged: (row1, row2) => row1 !== row2, }), loaded: false, }; } componentDidMount() { this.grabFulfillments("0"); } grabFulfillments(inputID) { var that = this; var ref = new Firebase("https://snapdrop.firebaseio.com/fulfillments"); ref.once("value", function(snapshot) { snapshot.forEach(function(childSnapshot) { var requestID = childSnapshot.val().requestID; var childData = childSnapshot.val(); if (requestID === inputID) { that.state.fulfillments.push(childData); console.log(that.state.fulfillments); that.setState({ dataSource: that.state.dataSource.cloneWithRows(that.state.fulfillments), loaded: true, }); }; }); }); } renderLoadingView() { return ( if(this.state.fulfillments.length === 0) { return ( <View style={fulfillmentsForUserMadeRequestsStyles.container}> <View style={fulfillmentsForUserMadeRequestsStyles.avatar1}> <TouchableOpacity onPress={() => this.goBack()}> <Image style = {fulfillmentsForUserMadeRequestsStyles.avatar} source = {this.state.userData.profileImage}/> </TouchableOpacity> </View> <Text style={fulfillmentsForUserMadeRequestsStyles.notice}>NO FULFILLMENTS YET</Text> </View> ) } else { return ( <View style={fulfillmentsForUserMadeRequestsStyles.container}> <Text style={fulfillmentsForUserMadeRequestsStyles.notice}> LOADING FULFILLMENTS... </Text> </View> ); } ); } renderFulfillment(fulfillment) { return ( <View style={fulfillmentsForUserMadeRequestsStyles.container}> <View style={fulfillmentsForUserMadeRequestsStyles.rightContainer}> <Text style={fulfillmentsForUserMadeRequestsStyles.description}>{fulfillment.description}</Text> </View> </View> ); } render() { if (!this.state.loaded) { return this.renderLoadingView(); } return ( <ListView dataSource={this.state.dataSource} renderRow={this.renderFulfillment} style={fulfillmentsForUserMadeRequestsStyles.listView} /> ); } } module.exports = FulfillRequest;
examples/shared-root/app.js
migolo/react-router
import React from 'react' import { createHistory, useBasename } from 'history' import { Router, Route, Link } from 'react-router' const history = useBasename(createHistory)({ basename: '/shared-root' }) class App extends React.Component { render() { return ( <div> <p> This illustrates how routes can share UI w/o sharing the URL. When routes have no path, they never match themselves but their children can, allowing "/signin" and "/forgot-password" to both be render in the <code>SignedOut</code> component. </p> <ol> <li><Link to="/home" activeClassName="active">Home</Link></li> <li><Link to="/signin" activeClassName="active">Sign in</Link></li> <li><Link to="/forgot-password" activeClassName="active">Forgot Password</Link></li> </ol> {this.props.children} </div> ) } } class SignedIn extends React.Component { render() { return ( <div> <h2>Signed In</h2> {this.props.children} </div> ) } } class Home extends React.Component { render() { return ( <h3>Welcome home!</h3> ) } } class SignedOut extends React.Component { render() { return ( <div> <h2>Signed Out</h2> {this.props.children} </div> ) } } class SignIn extends React.Component { render() { return ( <h3>Please sign in.</h3> ) } } class ForgotPassword extends React.Component { render() { return ( <h3>Forgot your password?</h3> ) } } React.render(( <Router history={history}> <Route path="/" component={App}> <Route component={SignedOut}> <Route path="signin" component={SignIn} /> <Route path="forgot-password" component={ForgotPassword} /> </Route> <Route component={SignedIn}> <Route path="home" component={Home} /> </Route> </Route> </Router> ), document.getElementById('example'))
app/client/src/components/SignupRegisterLogin/components/ActionSignupModal/ActionSignupModal.spec.js
uprisecampaigns/uprise-app
import React from 'react'; import { render, shallow, mount } from 'enzyme'; import ConnectedActionSignupModal, { ActionSignupModal } from './ActionSignupModal'; import configureStore from 'store/configureStore'; const store = configureStore(); describe('(Component) ActionSignupModal', () => { test('renders without exploding', () => { const action = { title: 'An Event', description: 'A test event', start_time: new Date(), end_time: new Date(), }; const userObject = { first_name: 'First', last_name: 'Last', email: '[email protected]' }; const timeWithZone = () => ''; const dispatch = () => {}; const signup = () => {}; const wrapper = shallow(<ActionSignupModal userObject={userObject} action={action} signup={signup} dispatch={dispatch} timeWithZone={timeWithZone} />); expect(wrapper).toHaveLength(1); }); test('connected component renders without exploding', () => { const action = { title: 'An Event', description: 'A test event', start_time: new Date(), end_time: new Date(), }; const userObject = { first_name: 'First', last_name: 'Last', email: '[email protected]' }; const wrapper = shallow(<ConnectedActionSignupModal store={store} />); expect(wrapper).toHaveLength(1); }); });
pages/venue/index.js
jsis/jsconf.is
import React from 'react' import BoxPage from '../../components/box-page' import content from './_venue.md' import icon from '!svg-inline!../../images/tonkvisl.svg' const title = 'Venue' export default () => <BoxPage icon={icon} title={title}> <div dangerouslySetInnerHTML={{ __html: content.body }} /> </BoxPage>
packages/ringcentral-widgets-docs/src/app/pages/Components/TabNavigationView/index.js
u9520107/ringcentral-js-widget
import React from 'react'; import { parse } from 'react-docgen'; import CodeExample from '../../../components/CodeExample'; import ComponentHeader from '../../../components/ComponentHeader'; import PropTypeDescription from '../../../components/PropTypeDescription'; import Demo from './Demo'; // eslint-disable-next-line import demoCode from '!raw-loader!./Demo'; // eslint-disable-next-line import componentCode from '!raw-loader!ringcentral-widgets/components/TabNavigationView'; const TabNavigationViewPage = () => { const info = parse(componentCode); return ( <div> <ComponentHeader name="TabNavigationView" description={info.description} /> <CodeExample code={demoCode} title="TabNavigationView Example" > <Demo /> </CodeExample> <PropTypeDescription componentInfo={info} /> </div> ); }; export default TabNavigationViewPage;
ajax/libs/angular-google-maps/2.4.1/angular-google-maps_dev_mapped.js
seogi1004/cdnjs
/*! angular-google-maps 2.4.1 2017-01-05 * AngularJS directives for Google Maps * git: https://github.com/angular-ui/angular-google-maps.git */ ; (function( window, angular, _, undefined ){ 'use strict'; /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. angular-google-maps https://github.com/angular-ui/angular-google-maps @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ (function() { angular.module('uiGmapgoogle-maps.providers', ['nemLogging']); angular.module('uiGmapgoogle-maps.wrapped', []); angular.module('uiGmapgoogle-maps.extensions', ['uiGmapgoogle-maps.wrapped', 'uiGmapgoogle-maps.providers']); angular.module('uiGmapgoogle-maps.directives.api.utils', ['uiGmapgoogle-maps.extensions']); angular.module('uiGmapgoogle-maps.directives.api.managers', []); angular.module('uiGmapgoogle-maps.directives.api.options', ['uiGmapgoogle-maps.directives.api.utils']); angular.module('uiGmapgoogle-maps.directives.api.options.builders', []); angular.module('uiGmapgoogle-maps.directives.api.models.child', ['uiGmapgoogle-maps.directives.api.utils', 'uiGmapgoogle-maps.directives.api.options', 'uiGmapgoogle-maps.directives.api.options.builders']); angular.module('uiGmapgoogle-maps.directives.api.models.parent', ['uiGmapgoogle-maps.directives.api.managers', 'uiGmapgoogle-maps.directives.api.models.child', 'uiGmapgoogle-maps.providers']); angular.module('uiGmapgoogle-maps.directives.api', ['uiGmapgoogle-maps.directives.api.models.parent']); angular.module('uiGmapgoogle-maps', ['uiGmapgoogle-maps.directives.api', 'uiGmapgoogle-maps.providers']); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.providers').factory('uiGmapMapScriptLoader', [ '$q', 'uiGmapuuid', function($q, uuid) { var getScriptUrl, includeScript, isGoogleMapsLoaded, scriptId, usedConfiguration; scriptId = void 0; usedConfiguration = void 0; getScriptUrl = function(options) { if (options.china) { return 'http://maps.google.cn/maps/api/js?'; } else { if (options.transport === 'auto') { return '//maps.googleapis.com/maps/api/js?'; } else { return options.transport + '://maps.googleapis.com/maps/api/js?'; } } }; includeScript = function(options) { var omitOptions, query, script, scriptElem; omitOptions = ['transport', 'isGoogleMapsForWork', 'china', 'preventLoad']; if (options.isGoogleMapsForWork) { omitOptions.push('key'); } query = _.map(_.omit(options, omitOptions), function(v, k) { return k + '=' + v; }); if (scriptId) { scriptElem = document.getElementById(scriptId); scriptElem.parentNode.removeChild(scriptElem); } query = query.join('&'); script = document.createElement('script'); script.id = scriptId = "ui_gmap_map_load_" + (uuid.generate()); script.type = 'text/javascript'; script.src = getScriptUrl(options) + query; return document.head.appendChild(script); }; isGoogleMapsLoaded = function() { return angular.isDefined(window.google) && angular.isDefined(window.google.maps); }; return { load: function(options) { var deferred, randomizedFunctionName; deferred = $q.defer(); if (isGoogleMapsLoaded()) { deferred.resolve(window.google.maps); return deferred.promise; } randomizedFunctionName = options.callback = 'onGoogleMapsReady' + Math.round(Math.random() * 1000); window[randomizedFunctionName] = function() { window[randomizedFunctionName] = null; deferred.resolve(window.google.maps); }; if (window.navigator.connection && window.Connection && window.navigator.connection.type === window.Connection.NONE && !options.preventLoad) { document.addEventListener('online', function() { if (!isGoogleMapsLoaded()) { return includeScript(options); } }); } else if (!options.preventLoad) { includeScript(options); } usedConfiguration = options; usedConfiguration.randomizedFunctionName = randomizedFunctionName; return deferred.promise; }, manualLoad: function() { var config; config = usedConfiguration; if (!isGoogleMapsLoaded()) { return includeScript(config); } else { if (window[config.randomizedFunctionName]) { return window[config.randomizedFunctionName](); } } } }; } ]).provider('uiGmapGoogleMapApi', function() { this.options = { transport: 'https', isGoogleMapsForWork: false, china: false, v: '3', libraries: '', language: 'en', preventLoad: false }; this.configure = function(options) { angular.extend(this.options, options); }; this.$get = [ 'uiGmapMapScriptLoader', (function(_this) { return function(loader) { return loader.load(_this.options); }; })(this) ]; return this; }).service('uiGmapGoogleMapApiManualLoader', [ 'uiGmapMapScriptLoader', function(loader) { return { load: function() { loader.manualLoad(); } }; } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.extensions').service('uiGmapExtendGWin', function() { return { init: _.once(function() { var uiGmapInfoBox; if (!(google || (typeof google !== "undefined" && google !== null ? google.maps : void 0) || (google.maps.InfoWindow != null))) { return; } google.maps.InfoWindow.prototype._open = google.maps.InfoWindow.prototype.open; google.maps.InfoWindow.prototype._close = google.maps.InfoWindow.prototype.close; google.maps.InfoWindow.prototype._isOpen = false; google.maps.InfoWindow.prototype.open = function(map, anchor, recurse) { if (recurse != null) { return; } this._isOpen = true; this._open(map, anchor, true); }; google.maps.InfoWindow.prototype.close = function(recurse) { if (recurse != null) { return; } this._isOpen = false; this._close(true); }; google.maps.InfoWindow.prototype.isOpen = function(val) { if (val == null) { val = void 0; } if (val == null) { return this._isOpen; } else { return this._isOpen = val; } }; /* Do the same for InfoBox TODO: Clean this up so the logic is defined once, wait until develop becomes master as this will be easier */ if (window.InfoBox) { window.InfoBox.prototype._open = window.InfoBox.prototype.open; window.InfoBox.prototype._close = window.InfoBox.prototype.close; window.InfoBox.prototype._isOpen = false; window.InfoBox.prototype.open = function(map, anchor) { this._isOpen = true; this._open(map, anchor); }; window.InfoBox.prototype.close = function() { this._isOpen = false; this._close(); }; window.InfoBox.prototype.isOpen = function(val) { if (val == null) { val = void 0; } if (val == null) { return this._isOpen; } else { return this._isOpen = val; } }; uiGmapInfoBox = (function(superClass) { extend(uiGmapInfoBox, superClass); function uiGmapInfoBox(opts) { this.getOrigCloseBoxImg_ = bind(this.getOrigCloseBoxImg_, this); this.getCloseBoxDiv_ = bind(this.getCloseBoxDiv_, this); var box; box = new window.InfoBox(opts); _.extend(this, box); if (opts.closeBoxDiv != null) { this.closeBoxDiv_ = opts.closeBoxDiv; } } uiGmapInfoBox.prototype.getCloseBoxDiv_ = function() { return this.closeBoxDiv_; }; uiGmapInfoBox.prototype.getCloseBoxImg_ = function() { var div, img; div = this.getCloseBoxDiv_(); img = this.getOrigCloseBoxImg_(); return div || img; }; uiGmapInfoBox.prototype.getOrigCloseBoxImg_ = function() { var img; img = ""; if (this.closeBoxURL_ !== "") { img = "<img"; img += " src='" + this.closeBoxURL_ + "'"; img += " align=right"; img += " style='"; img += " position: relative;"; img += " cursor: pointer;"; img += " margin: " + this.closeBoxMargin_ + ";"; img += "'>"; } return img; }; return uiGmapInfoBox; })(window.InfoBox); window.uiGmapInfoBox = uiGmapInfoBox; } if (window.MarkerLabel_) { return window.MarkerLabel_.prototype.setContent = function() { var content; content = this.marker_.get('labelContent'); if (!content || _.isEqual(this.oldContent, content)) { return; } if (typeof (content != null ? content.nodeType : void 0) === 'undefined') { this.labelDiv_.innerHTML = content; this.eventDiv_.innerHTML = this.labelDiv_.innerHTML; this.oldContent = content; } else { this.labelDiv_.innerHTML = ''; this.labelDiv_.appendChild(content); content = content.cloneNode(true); this.labelDiv_.innerHTML = ''; this.eventDiv_.appendChild(content); this.oldContent = content; } }; } }) }; }); }).call(this); ; /*global _:true, angular:true */ (function() { angular.module('uiGmapgoogle-maps.extensions').service('uiGmapLodash', function() { var baseGet, baseToString, fixLodash, get, reEscapeChar, rePropName, toObject, toPath; rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g; reEscapeChar = /\\(\\)?/g; /* For Lodash 4 compatibility (some aliases are removed) */ fixLodash = function(arg) { var isProto, missingName, swapName; missingName = arg.missingName, swapName = arg.swapName, isProto = arg.isProto; if (_[missingName] == null) { _[missingName] = _[swapName]; if (isProto) { return _.prototype[missingName] = _[swapName]; } } }; [ { missingName: 'contains', swapName: 'includes', isProto: true }, { missingName: 'includes', swapName: 'contains', isProto: true }, { missingName: 'object', swapName: 'zipObject' }, { missingName: 'zipObject', swapName: 'object' }, { missingName: 'all', swapName: 'every' }, { missingName: 'every', swapName: 'all' }, { missingName: 'any', swapName: 'some' }, { missingName: 'some', swapName: 'any' }, { missingName: 'first', swapName: 'head' }, { missingName: 'head', swapName: 'first' } ].forEach(function(toMonkeyPatch) { return fixLodash(toMonkeyPatch); }); if (_.get == null) { /** * Converts `value` to an object if it's not one. * * @private * @param {*} value The value to process. * @returns {Object} Returns the object. */ toObject = function(value) { if (_.isObject(value)) { return value; } else { return Object(value); } }; /** * Converts `value` to a string if it's not one. An empty string is returned * for `null` or `undefined` values. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ baseToString = function(value) { if (value === null) { return ''; } else { return value + ''; } }; /** * Converts `value` to property path array if it's not one. * * @private * @param {*} value The value to process. * @returns {Array} Returns the property path array. */ toPath = function(value) { var result; if (_.isArray(value)) { return value; } result = []; baseToString(value).replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, '$1') : number || match); }); return result; }; /** * The base implementation of `get` without support for string paths * and default values. * * @private * @param {Object} object The object to query. * @param {Array} path The path of the property to get. * @param {string} [pathKey] The key representation of path. * @returns {*} Returns the resolved value. */ baseGet = function(object, path, pathKey) { var index, length; if (object === null) { return; } if (pathKey !== void 0 && pathKey in toObject(object)) { path = [pathKey]; } index = 0; length = path.length; while (!_.isUndefined(object) && index < length) { object = object[path[index++]]; } if (index && index === length) { return object; } else { return void 0; } }; /** * Gets the property value at `path` of `object`. If the resolved value is * `undefined` the `defaultValue` is used in its place. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned if the resolved value is `undefined`. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ get = function(object, path, defaultValue) { var result; result = object === null ? void 0 : baseGet(object, toPath(path), path + ''); if (result === void 0) { return defaultValue; } else { return result; } }; _.get = get; } /* Author Nick McCready Intersection of Objects if the arrays have something in common each intersecting object will be returned in an new array. */ this.intersectionObjects = function(array1, array2, comparison) { var res; if (comparison == null) { comparison = void 0; } res = _.map(array1, function(obj1) { return _.find(array2, function(obj2) { if (comparison != null) { return comparison(obj1, obj2); } else { return _.isEqual(obj1, obj2); } }); }); return _.filter(res, function(o) { return o != null; }); }; this.containsObject = _.includeObject = function(obj, target, comparison) { if (comparison == null) { comparison = void 0; } if (obj === null) { return false; } return _.some(obj, function(value) { if (comparison != null) { return comparison(value, target); } else { return _.isEqual(value, target); } }); }; this.differenceObjects = function(array1, array2, comparison) { if (comparison == null) { comparison = void 0; } return _.filter(array1, (function(_this) { return function(value) { return !_this.containsObject(array2, value, comparison); }; })(this)); }; this.withoutObjects = this.differenceObjects; this.indexOfObject = function(array, item, comparison, isSorted) { var i, length; if (array == null) { return -1; } 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); } } while (i < length) { if (comparison != null) { if (comparison(array[i], item)) { return i; } } else { if (_.isEqual(array[i], item)) { return i; } } i++; } return -1; }; this.isNullOrUndefined = function(thing) { return _.isNull(thing || _.isUndefined(thing)); }; return this; }); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.extensions').factory('uiGmapString', function() { return function(str) { this.contains = function(value, fromIndex) { return str.indexOf(value, fromIndex) !== -1; }; return this; }; }); }).call(this); ; /*global _:true,angular:true, */ (function() { angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmap_sync', [ function() { return { fakePromise: function() { var _cb; _cb = void 0; return { then: function(cb) { return _cb = cb; }, resolve: function() { return _cb.apply(void 0, arguments); } }; } }; } ]).service('uiGmap_async', [ '$timeout', 'uiGmapPromise', 'uiGmapLogger', '$q', 'uiGmapDataStructures', 'uiGmapGmapUtil', function($timeout, uiGmapPromise, $log, $q, uiGmapDataStructures, uiGmapGmapUtil) { var ExposedPromise, PromiseQueueManager, SniffedPromise, _getIterateeValue, _ignoreFields, defaultChunkSize, doChunk, doSkippPromise, each, errorObject, getArrayAndKeys, isInProgress, kickPromise, logTryCatch, managePromiseQueue, map, maybeCancelPromises, promiseStatus, promiseTypes, tryCatch; promiseTypes = uiGmapPromise.promiseTypes; isInProgress = uiGmapPromise.isInProgress; promiseStatus = uiGmapPromise.promiseStatus; ExposedPromise = uiGmapPromise.ExposedPromise; SniffedPromise = uiGmapPromise.SniffedPromise; kickPromise = function(sniffedPromise, cancelCb) { var promise; promise = sniffedPromise.promise(); promise.promiseType = sniffedPromise.promiseType; if (promise.$$state) { $log.debug("promiseType: " + promise.promiseType + ", state: " + (promiseStatus(promise.$$state.status))); } promise.cancelCb = cancelCb; return promise; }; doSkippPromise = function(sniffedPromise, lastPromise) { if (sniffedPromise.promiseType === promiseTypes.create && lastPromise.promiseType !== promiseTypes["delete"] && lastPromise.promiseType !== promiseTypes.init) { $log.debug("lastPromise.promiseType " + lastPromise.promiseType + ", newPromiseType: " + sniffedPromise.promiseType + ", SKIPPED MUST COME AFTER DELETE ONLY"); return true; } return false; }; maybeCancelPromises = function(queue, sniffedPromise, lastPromise) { var first; if (sniffedPromise.promiseType === promiseTypes["delete"] && lastPromise.promiseType !== promiseTypes["delete"]) { if ((lastPromise.cancelCb != null) && _.isFunction(lastPromise.cancelCb) && isInProgress(lastPromise)) { $log.debug("promiseType: " + sniffedPromise.promiseType + ", CANCELING LAST PROMISE type: " + lastPromise.promiseType); lastPromise.cancelCb('cancel safe'); first = queue.peek(); if ((first != null) && isInProgress(first)) { if (first.hasOwnProperty("cancelCb") && _.isFunction(first.cancelCb)) { $log.debug("promiseType: " + first.promiseType + ", CANCELING FIRST PROMISE type: " + first.promiseType); return first.cancelCb('cancel safe'); } else { return $log.warn('first promise was not cancelable'); } } } } }; /* From a High Level: This is a SniffedPromiseQueueManager (looking to rename) where the queue is existingPiecesObj.existingPieces. This is a function and should not be considered a class. So it is run to manage the state (cancel, skip, link) as needed. Purpose: The whole point is to check if there is existing async work going on. If so we wait on it. arguments: - existingPiecesObj = Queue<Promises> - sniffedPromise = object wrapper holding a function to a pending (function) promise (promise: fnPromise) with its intended type. - cancelCb = callback which accepts a string, this string is intended to be returned at the end of _async.each iterator Where the cancelCb passed msg is 'cancel safe' _async.each will drop out and fall through. Thus canceling the promise gracefully without messing up state. Synopsis: - Promises have been broken down to 4 states create, update,delete (3 main) and init. (Helps boil down problems in ordering) where (init) is special to indicate that it is one of the first or to allow a create promise to work beyond being after a delete - Every Promise that comes in is enqueued and linked to the last promise in the queue. - A promise can be skipped or canceled to save cycles. Saved Cycles: - Skipped - This will only happen if async work comes in out of order. Where a pending create promise (un-executed) comes in after a delete promise. - Canceled - Where an incoming promise (un-executed promise) is of type delete and the any lastPromise is not a delete type. NOTE: - You should not muck with existingPieces as its state is dependent on this functional loop. - PromiseQueueManager should not be thought of as a class that has a life expectancy (it has none). It's sole purpose is to link, skip, and kill promises. It also manages the promise queue existingPieces. */ PromiseQueueManager = function(existingPiecesObj, sniffedPromise, cancelCb) { var lastPromise, newPromise; if (!existingPiecesObj.existingPieces) { existingPiecesObj.existingPieces = new uiGmapDataStructures.Queue(); return existingPiecesObj.existingPieces.enqueue(kickPromise(sniffedPromise, cancelCb)); } else { lastPromise = _.last(existingPiecesObj.existingPieces._content); if (doSkippPromise(sniffedPromise, lastPromise)) { return; } maybeCancelPromises(existingPiecesObj.existingPieces, sniffedPromise, lastPromise); newPromise = ExposedPromise(lastPromise["finally"](function() { return kickPromise(sniffedPromise, cancelCb); })); newPromise.cancelCb = cancelCb; newPromise.promiseType = sniffedPromise.promiseType; existingPiecesObj.existingPieces.enqueue(newPromise); return lastPromise["finally"](function() { return existingPiecesObj.existingPieces.dequeue(); }); } }; managePromiseQueue = function(objectToLock, promiseType, msg, cancelCb, fnPromise) { var cancelLogger; if (msg == null) { msg = ''; } cancelLogger = function(msg) { $log.debug(msg + ": " + msg); if ((cancelCb != null) && _.isFunction(cancelCb)) { return cancelCb(msg); } }; return PromiseQueueManager(objectToLock, SniffedPromise(fnPromise, promiseType), cancelLogger); }; defaultChunkSize = 80; errorObject = { value: null }; tryCatch = function(fn, ctx, args) { var e, error1; try { return fn.apply(ctx, args); } catch (error1) { e = error1; errorObject.value = e; return errorObject; } }; logTryCatch = function(fn, ctx, deferred, args) { var msg, result; result = tryCatch(fn, ctx, args); if (result === errorObject) { msg = "error within chunking iterator: " + errorObject.value; $log.error(msg); deferred.reject(msg); } if (result === 'cancel safe') { return false; } return true; }; _getIterateeValue = function(collection, array, index) { var _isArray, valOrKey; _isArray = collection === array; valOrKey = array[index]; if (_isArray) { return valOrKey; } return collection[valOrKey]; }; _ignoreFields = ['length', 'forEach', 'map']; getArrayAndKeys = function(collection, keys, bailOutCb, cb) { var array, propName, val; if (angular.isArray(collection)) { array = collection; } else { if (keys) { array = keys; } else { array = []; for (propName in collection) { val = collection[propName]; if (collection.hasOwnProperty(propName) && !_.includes(_ignoreFields, propName)) { array.push(propName); } } } } if (cb == null) { cb = bailOutCb; } if (angular.isArray(array) && !(array != null ? array.length : void 0)) { if (cb !== bailOutCb) { return bailOutCb(); } } return cb(array, keys); }; /* Author: Nicholas McCready & jfriend00 _async handles things asynchronous-like :), to allow the UI to be free'd to do other things Code taken from http://stackoverflow.com/questions/10344498/best-way-to-iterate-over-an-array-without-blocking-the-ui The design of any functionality of _async is to be like lodash/underscore and replicate it but call things asynchronously underneath. Each should be sufficient for most things to be derived from. Optional Asynchronous Chunking via promises. */ doChunk = function(collection, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index, _keys) { return getArrayAndKeys(collection, _keys, function(array, keys) { var cnt, i, keepGoing, val; if (chunkSizeOrDontChunk && chunkSizeOrDontChunk < array.length) { cnt = chunkSizeOrDontChunk; } else { cnt = array.length; } i = index; keepGoing = true; while (keepGoing && cnt-- && i < (array ? array.length : i + 1)) { val = _getIterateeValue(collection, array, i); keepGoing = angular.isFunction(val) ? true : logTryCatch(chunkCb, void 0, overallD, [val, i]); ++i; } if (array) { if (keepGoing && i < array.length) { index = i; if (chunkSizeOrDontChunk) { if ((pauseCb != null) && _.isFunction(pauseCb)) { logTryCatch(pauseCb, void 0, overallD, []); } return $timeout(function() { return doChunk(collection, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index, keys); }, pauseMilli, false); } } else { return overallD.resolve(); } } }); }; each = function(collection, chunk, chunkSizeOrDontChunk, pauseCb, index, pauseMilli, _keys) { var error, overallD, ret; if (chunkSizeOrDontChunk == null) { chunkSizeOrDontChunk = defaultChunkSize; } if (index == null) { index = 0; } if (pauseMilli == null) { pauseMilli = 1; } ret = void 0; overallD = uiGmapPromise.defer(); ret = overallD.promise; if (!pauseMilli) { error = 'pause (delay) must be set from _async!'; $log.error(error); overallD.reject(error); return ret; } return getArrayAndKeys(collection, _keys, function() { overallD.resolve(); return ret; }, function(array, keys) { doChunk(collection, chunkSizeOrDontChunk, pauseMilli, chunk, pauseCb, overallD, index, keys); return ret; }); }; map = function(collection, iterator, chunkSizeOrDontChunk, pauseCb, index, pauseMilli, _keys) { var results; results = []; return getArrayAndKeys(collection, _keys, function() { return uiGmapPromise.resolve(results); }, function(array, keys) { return each(collection, function(o) { return results.push(iterator(o)); }, chunkSizeOrDontChunk, pauseCb, index, pauseMilli, keys).then(function() { return results; }); }); }; return { each: each, map: map, managePromiseQueue: managePromiseQueue, promiseLock: managePromiseQueue, defaultChunkSize: defaultChunkSize, getArrayAndKeys: getArrayAndKeys, chunkSizeFrom: function(fromSize, ret) { if (ret == null) { ret = void 0; } if (_.isNumber(fromSize)) { ret = fromSize; } if (uiGmapGmapUtil.isFalse(fromSize) || fromSize === false) { ret = false; } return ret; } }; } ]); }).call(this); ;(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; }; angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapBaseObject', function() { var BaseObject, baseObjectKeywords; baseObjectKeywords = ['extended', 'included']; BaseObject = (function() { function BaseObject() {} BaseObject.extend = function(obj) { var key, ref, value; for (key in obj) { value = obj[key]; if (indexOf.call(baseObjectKeywords, key) < 0) { this[key] = value; } } if ((ref = obj.extended) != null) { ref.apply(this); } return this; }; BaseObject.include = function(obj) { var key, ref, value; for (key in obj) { value = obj[key]; if (indexOf.call(baseObjectKeywords, key) < 0) { this.prototype[key] = value; } } if ((ref = obj.included) != null) { ref.apply(this); } return this; }; return BaseObject; })(); return BaseObject; }); }).call(this); ; /* Useful function callbacks that should be defined at later time. Mainly to be used for specs to verify creation / linking. This is to lead a common design in notifying child stuff. */ (function() { angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapChildEvents', function() { return { onChildCreation: function(child) {} }; }); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapCtrlHandle', [ '$q', function($q) { var CtrlHandle; return CtrlHandle = { handle: function($scope, $element) { $scope.$on('$destroy', function() { return CtrlHandle.handle($scope); }); $scope.deferred = $q.defer(); return { getScope: function() { return $scope; } }; }, mapPromise: function(scope, ctrl) { var mapScope; mapScope = ctrl.getScope(); mapScope.deferred.promise.then(function(map) { return scope.map = map; }); return mapScope.deferred.promise; } }; } ]); }).call(this); ;(function() { angular.module("uiGmapgoogle-maps.directives.api.utils").service("uiGmapEventsHelper", [ "uiGmapLogger", function($log) { var _getEventsObj, _hasEvents; _hasEvents = function(obj) { return angular.isDefined(obj.events) && (obj.events != null) && angular.isObject(obj.events); }; _getEventsObj = function(scope, model) { if (_hasEvents(scope)) { return scope; } if (_hasEvents(model)) { return model; } }; return { setEvents: function(gObject, scope, model, ignores) { var eventObj; eventObj = _getEventsObj(scope, model); if (eventObj != null) { return _.compact(_.map(eventObj.events, function(eventHandler, eventName) { var doIgnore; if (ignores) { doIgnore = _(ignores).includes(eventName); } if (eventObj.events.hasOwnProperty(eventName) && angular.isFunction(eventObj.events[eventName]) && !doIgnore) { return google.maps.event.addListener(gObject, eventName, function() { if (!scope.$evalAsync) { scope.$evalAsync = function() {}; } return scope.$evalAsync(eventHandler.apply(scope, [gObject, eventName, model, arguments])); }); } })); } }, removeEvents: function(listeners) { var key, l; if (!listeners) { return; } for (key in listeners) { l = listeners[key]; if (l && listeners.hasOwnProperty(key)) { google.maps.event.removeListener(l); } } } }; } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapFitHelper', [ 'uiGmapLogger', '$timeout', function($log, $timeout) { return { fit: function(markersOrPoints, gMap) { var bounds, everSet, key, markerOrPoint, point; if (gMap && (markersOrPoints != null ? markersOrPoints.length : void 0)) { bounds = new google.maps.LatLngBounds(); everSet = false; for (key in markersOrPoints) { markerOrPoint = markersOrPoints[key]; if (markerOrPoint) { if (!everSet) { everSet = true; } point = _.isFunction(markerOrPoint.getPosition) ? markerOrPoint.getPosition() : markerOrPoint; } bounds.extend(point); } if (everSet) { return $timeout(function() { return gMap.fitBounds(bounds); }); } } } }; } ]); }).call(this); ; /*global _:true, angular:true, google:true */ (function() { angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapGmapUtil', [ 'uiGmapLogger', '$compile', function(Logger, $compile) { var _isFalse, _isTruthy, getCoords, getLatitude, getLongitude, validateCoords; _isTruthy = function(value, bool, optionsArray) { return value === bool || optionsArray.indexOf(value) !== -1; }; _isFalse = function(value) { return _isTruthy(value, false, ['false', 'FALSE', 0, 'n', 'N', 'no', 'NO']); }; getLatitude = function(value) { if (Array.isArray(value) && value.length === 2) { return value[1]; } else if (angular.isDefined(value.type) && value.type === 'Point') { return value.coordinates[1]; } else { return value.latitude; } }; getLongitude = function(value) { if (Array.isArray(value) && value.length === 2) { return value[0]; } else if (angular.isDefined(value.type) && value.type === 'Point') { return value.coordinates[0]; } else { return value.longitude; } }; getCoords = function(value) { if (!value) { return; } if (value instanceof google.maps.LatLng) { return value; } else if (Array.isArray(value) && value.length === 2) { return new google.maps.LatLng(value[1], value[0]); } else if (angular.isDefined(value.type) && value.type === 'Point') { return new google.maps.LatLng(value.coordinates[1], value.coordinates[0]); } else { return new google.maps.LatLng(value.latitude, value.longitude); } }; validateCoords = function(coords) { if (angular.isUndefined(coords)) { return false; } if (_.isArray(coords)) { if (coords.length === 2) { return true; } } else if ((coords != null) && (coords != null ? coords.type : void 0)) { if (coords.type === 'Point' && _.isArray(coords.coordinates) && coords.coordinates.length === 2) { return true; } } if (coords && angular.isDefined((coords != null ? coords.latitude : void 0) && angular.isDefined(coords != null ? coords.longitude : void 0))) { return true; } return false; }; return { setCoordsFromEvent: function(prevValue, newLatLon) { if (!prevValue) { return; } if (Array.isArray(prevValue) && prevValue.length === 2) { prevValue[1] = newLatLon.lat(); prevValue[0] = newLatLon.lng(); } else if (angular.isDefined(prevValue.type) && prevValue.type === 'Point') { prevValue.coordinates[1] = newLatLon.lat(); prevValue.coordinates[0] = newLatLon.lng(); } else { prevValue.latitude = newLatLon.lat(); prevValue.longitude = newLatLon.lng(); } return prevValue; }, getLabelPositionPoint: function(anchor) { var xPos, yPos; if (anchor === void 0) { return void 0; } anchor = /^([-\d\.]+)\s([-\d\.]+)$/.exec(anchor); xPos = parseFloat(anchor[1]); yPos = parseFloat(anchor[2]); if ((xPos != null) && (yPos != null)) { return new google.maps.Point(xPos, yPos); } }, createWindowOptions: function(gMarker, scope, content, defaults) { var options; if ((content != null) && (defaults != null) && ($compile != null)) { options = angular.extend({}, defaults, { content: this.buildContent(scope, defaults, content), position: defaults.position != null ? defaults.position : angular.isObject(gMarker) ? gMarker.getPosition() : getCoords(scope.coords) }); if ((gMarker != null) && ((options != null ? options.pixelOffset : void 0) == null)) { if (options.boxClass == null) { } else { options.pixelOffset = { height: 0, width: -2 }; } } return options; } else { if (!defaults) { Logger.error('infoWindow defaults not defined'); if (!content) { return Logger.error('infoWindow content not defined'); } } else { return defaults; } } }, buildContent: function(scope, defaults, content) { var parsed, ret; if (defaults.content != null) { ret = defaults.content; } else { if ($compile != null) { content = content.replace(/^\s+|\s+$/g, ''); parsed = content === '' ? '' : $compile(content)(scope); if (parsed.length > 0) { ret = parsed[0]; } } else { ret = content; } } return ret; }, defaultDelay: 50, isTrue: function(value) { return _isTruthy(value, true, ['true', 'TRUE', 1, 'y', 'Y', 'yes', 'YES']); }, isFalse: _isFalse, isFalsy: function(value) { return _isTruthy(value, false, [void 0, null]) || _isFalse(value); }, getCoords: getCoords, validateCoords: validateCoords, equalCoords: function(coord1, coord2) { return getLatitude(coord1) === getLatitude(coord2) && getLongitude(coord1) === getLongitude(coord2); }, validatePath: function(path) { var array, i, polygon, trackMaxVertices; i = 0; if (angular.isUndefined(path.type)) { if (!Array.isArray(path) || path.length < 2) { return false; } while (i < path.length) { if (!((angular.isDefined(path[i].latitude) && angular.isDefined(path[i].longitude)) || (typeof path[i].lat === 'function' && typeof path[i].lng === 'function'))) { return false; } i++; } return true; } else { if (angular.isUndefined(path.coordinates)) { return false; } if (path.type === 'Polygon') { if (path.coordinates[0].length < 4) { return false; } array = path.coordinates[0]; } else if (path.type === 'MultiPolygon') { trackMaxVertices = { max: 0, index: 0 }; _.forEach(path.coordinates, function(polygon, index) { if (polygon[0].length > this.max) { this.max = polygon[0].length; return this.index = index; } }, trackMaxVertices); polygon = path.coordinates[trackMaxVertices.index]; array = polygon[0]; if (array.length < 4) { return false; } } else if (path.type === 'LineString') { if (path.coordinates.length < 2) { return false; } array = path.coordinates; } else { return false; } while (i < array.length) { if (array[i].length !== 2) { return false; } i++; } return true; } }, convertPathPoints: function(path) { var array, i, latlng, result, trackMaxVertices; i = 0; result = new google.maps.MVCArray(); if (angular.isUndefined(path.type)) { while (i < path.length) { latlng; if (angular.isDefined(path[i].latitude) && angular.isDefined(path[i].longitude)) { latlng = new google.maps.LatLng(path[i].latitude, path[i].longitude); } else if (typeof path[i].lat === 'function' && typeof path[i].lng === 'function') { latlng = path[i]; } result.push(latlng); i++; } } else { array; if (path.type === 'Polygon') { array = path.coordinates[0]; } else if (path.type === 'MultiPolygon') { trackMaxVertices = { max: 0, index: 0 }; _.forEach(path.coordinates, function(polygon, index) { if (polygon[0].length > this.max) { this.max = polygon[0].length; return this.index = index; } }, trackMaxVertices); array = path.coordinates[trackMaxVertices.index][0]; } else if (path.type === 'LineString') { array = path.coordinates; } while (i < array.length) { result.push(new google.maps.LatLng(array[i][1], array[i][0])); i++; } } return result; }, getPath: function(object, key) { var obj; if ((key == null) || !_.isString(key)) { return key; } obj = object; _.each(key.split('.'), function(value) { if (obj) { return obj = obj[value]; } }); return obj; }, validateBoundPoints: function(bounds) { if (angular.isUndefined(bounds.sw.latitude) || angular.isUndefined(bounds.sw.longitude) || angular.isUndefined(bounds.ne.latitude) || angular.isUndefined(bounds.ne.longitude)) { return false; } return true; }, convertBoundPoints: function(bounds) { var result; result = new google.maps.LatLngBounds(new google.maps.LatLng(bounds.sw.latitude, bounds.sw.longitude), new google.maps.LatLng(bounds.ne.latitude, bounds.ne.longitude)); return result; }, fitMapBounds: function(map, bounds) { return map.fitBounds(bounds); } }; } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapIsReady', [ '$q', '$timeout', function($q, $timeout) { var _checkIfReady, _ctr, _promises, _proms; _ctr = 0; _proms = []; _promises = function() { return $q.all(_proms); }; _checkIfReady = function(deferred, expectedInstances, retriesLeft) { return $timeout(function() { if (retriesLeft <= 0) { deferred.reject('Your maps are not found we have checked the maximum amount of times. :)'); return; } if (_ctr !== expectedInstances) { _checkIfReady(deferred, expectedInstances, retriesLeft - 1); } else { deferred.resolve(_promises()); } }, 100); }; return { spawn: function() { var d; d = $q.defer(); _proms.push(d.promise); _ctr += 1; return { instance: _ctr, deferred: d }; }, promises: _promises, instances: function() { return _ctr; }, promise: function(expectedInstances, numRetries) { var d; if (expectedInstances == null) { expectedInstances = 1; } if (numRetries == null) { numRetries = 50; } d = $q.defer(); _checkIfReady(d, expectedInstances, numRetries); return d.promise; }, reset: function() { _ctr = 0; _proms.length = 0; }, decrement: function() { if (_ctr > 0) { _ctr -= 1; } if (_proms.length) { _proms.length -= 1; } } }; } ]); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapLinked", [ "uiGmapBaseObject", function(BaseObject) { var Linked; Linked = (function(superClass) { extend(Linked, superClass); function Linked(scope, element, attrs, ctrls) { this.scope = scope; this.element = element; this.attrs = attrs; this.ctrls = ctrls; } return Linked; })(BaseObject); return Linked; } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapLogger', [ 'nemSimpleLogger', function(nemSimpleLogger) { return nemSimpleLogger.spawn(); } ]); }).call(this); ; /*global _:true, angular:true */ (function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapModelKey', [ 'uiGmapBaseObject', 'uiGmapGmapUtil', function(BaseObject, GmapUtil) { return (function(superClass) { extend(_Class, superClass); function _Class(scope1, _interface) { this.scope = scope1; this["interface"] = _interface != null ? _interface : { scopeKeys: [] }; this.modelsLength = bind(this.modelsLength, this); this.updateChild = bind(this.updateChild, this); this.destroy = bind(this.destroy, this); this.setChildScope = bind(this.setChildScope, this); this.getChanges = bind(this.getChanges, this); this.getProp = bind(this.getProp, this); this.setIdKey = bind(this.setIdKey, this); this.modelKeyComparison = bind(this.modelKeyComparison, this); _Class.__super__.constructor.call(this); this.defaultIdKey = 'id'; this.idKey = void 0; } _Class.prototype.evalModelHandle = function(model, modelKey) { if ((model == null) || (modelKey == null)) { return; } if (modelKey === 'self') { return model; } else { if (_.isFunction(modelKey)) { modelKey = modelKey(); } return GmapUtil.getPath(model, modelKey); } }; _Class.prototype.modelKeyComparison = function(model1, model2) { var coord1, coord2, hasCoords, isEqual, scope, without; hasCoords = this["interface"].scopeKeys.indexOf('coords') >= 0; if (hasCoords && (this.scope.coords != null) || !hasCoords) { scope = this.scope; } if (scope == null) { throw 'No scope set!'; } if (hasCoords) { coord1 = this.scopeOrModelVal('coords', scope, model1); coord2 = this.scopeOrModelVal('coords', scope, model2); isEqual = GmapUtil.equalCoords(coord1, coord2); if (!isEqual) { return isEqual; } } without = _.without(this["interface"].scopeKeys, 'coords'); isEqual = _.every(without, (function(_this) { return function(k) { var m1, m2; m1 = _this.scopeOrModelVal(scope[k], scope, model1); m2 = _this.scopeOrModelVal(scope[k], scope, model2); if (scope.deepComparison) { return _.isEqual(m1, m2); } else { return m1 === m2; } }; })(this)); return isEqual; }; _Class.prototype.setIdKey = function(scope) { return this.idKey = scope.idKey != null ? scope.idKey : this.defaultIdKey; }; _Class.prototype.setVal = function(model, key, newValue) { this.modelOrKey(model, key = newValue); return model; }; _Class.prototype.modelOrKey = function(model, key) { if (key == null) { return; } if (key !== 'self') { return GmapUtil.getPath(model, key); } return model; }; _Class.prototype.getProp = function(propName, scope, model) { return this.scopeOrModelVal(propName, scope, model); }; /* For the cases were watching a large object we only want to know the list of props that actually changed. Also we want to limit the amount of props we analyze to whitelisted props that are actually tracked by scope. (should make things faster with whitelisted) */ _Class.prototype.getChanges = function(now, prev, whitelistedProps) { var c, changes, prop; if (whitelistedProps) { prev = _.pick(prev, whitelistedProps); now = _.pick(now, whitelistedProps); } changes = {}; prop = {}; c = {}; for (prop in now) { if (!prev || prev[prop] !== now[prop]) { if (_.isArray(now[prop])) { changes[prop] = now[prop]; } else if (_.isObject(now[prop])) { c = this.getChanges(now[prop], (prev ? prev[prop] : null)); if (!_.isEmpty(c)) { changes[prop] = c; } } else { changes[prop] = now[prop]; } } } return changes; }; _Class.prototype.scopeOrModelVal = function(key, scope, model, doWrap) { var maybeWrap, modelKey, modelProp, scopeProp; if (doWrap == null) { doWrap = false; } maybeWrap = function(isScope, ret, doWrap) { if (doWrap == null) { doWrap = false; } if (doWrap) { return { isScope: isScope, value: ret }; } return ret; }; scopeProp = _.get(scope, key); if (_.isFunction(scopeProp)) { return maybeWrap(true, scopeProp(model), doWrap); } if (_.isObject(scopeProp)) { return maybeWrap(true, scopeProp, doWrap); } if (!_.isString(scopeProp)) { return maybeWrap(true, scopeProp, doWrap); } modelKey = scopeProp; if (!modelKey) { modelProp = _.get(model, key); } else { modelProp = modelKey === 'self' ? model : _.get(model, modelKey); } if (_.isFunction(modelProp)) { return maybeWrap(false, modelProp(), doWrap); } return maybeWrap(false, modelProp, doWrap); }; _Class.prototype.setChildScope = function(keys, childScope, model) { var isScopeObj, key, name, newValue; for (key in keys) { name = keys[key]; isScopeObj = this.scopeOrModelVal(name, childScope, model, true); if ((isScopeObj != null ? isScopeObj.value : void 0) != null) { newValue = isScopeObj.value; if (newValue !== childScope[name]) { childScope[name] = newValue; } } } return childScope.model = model; }; _Class.prototype.onDestroy = function(scope) {}; _Class.prototype.destroy = function(manualOverride) { var ref; if (manualOverride == null) { manualOverride = false; } if ((this.scope != null) && !((ref = this.scope) != null ? ref.$$destroyed : void 0) && (this.needToManualDestroy || manualOverride)) { return this.scope.$destroy(); } else { return this.clean(); } }; _Class.prototype.updateChild = function(child, model) { if (model[this.idKey] == null) { this.$log.error("Model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key."); return; } return child.updateModel(model); }; _Class.prototype.modelsLength = function(arrayOrObjModels) { var len, toCheck; if (arrayOrObjModels == null) { arrayOrObjModels = void 0; } len = 0; toCheck = arrayOrObjModels ? arrayOrObjModels : this.scope.models; if (toCheck == null) { return len; } if (angular.isArray(toCheck) || (toCheck.length != null)) { len = toCheck.length; } else { len = Object.keys(toCheck).length; } return len; }; return _Class; })(BaseObject); } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapModelsWatcher', [ 'uiGmapLogger', 'uiGmap_async', '$q', 'uiGmapPromise', function(Logger, _async, $q, uiGmapPromise) { return { didQueueInitPromise: function(existingPiecesObj, scope) { if (scope.models.length === 0) { _async.promiseLock(existingPiecesObj, uiGmapPromise.promiseTypes.init, null, null, (function() { return uiGmapPromise.resolve(); })); return true; } return false; }, figureOutState: function(idKey, scope, childObjects, comparison, callBack) { var adds, children, mappedScopeModelIds, removals, updates; adds = []; mappedScopeModelIds = {}; removals = []; updates = []; scope.models.forEach(function(m) { var child; if (m[idKey] != null) { mappedScopeModelIds[m[idKey]] = {}; if (childObjects.get(m[idKey]) == null) { return adds.push(m); } else { child = childObjects.get(m[idKey]); if (!comparison(m, child.clonedModel, scope)) { return updates.push({ model: m, child: child }); } } } else { return Logger.error(' id missing for model #{m.toString()},\ncan not use do comparison/insertion'); } }); children = childObjects.values(); children.forEach(function(c) { var id; if (c == null) { Logger.error('child undefined in ModelsWatcher.'); return; } if (c.model == null) { Logger.error('child.model undefined in ModelsWatcher.'); return; } id = c.model[idKey]; if (mappedScopeModelIds[id] == null) { return removals.push(c); } }); return { adds: adds, removals: removals, updates: updates }; } }; } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapPromise', [ '$q', '$timeout', 'uiGmapLogger', function($q, $timeout, $log) { var ExposedPromise, SniffedPromise, defer, isInProgress, isResolved, promise, promiseStatus, promiseStatuses, promiseTypes, resolve, strPromiseStatuses; promiseTypes = { create: 'create', update: 'update', "delete": 'delete', init: 'init' }; promiseStatuses = { IN_PROGRESS: 0, RESOLVED: 1, REJECTED: 2 }; strPromiseStatuses = (function() { var obj; obj = {}; obj["" + promiseStatuses.IN_PROGRESS] = 'in-progress'; obj["" + promiseStatuses.RESOLVED] = 'resolved'; obj["" + promiseStatuses.REJECTED] = 'rejected'; return obj; })(); isInProgress = function(promise) { if (promise.$$state) { return promise.$$state.status === promiseStatuses.IN_PROGRESS; } if (!promise.hasOwnProperty("$$v")) { return true; } }; isResolved = function(promise) { if (promise.$$state) { return promise.$$state.status === promiseStatuses.RESOLVED; } if (promise.hasOwnProperty("$$v")) { return true; } }; promiseStatus = function(status) { return strPromiseStatuses[status] || 'done w error'; }; ExposedPromise = function(promise) { var cancelDeferred, combined, wrapped; cancelDeferred = $q.defer(); combined = $q.all([promise, cancelDeferred.promise]); wrapped = $q.defer(); promise.then(cancelDeferred.resolve, (function() {}), function(notify) { cancelDeferred.notify(notify); return wrapped.notify(notify); }); combined.then(function(successes) { return wrapped.resolve(successes[0] || successes[1]); }, function(error) { return wrapped.reject(error); }); wrapped.promise.cancel = function(reason) { if (reason == null) { reason = 'canceled'; } return cancelDeferred.reject(reason); }; wrapped.promise.notify = function(msg) { if (msg == null) { msg = 'cancel safe'; } wrapped.notify(msg); if (promise.hasOwnProperty('notify')) { return promise.notify(msg); } }; if (promise.promiseType != null) { wrapped.promise.promiseType = promise.promiseType; } return wrapped.promise; }; SniffedPromise = function(fnPromise, promiseType) { return { promise: fnPromise, promiseType: promiseType }; }; defer = function() { return $q.defer(); }; resolve = function() { var d; d = $q.defer(); d.resolve.apply(void 0, arguments); return d.promise; }; promise = function(fnToWrap) { var d; if (!_.isFunction(fnToWrap)) { $log.error("uiGmapPromise.promise() only accepts functions"); return; } d = $q.defer(); $timeout(function() { var result; result = fnToWrap(); return d.resolve(result); }); return d.promise; }; return { defer: defer, promise: promise, resolve: resolve, promiseTypes: promiseTypes, isInProgress: isInProgress, isResolved: isResolved, promiseStatus: promiseStatus, ExposedPromise: ExposedPromise, SniffedPromise: SniffedPromise }; } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapPropMap", function() { /* Simple Object Map with a length property to make it easy to track length/size */ var PropMap; return PropMap = (function() { function PropMap() { this.removeAll = bind(this.removeAll, this); this.slice = bind(this.slice, this); this.push = bind(this.push, this); this.keys = bind(this.keys, this); this.values = bind(this.values, this); this.remove = bind(this.remove, this); this.put = bind(this.put, this); this.stateChanged = bind(this.stateChanged, this); this.get = bind(this.get, this); this.length = 0; this.dict = {}; this.didValsStateChange = false; this.didKeysStateChange = false; this.allVals = []; this.allKeys = []; } PropMap.prototype.get = function(key) { return this.dict[key]; }; PropMap.prototype.stateChanged = function() { this.didValsStateChange = true; return this.didKeysStateChange = true; }; PropMap.prototype.put = function(key, value) { if (this.get(key) == null) { this.length++; } this.stateChanged(); return this.dict[key] = value; }; PropMap.prototype.remove = function(key, isSafe) { var value; if (isSafe == null) { isSafe = false; } if (isSafe && !this.get(key)) { return void 0; } value = this.dict[key]; delete this.dict[key]; this.length--; this.stateChanged(); return value; }; PropMap.prototype.valuesOrKeys = function(str) { var keys, vals; if (str == null) { str = 'Keys'; } if (!this["did" + str + "StateChange"]) { return this['all' + str]; } vals = []; keys = []; _.each(this.dict, function(v, k) { vals.push(v); return keys.push(k); }); this.didKeysStateChange = false; this.didValsStateChange = false; this.allVals = vals; this.allKeys = keys; return this['all' + str]; }; PropMap.prototype.values = function() { return this.valuesOrKeys('Vals'); }; PropMap.prototype.keys = function() { return this.valuesOrKeys(); }; PropMap.prototype.push = function(obj, key) { if (key == null) { key = "key"; } return this.put(obj[key], obj); }; PropMap.prototype.slice = function() { return this.keys().map((function(_this) { return function(k) { return _this.remove(k); }; })(this)); }; PropMap.prototype.removeAll = function() { return this.slice(); }; PropMap.prototype.each = function(cb) { return _.each(this.dict, function(v, k) { return cb(v); }); }; PropMap.prototype.map = function(cb) { return _.map(this.dict, function(v, k) { return cb(v); }); }; return PropMap; })(); }); }).call(this); ; /*globals angular,_ */ (function() { angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapPropertyAction", [ "uiGmapLogger", function(Logger) { var PropertyAction; PropertyAction = function(setterFn) { this.setIfChange = function(callingKey) { return function(newVal, oldVal) { if (!_.isEqual(oldVal, newVal)) { return setterFn(callingKey, newVal); } }; }; this.sic = this.setIfChange; return this; }; return PropertyAction; } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; angular.module('uiGmapgoogle-maps.directives.api.managers').factory('uiGmapClustererMarkerManager', [ 'uiGmapLogger', 'uiGmapFitHelper', 'uiGmapPropMap', 'uiGmapEventsHelper', function($log, FitHelper, PropMap, EventsHelper) { var ClustererMarkerManager; ClustererMarkerManager = (function() { ClustererMarkerManager.type = 'ClustererMarkerManager'; function ClustererMarkerManager(gMap, opt_markers, opt_options, opt_events) { if (opt_markers == null) { opt_markers = {}; } this.opt_options = opt_options != null ? opt_options : {}; this.opt_events = opt_events; this.getGMarkers = bind(this.getGMarkers, this); this.fit = bind(this.fit, this); this.destroy = bind(this.destroy, this); this.attachEvents = bind(this.attachEvents, this); this.clear = bind(this.clear, this); this.draw = bind(this.draw, this); this.removeMany = bind(this.removeMany, this); this.remove = bind(this.remove, this); this.addMany = bind(this.addMany, this); this.update = bind(this.update, this); this.add = bind(this.add, this); this.type = ClustererMarkerManager.type; this.clusterer = new NgMapMarkerClusterer(gMap, opt_markers, this.opt_options); this.propMapGMarkers = new PropMap(); this.attachEvents(this.opt_events, 'opt_events'); this.clusterer.setIgnoreHidden(true); this.noDrawOnSingleAddRemoves = true; $log.info(this); } ClustererMarkerManager.prototype.checkKey = function(gMarker) { var msg; if (gMarker.key == null) { msg = 'gMarker.key undefined and it is REQUIRED!!'; return $log.error(msg); } }; ClustererMarkerManager.prototype.add = function(gMarker) { this.checkKey(gMarker); this.clusterer.addMarker(gMarker, this.noDrawOnSingleAddRemoves); this.propMapGMarkers.put(gMarker.key, gMarker); return this.checkSync(); }; ClustererMarkerManager.prototype.update = function(gMarker) { this.remove(gMarker); return this.add(gMarker); }; ClustererMarkerManager.prototype.addMany = function(gMarkers) { return gMarkers.forEach((function(_this) { return function(gMarker) { return _this.add(gMarker); }; })(this)); }; ClustererMarkerManager.prototype.remove = function(gMarker) { var exists; this.checkKey(gMarker); exists = this.propMapGMarkers.get(gMarker.key); if (exists) { this.clusterer.removeMarker(gMarker, this.noDrawOnSingleAddRemoves); this.propMapGMarkers.remove(gMarker.key); } return this.checkSync(); }; ClustererMarkerManager.prototype.removeMany = function(gMarkers) { return gMarkers.forEach((function(_this) { return function(gMarker) { return _this.remove(gMarker); }; })(this)); }; ClustererMarkerManager.prototype.draw = function() { return this.clusterer.repaint(); }; ClustererMarkerManager.prototype.clear = function() { this.removeMany(this.getGMarkers()); return this.clusterer.repaint(); }; ClustererMarkerManager.prototype.attachEvents = function(options, optionsName) { var eventHandler, eventName, results; this.listeners = []; if (angular.isDefined(options) && (options != null) && angular.isObject(options)) { results = []; for (eventName in options) { eventHandler = options[eventName]; if (options.hasOwnProperty(eventName) && angular.isFunction(options[eventName])) { $log.info(optionsName + ": Attaching event: " + eventName + " to clusterer"); results.push(this.listeners.push(google.maps.event.addListener(this.clusterer, eventName, options[eventName]))); } else { results.push(void 0); } } return results; } }; ClustererMarkerManager.prototype.clearEvents = function() { EventsHelper.removeEvents(this.listeners); return this.listeners = []; }; ClustererMarkerManager.prototype.destroy = function() { this.clearEvents(); return this.clear(); }; ClustererMarkerManager.prototype.fit = function() { return FitHelper.fit(this.getGMarkers(), this.clusterer.getMap()); }; ClustererMarkerManager.prototype.getGMarkers = function() { return this.clusterer.getMarkers().values(); }; ClustererMarkerManager.prototype.checkSync = function() {}; return ClustererMarkerManager; })(); return ClustererMarkerManager; } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api.managers').service('uiGmapGoogleMapObjectManager', [ function() { var _availableInstances, _usedInstances; _availableInstances = []; _usedInstances = []; return { createMapInstance: function(parentElement, options) { var instance; instance = null; if (_availableInstances.length === 0) { instance = new google.maps.Map(parentElement, options); _usedInstances.push(instance); } else { instance = _availableInstances.pop(); angular.element(parentElement).append(instance.getDiv()); instance.setOptions(options); _usedInstances.push(instance); } return instance; }, recycleMapInstance: function(instance) { var index; index = _usedInstances.indexOf(instance); if (index < 0) { throw new Error('Expected map instance to be a previously used instance'); } _usedInstances.splice(index, 1); return _availableInstances.push(instance); } }; } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; angular.module("uiGmapgoogle-maps.directives.api.managers").factory("uiGmapMarkerManager", [ "uiGmapLogger", "uiGmapFitHelper", "uiGmapPropMap", function(Logger, FitHelper, PropMap) { var MarkerManager; MarkerManager = (function() { MarkerManager.type = 'MarkerManager'; function MarkerManager(gMap, opt_markers, opt_options) { this.getGMarkers = bind(this.getGMarkers, this); this.fit = bind(this.fit, this); this.handleOptDraw = bind(this.handleOptDraw, this); this.clear = bind(this.clear, this); this.destroy = bind(this.destroy, this); this.draw = bind(this.draw, this); this.removeMany = bind(this.removeMany, this); this.remove = bind(this.remove, this); this.addMany = bind(this.addMany, this); this.update = bind(this.update, this); this.add = bind(this.add, this); this.type = MarkerManager.type; this.gMap = gMap; this.gMarkers = new PropMap(); this.$log = Logger; this.$log.info(this); } MarkerManager.prototype.add = function(gMarker, optDraw) { var exists, msg; if (optDraw == null) { optDraw = true; } if (gMarker.key == null) { msg = "gMarker.key undefined and it is REQUIRED!!"; Logger.error(msg); throw msg; } exists = this.gMarkers.get(gMarker.key); if (!exists) { this.handleOptDraw(gMarker, optDraw, true); return this.gMarkers.put(gMarker.key, gMarker); } }; MarkerManager.prototype.update = function(gMarker, optDraw) { if (optDraw == null) { optDraw = true; } this.remove(gMarker, optDraw); return this.add(gMarker, optDraw); }; MarkerManager.prototype.addMany = function(gMarkers) { return gMarkers.forEach((function(_this) { return function(gMarker) { return _this.add(gMarker); }; })(this)); }; MarkerManager.prototype.remove = function(gMarker, optDraw) { if (optDraw == null) { optDraw = true; } this.handleOptDraw(gMarker, optDraw, false); if (this.gMarkers.get(gMarker.key)) { return this.gMarkers.remove(gMarker.key); } }; MarkerManager.prototype.removeMany = function(gMarkers) { return gMarkers.forEach((function(_this) { return function(marker) { return _this.remove(marker); }; })(this)); }; MarkerManager.prototype.draw = function() { var deletes; deletes = []; this.gMarkers.each((function(_this) { return function(gMarker) { if (!gMarker.isDrawn) { if (gMarker.doAdd) { gMarker.setMap(_this.gMap); return gMarker.isDrawn = true; } else { return deletes.push(gMarker); } } }; })(this)); return deletes.forEach((function(_this) { return function(gMarker) { gMarker.isDrawn = false; return _this.remove(gMarker, true); }; })(this)); }; MarkerManager.prototype.destroy = function() { return this.clear(); }; MarkerManager.prototype.clear = function() { this.gMarkers.each(function(gMarker) { return gMarker.setMap(null); }); delete this.gMarkers; return this.gMarkers = new PropMap(); }; MarkerManager.prototype.handleOptDraw = function(gMarker, optDraw, doAdd) { if (optDraw === true) { if (doAdd) { gMarker.setMap(this.gMap); } else { gMarker.setMap(null); } return gMarker.isDrawn = true; } else { gMarker.isDrawn = false; return gMarker.doAdd = doAdd; } }; MarkerManager.prototype.fit = function() { return FitHelper.fit(this.getGMarkers(), this.gMap); }; MarkerManager.prototype.getGMarkers = function() { return this.gMarkers.values(); }; return MarkerManager; })(); return MarkerManager; } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; angular.module('uiGmapgoogle-maps.directives.api.managers').factory('uiGmapSpiderfierMarkerManager', [ 'uiGmapLogger', 'uiGmapFitHelper', 'uiGmapPropMap', 'uiGmapMarkerSpiderfier', function($log, FitHelper, PropMap, MarkerSpiderfier) { var SpiderfierMarkerManager; return SpiderfierMarkerManager = (function() { SpiderfierMarkerManager.type = 'SpiderfierMarkerManager'; function SpiderfierMarkerManager(gMap, opt_markers, opt_options, opt_events, scope) { if (opt_markers == null) { opt_markers = {}; } this.opt_options = opt_options != null ? opt_options : {}; this.opt_events = opt_events; this.scope = scope; this.isSpiderfied = bind(this.isSpiderfied, this); this.getGMarkers = bind(this.getGMarkers, this); this.fit = bind(this.fit, this); this.destroy = bind(this.destroy, this); this.attachEvents = bind(this.attachEvents, this); this.clear = bind(this.clear, this); this.removeMany = bind(this.removeMany, this); this.remove = bind(this.remove, this); this.addMany = bind(this.addMany, this); this.update = bind(this.update, this); this.add = bind(this.add, this); this.type = SpiderfierMarkerManager.type; this.markerSpiderfier = new MarkerSpiderfier(gMap, this.opt_options); this.propMapGMarkers = new PropMap(); this.attachEvents(this.opt_events, 'opt_events'); this.noDrawOnSingleAddRemoves = true; $log.info(this); } SpiderfierMarkerManager.prototype.checkKey = function(gMarker) { var msg; if (gMarker.key == null) { msg = 'gMarker.key undefined and it is REQUIRED!!'; return $log.error(msg); } }; SpiderfierMarkerManager.prototype.add = function(gMarker) { gMarker.setMap(this.markerSpiderfier.map); this.checkKey(gMarker); this.markerSpiderfier.addMarker(gMarker, this.noDrawOnSingleAddRemoves); this.propMapGMarkers.put(gMarker.key, gMarker); return this.checkSync(); }; SpiderfierMarkerManager.prototype.update = function(gMarker) { this.remove(gMarker); return this.add(gMarker); }; SpiderfierMarkerManager.prototype.addMany = function(gMarkers) { return gMarkers.forEach((function(_this) { return function(gMarker) { return _this.add(gMarker); }; })(this)); }; SpiderfierMarkerManager.prototype.remove = function(gMarker) { var exists; this.checkKey(gMarker); exists = this.propMapGMarkers.get(gMarker.key); if (exists) { gMarker.setMap(null); this.markerSpiderfier.removeMarker(gMarker, this.noDrawOnSingleAddRemoves); this.propMapGMarkers.remove(gMarker.key); } return this.checkSync(); }; SpiderfierMarkerManager.prototype.removeMany = function(gMarkers) { return gMarkers.forEach((function(_this) { return function(gMarker) { return _this.remove(gMarker); }; })(this)); }; SpiderfierMarkerManager.prototype.draw = function() {}; SpiderfierMarkerManager.prototype.clear = function() { return this.removeMany(this.getGMarkers()); }; SpiderfierMarkerManager.prototype.attachEvents = function(options, optionsName) { if (angular.isDefined(options) && (options != null) && angular.isObject(options)) { return _.each(options, (function(_this) { return function(eventHandler, eventName) { if (options.hasOwnProperty(eventName) && angular.isFunction(options[eventName])) { $log.info(optionsName + ": Attaching event: " + eventName + " to markerSpiderfier"); return _this.markerSpiderfier.addListener(eventName, function() { if (eventName === 'spiderfy' || eventName === 'unspiderfy') { return _this.scope.$evalAsync(options[eventName].apply(options, arguments)); } else { return _this.scope.$evalAsync(options[eventName].apply(options, [arguments[0], eventName, arguments[0].model, arguments])); } }); } }; })(this)); } }; SpiderfierMarkerManager.prototype.clearEvents = function(options, optionsName) { var eventHandler, eventName; if (angular.isDefined(options) && (options != null) && angular.isObject(options)) { for (eventName in options) { eventHandler = options[eventName]; if (options.hasOwnProperty(eventName) && angular.isFunction(options[eventName])) { $log.info(optionsName + ": Clearing event: " + eventName + " to markerSpiderfier"); this.markerSpiderfier.clearListeners(eventName); } } } }; SpiderfierMarkerManager.prototype.destroy = function() { this.clearEvents(this.opt_events, 'opt_events'); return this.clear(); }; SpiderfierMarkerManager.prototype.fit = function() { return FitHelper.fit(this.getGMarkers(), this.markerSpiderfier.map); }; SpiderfierMarkerManager.prototype.getGMarkers = function() { return this.markerSpiderfier.getMarkers(); }; SpiderfierMarkerManager.prototype.isSpiderfied = function() { return _.find(this.getGMarkers(), function(gMarker) { return (gMarker != null ? gMarker._omsData : void 0) != null; }); }; SpiderfierMarkerManager.prototype.checkSync = function() {}; return SpiderfierMarkerManager; })(); } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps').factory('uiGmapadd-events', [ '$timeout', function($timeout) { var addEvent, addEvents; addEvent = function(target, eventName, handler) { return google.maps.event.addListener(target, eventName, function() { handler.apply(this, arguments); return $timeout((function() {}), true); }); }; addEvents = function(target, eventName, handler) { var remove; if (handler) { return addEvent(target, eventName, handler); } remove = []; angular.forEach(eventName, function(_handler, key) { return remove.push(addEvent(target, key, _handler)); }); return function() { angular.forEach(remove, function(listener) { return google.maps.event.removeListener(listener); }); return remove = null; }; }; return addEvents; } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps').factory('uiGmaparray-sync', [ 'uiGmapadd-events', function(mapEvents) { return function(mapArray, scope, pathEval, pathChangedFn) { var geojsonArray, geojsonHandlers, geojsonWatcher, isSetFromScope, legacyHandlers, legacyWatcher, mapArrayListener, scopePath, watchListener; isSetFromScope = false; scopePath = scope.$eval(pathEval); if (!scope["static"]) { legacyHandlers = { set_at: function(index) { var value; if (isSetFromScope) { return; } value = mapArray.getAt(index); if (!value) { return; } if (!value.lng || !value.lat) { return scopePath[index] = value; } else { scopePath[index].latitude = value.lat(); return scopePath[index].longitude = value.lng(); } }, insert_at: function(index) { var value; if (isSetFromScope) { return; } value = mapArray.getAt(index); if (!value) { return; } if (!value.lng || !value.lat) { return scopePath.splice(index, 0, value); } else { return scopePath.splice(index, 0, { latitude: value.lat(), longitude: value.lng() }); } }, remove_at: function(index) { if (isSetFromScope) { return; } return scopePath.splice(index, 1); } }; geojsonArray; if (scopePath.type === 'Polygon') { geojsonArray = scopePath.coordinates[0]; } else if (scopePath.type === 'LineString') { geojsonArray = scopePath.coordinates; } geojsonHandlers = { set_at: function(index) { var value; if (isSetFromScope) { return; } value = mapArray.getAt(index); if (!(value && value.lng && value.lat)) { return; } geojsonArray[index][1] = value.lat(); return geojsonArray[index][0] = value.lng(); }, insert_at: function(index) { var value; if (isSetFromScope) { return; } value = mapArray.getAt(index); if (!value) { return; } if (!value.lng || !value.lat) { return; } return geojsonArray.splice(index, 0, [value.lng(), value.lat()]); }, remove_at: function(index) { if (isSetFromScope) { return; } return geojsonArray.splice(index, 1); } }; mapArrayListener = mapEvents(mapArray, angular.isUndefined(scopePath.type) ? legacyHandlers : geojsonHandlers); } legacyWatcher = function(newPath) { var changed, i, l, newLength, newValue, oldArray, oldLength, oldValue; isSetFromScope = true; oldArray = mapArray; changed = false; if (newPath) { i = 0; oldLength = oldArray.getLength(); newLength = newPath.length; l = Math.min(oldLength, newLength); newValue = void 0; while (i < l) { oldValue = oldArray.getAt(i); newValue = newPath[i]; if (typeof newValue.equals === 'function') { if (!newValue.equals(oldValue)) { oldArray.setAt(i, newValue); changed = true; } } else { if ((oldValue.lat() !== newValue.latitude) || (oldValue.lng() !== newValue.longitude)) { oldArray.setAt(i, new google.maps.LatLng(newValue.latitude, newValue.longitude)); changed = true; } } i++; } while (i < newLength) { newValue = newPath[i]; if (typeof newValue.lat === 'function' && typeof newValue.lng === 'function') { oldArray.push(newValue); } else { oldArray.push(new google.maps.LatLng(newValue.latitude, newValue.longitude)); } changed = true; i++; } while (i < oldLength) { oldArray.pop(); changed = true; i++; } } isSetFromScope = false; if (changed) { return pathChangedFn(oldArray); } }; geojsonWatcher = function(newPath) { var array, changed, i, l, newLength, newValue, oldArray, oldLength, oldValue; isSetFromScope = true; oldArray = mapArray; changed = false; if (newPath) { array; if (scopePath.type === 'Polygon') { array = newPath.coordinates[0]; } else if (scopePath.type === 'LineString') { array = newPath.coordinates; } i = 0; oldLength = oldArray.getLength(); newLength = array.length; l = Math.min(oldLength, newLength); newValue = void 0; while (i < l) { oldValue = oldArray.getAt(i); newValue = array[i]; if ((oldValue.lat() !== newValue[1]) || (oldValue.lng() !== newValue[0])) { oldArray.setAt(i, new google.maps.LatLng(newValue[1], newValue[0])); changed = true; } i++; } while (i < newLength) { newValue = array[i]; oldArray.push(new google.maps.LatLng(newValue[1], newValue[0])); changed = true; i++; } while (i < oldLength) { oldArray.pop(); changed = true; i++; } } isSetFromScope = false; if (changed) { return pathChangedFn(oldArray); } }; watchListener; if (!scope["static"]) { if (angular.isUndefined(scopePath.type)) { watchListener = scope.$watchCollection(pathEval, legacyWatcher); } else { watchListener = scope.$watch(pathEval, geojsonWatcher, true); } } return function() { if (mapArrayListener) { mapArrayListener(); mapArrayListener = null; } if (watchListener) { watchListener(); return watchListener = null; } }; }; } ]); }).call(this); ;(function() { angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapChromeFixes", [ '$timeout', function($timeout) { return { maybeRepaint: function(el) { if (el) { el.style.opacity = 0.9; return $timeout(function() { return el.style.opacity = 1; }); } } }; } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps').service('uiGmapObjectIterators', function() { var _ignores, _iterators, _slapForEach, _slapMap; _ignores = ['length', 'forEach', 'map']; _iterators = []; _slapForEach = function(object) { object.forEach = function(cb) { return _.each(_.omit(object, _ignores), function(val) { if (!_.isFunction(val)) { return cb(val); } }); }; return object; }; _iterators.push(_slapForEach); _slapMap = function(object) { object.map = function(cb) { return _.map(_.omit(object, _ignores), function(val) { if (!_.isFunction(val)) { return cb(val); } }); }; return object; }; _iterators.push(_slapMap); return { slapMap: _slapMap, slapForEach: _slapForEach, slapAll: function(object) { _iterators.forEach(function(it) { return it(object); }); return object; } }; }); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.options.builders').service('uiGmapCommonOptionsBuilder', [ 'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapModelKey', function(BaseObject, $log, ModelKey) { var CommonOptionsBuilder; return CommonOptionsBuilder = (function(superClass) { extend(CommonOptionsBuilder, superClass); function CommonOptionsBuilder() { this.watchProps = bind(this.watchProps, this); this.buildOpts = bind(this.buildOpts, this); return CommonOptionsBuilder.__super__.constructor.apply(this, arguments); } CommonOptionsBuilder.prototype.props = [ 'clickable', 'draggable', 'editable', 'visible', { prop: 'stroke', isColl: true } ]; CommonOptionsBuilder.prototype.getCorrectModel = function(scope) { if (angular.isDefined(scope != null ? scope.model : void 0)) { return scope.model; } else { return scope; } }; CommonOptionsBuilder.prototype.buildOpts = function(customOpts, cachedEval, forEachOpts) { var model, opts, stroke; if (customOpts == null) { customOpts = {}; } if (forEachOpts == null) { forEachOpts = {}; } if (!this.scope) { $log.error('this.scope not defined in CommonOptionsBuilder can not buildOpts'); return; } if (!this.gMap) { $log.error('this.map not defined in CommonOptionsBuilder can not buildOpts'); return; } model = this.getCorrectModel(this.scope); stroke = this.scopeOrModelVal('stroke', this.scope, model); opts = angular.extend(customOpts, this.DEFAULTS, { map: this.gMap, strokeColor: stroke != null ? stroke.color : void 0, strokeOpacity: stroke != null ? stroke.opacity : void 0, strokeWeight: stroke != null ? stroke.weight : void 0 }); angular.forEach(angular.extend(forEachOpts, { clickable: true, draggable: false, editable: false, "static": false, fit: false, visible: true, zIndex: 0, icons: [] }), (function(_this) { return function(defaultValue, key) { var val; val = cachedEval ? cachedEval[key] : _this.scopeOrModelVal(key, _this.scope, model); if (angular.isUndefined(val)) { return opts[key] = defaultValue; } else { return opts[key] = model[key]; } }; })(this)); if (opts["static"]) { opts.editable = false; } return opts; }; CommonOptionsBuilder.prototype.watchProps = function(props) { if (props == null) { props = this.props; } return props.forEach((function(_this) { return function(prop) { if ((_this.attrs[prop] != null) || (_this.attrs[prop != null ? prop.prop : void 0] != null)) { if (prop != null ? prop.isColl : void 0) { return _this.scope.$watchCollection(prop.prop, _this.setMyOptions); } else { return _this.scope.$watch(prop, _this.setMyOptions); } } }; })(this)); }; return CommonOptionsBuilder; })(ModelKey); } ]); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.options.builders').factory('uiGmapPolylineOptionsBuilder', [ 'uiGmapCommonOptionsBuilder', function(CommonOptionsBuilder) { var PolylineOptionsBuilder; return PolylineOptionsBuilder = (function(superClass) { extend(PolylineOptionsBuilder, superClass); function PolylineOptionsBuilder() { return PolylineOptionsBuilder.__super__.constructor.apply(this, arguments); } PolylineOptionsBuilder.prototype.buildOpts = function(pathPoints, cachedEval) { return PolylineOptionsBuilder.__super__.buildOpts.call(this, { path: pathPoints }, cachedEval, { geodesic: false }); }; return PolylineOptionsBuilder; })(CommonOptionsBuilder); } ]).factory('uiGmapShapeOptionsBuilder', [ 'uiGmapCommonOptionsBuilder', function(CommonOptionsBuilder) { var ShapeOptionsBuilder; return ShapeOptionsBuilder = (function(superClass) { extend(ShapeOptionsBuilder, superClass); function ShapeOptionsBuilder() { return ShapeOptionsBuilder.__super__.constructor.apply(this, arguments); } ShapeOptionsBuilder.prototype.buildOpts = function(customOpts, cachedEval, forEachOpts) { var fill, model; model = this.getCorrectModel(this.scope); fill = cachedEval ? cachedEval['fill'] : this.scopeOrModelVal('fill', this.scope, model); customOpts = angular.extend(customOpts, { fillColor: fill != null ? fill.color : void 0, fillOpacity: fill != null ? fill.opacity : void 0 }); return ShapeOptionsBuilder.__super__.buildOpts.call(this, customOpts, cachedEval, forEachOpts); }; return ShapeOptionsBuilder; })(CommonOptionsBuilder); } ]).factory('uiGmapPolygonOptionsBuilder', [ 'uiGmapShapeOptionsBuilder', function(ShapeOptionsBuilder) { var PolygonOptionsBuilder; return PolygonOptionsBuilder = (function(superClass) { extend(PolygonOptionsBuilder, superClass); function PolygonOptionsBuilder() { return PolygonOptionsBuilder.__super__.constructor.apply(this, arguments); } PolygonOptionsBuilder.prototype.buildOpts = function(pathPoints, cachedEval) { return PolygonOptionsBuilder.__super__.buildOpts.call(this, { path: pathPoints }, cachedEval, { geodesic: false }); }; return PolygonOptionsBuilder; })(ShapeOptionsBuilder); } ]).factory('uiGmapRectangleOptionsBuilder', [ 'uiGmapShapeOptionsBuilder', function(ShapeOptionsBuilder) { var RectangleOptionsBuilder; return RectangleOptionsBuilder = (function(superClass) { extend(RectangleOptionsBuilder, superClass); function RectangleOptionsBuilder() { return RectangleOptionsBuilder.__super__.constructor.apply(this, arguments); } RectangleOptionsBuilder.prototype.buildOpts = function(bounds, cachedEval) { return RectangleOptionsBuilder.__super__.buildOpts.call(this, { bounds: bounds }, cachedEval); }; return RectangleOptionsBuilder; })(ShapeOptionsBuilder); } ]).factory('uiGmapCircleOptionsBuilder', [ 'uiGmapShapeOptionsBuilder', function(ShapeOptionsBuilder) { var CircleOptionsBuilder; return CircleOptionsBuilder = (function(superClass) { extend(CircleOptionsBuilder, superClass); function CircleOptionsBuilder() { return CircleOptionsBuilder.__super__.constructor.apply(this, arguments); } CircleOptionsBuilder.prototype.buildOpts = function(center, radius, cachedEval) { return CircleOptionsBuilder.__super__.buildOpts.call(this, { center: center, radius: radius }, cachedEval); }; return CircleOptionsBuilder; })(ShapeOptionsBuilder); } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api.options').service('uiGmapMarkerOptions', [ 'uiGmapLogger', 'uiGmapGmapUtil', function($log, GmapUtil) { return _.extend(GmapUtil, { createOptions: function(coords, icon, defaults, map) { var opts; if (defaults == null) { defaults = {}; } opts = angular.extend({}, defaults, { position: defaults.position != null ? defaults.position : GmapUtil.getCoords(coords), visible: defaults.visible != null ? defaults.visible : GmapUtil.validateCoords(coords) }); if ((defaults.icon != null) || (icon != null)) { opts = angular.extend(opts, { icon: defaults.icon != null ? defaults.icon : icon }); } if (map != null) { opts.map = map; } return opts; }, isLabel: function(options) { if (options == null) { return false; } return (options.labelContent != null) || (options.labelAnchor != null) || (options.labelClass != null) || (options.labelStyle != null) || (options.labelVisible != null); } }); } ]); }).call(this); ; /*global _,angular */ (function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapBasePolyChildModel', [ 'uiGmapLogger', '$timeout', 'uiGmaparray-sync', 'uiGmapGmapUtil', 'uiGmapEventsHelper', function($log, $timeout, arraySync, GmapUtil, EventsHelper) { return function(Builder, gFactory) { var BasePolyChildModel; return BasePolyChildModel = (function(superClass) { extend(BasePolyChildModel, superClass); BasePolyChildModel.include(GmapUtil); function BasePolyChildModel(arg) { var create, gObjectChangeCb, ref; this.scope = arg.scope, this.attrs = arg.attrs, this.gMap = arg.gMap, this.defaults = arg.defaults, this.model = arg.model, gObjectChangeCb = arg.gObjectChangeCb, this.isScopeModel = (ref = arg.isScopeModel) != null ? ref : false; this.clean = bind(this.clean, this); if (this.isScopeModel) { this.clonedModel = _.clone(this.model, true); } this.isDragging = false; this.internalEvents = { dragend: (function(_this) { return function() { return _.defer(function() { return _this.isDragging = false; }); }; })(this), dragstart: (function(_this) { return function() { return _this.isDragging = true; }; })(this) }; create = (function(_this) { return function() { var maybeCachedEval; if (_this.isDragging) { return; } _this.pathPoints = _this.convertPathPoints(_this.scope.path); if (_this.gObject != null) { _this.clean(); } if (_this.scope.model != null) { maybeCachedEval = _this.scope; } if (_this.pathPoints.length > 0) { _this.gObject = gFactory(_this.buildOpts(_this.pathPoints, maybeCachedEval)); } if (_this.gObject) { arraySync(_this.gObject.getPath(), _this.scope, 'path', function(pathPoints) { _this.pathPoints = pathPoints; if (gObjectChangeCb != null) { return gObjectChangeCb(); } }); if (angular.isDefined(_this.scope.events) && angular.isObject(_this.scope.events)) { _this.listeners = _this.model ? EventsHelper.setEvents(_this.gObject, _this.scope, _this.model) : EventsHelper.setEvents(_this.gObject, _this.scope, _this.scope); } return _this.internalListeners = _this.model ? EventsHelper.setEvents(_this.gObject, { events: _this.internalEvents }, _this.model) : EventsHelper.setEvents(_this.gObject, { events: _this.internalEvents }, _this.scope); } }; })(this); create(); this.scope.$watch('path', (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue) || !_this.gObject) { return create(); } }; })(this), true); if (!this.scope["static"] && angular.isDefined(this.scope.editable)) { this.scope.$watch('editable', (function(_this) { return function(newValue, oldValue) { var ref1; if (newValue !== oldValue) { newValue = !_this.isFalse(newValue); return (ref1 = _this.gObject) != null ? ref1.setEditable(newValue) : void 0; } }; })(this), true); } if (angular.isDefined(this.scope.draggable)) { this.scope.$watch('draggable', (function(_this) { return function(newValue, oldValue) { var ref1; if (newValue !== oldValue) { newValue = !_this.isFalse(newValue); return (ref1 = _this.gObject) != null ? ref1.setDraggable(newValue) : void 0; } }; })(this), true); } if (angular.isDefined(this.scope.visible)) { this.scope.$watch('visible', (function(_this) { return function(newValue, oldValue) { var ref1; if (newValue !== oldValue) { newValue = !_this.isFalse(newValue); } return (ref1 = _this.gObject) != null ? ref1.setVisible(newValue) : void 0; }; })(this), true); } if (angular.isDefined(this.scope.geodesic)) { this.scope.$watch('geodesic', (function(_this) { return function(newValue, oldValue) { var ref1; if (newValue !== oldValue) { newValue = !_this.isFalse(newValue); return (ref1 = _this.gObject) != null ? ref1.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0; } }; })(this), true); } if (angular.isDefined(this.scope.stroke) && angular.isDefined(this.scope.stroke.weight)) { this.scope.$watch('stroke.weight', (function(_this) { return function(newValue, oldValue) { var ref1; if (newValue !== oldValue) { return (ref1 = _this.gObject) != null ? ref1.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0; } }; })(this), true); } if (angular.isDefined(this.scope.stroke) && angular.isDefined(this.scope.stroke.color)) { this.scope.$watch('stroke.color', (function(_this) { return function(newValue, oldValue) { var ref1; if (newValue !== oldValue) { return (ref1 = _this.gObject) != null ? ref1.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0; } }; })(this), true); } if (angular.isDefined(this.scope.stroke) && angular.isDefined(this.scope.stroke.opacity)) { this.scope.$watch('stroke.opacity', (function(_this) { return function(newValue, oldValue) { var ref1; if (newValue !== oldValue) { return (ref1 = _this.gObject) != null ? ref1.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0; } }; })(this), true); } if (angular.isDefined(this.scope.icons)) { this.scope.$watch('icons', (function(_this) { return function(newValue, oldValue) { var ref1; if (newValue !== oldValue) { return (ref1 = _this.gObject) != null ? ref1.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0; } }; })(this), true); } this.scope.$on('$destroy', (function(_this) { return function() { _this.clean(); return _this.scope = null; }; })(this)); if (angular.isDefined(this.scope.fill) && angular.isDefined(this.scope.fill.color)) { this.scope.$watch('fill.color', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.gObject.setOptions(_this.buildOpts(_this.gObject.getPath())); } }; })(this)); } if (angular.isDefined(this.scope.fill) && angular.isDefined(this.scope.fill.opacity)) { this.scope.$watch('fill.opacity', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.gObject.setOptions(_this.buildOpts(_this.gObject.getPath())); } }; })(this)); } if (angular.isDefined(this.scope.zIndex)) { this.scope.$watch('zIndex', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.gObject.setOptions(_this.buildOpts(_this.gObject.getPath())); } }; })(this)); } } BasePolyChildModel.prototype.clean = function() { var ref; EventsHelper.removeEvents(this.listeners); EventsHelper.removeEvents(this.internalListeners); if ((ref = this.gObject) != null) { ref.setMap(null); } return this.gObject = null; }; return BasePolyChildModel; })(Builder); }; } ]); }).call(this); ; /* @authors Nicholas McCready - https://twitter.com/nmccready Original idea from: http://stackoverflow.com/questions/22758950/google-map-drawing-freehand , & http://jsfiddle.net/YsQdh/88/ */ (function() { angular.module('uiGmapgoogle-maps.directives.api.models.child').factory('uiGmapDrawFreeHandChildModel', [ 'uiGmapLogger', '$q', function($log, $q) { var drawFreeHand, freeHandMgr; drawFreeHand = function(map, polys, done) { var move, poly; poly = new google.maps.Polyline({ map: map, clickable: false }); move = google.maps.event.addListener(map, 'mousemove', function(e) { return poly.getPath().push(e.latLng); }); google.maps.event.addListenerOnce(map, 'mouseup', function(e) { var path; google.maps.event.removeListener(move); path = poly.getPath(); poly.setMap(null); polys.push(new google.maps.Polygon({ map: map, path: path })); poly = null; google.maps.event.clearListeners(map.getDiv(), 'mousedown'); return done(); }); return void 0; }; freeHandMgr = function(map1, scope) { var disableMap, enableMap; this.map = map1; disableMap = (function(_this) { return function() { var mapOptions; mapOptions = { draggable: false, disableDefaultUI: true, scrollwheel: false, disableDoubleClickZoom: false }; $log.info('disabling map move'); return _this.map.setOptions(mapOptions); }; })(this); enableMap = (function(_this) { return function() { var mapOptions, ref; mapOptions = { draggable: true, disableDefaultUI: false, scrollwheel: true, disableDoubleClickZoom: true }; if ((ref = _this.deferred) != null) { ref.resolve(); } return _.defer(function() { return _this.map.setOptions(_.extend(mapOptions, scope.options)); }); }; })(this); this.engage = (function(_this) { return function(polys1) { _this.polys = polys1; _this.deferred = $q.defer(); disableMap(); $log.info('DrawFreeHandChildModel is engaged (drawing).'); google.maps.event.addDomListener(_this.map.getDiv(), 'mousedown', function(e) { return drawFreeHand(_this.map, _this.polys, enableMap); }); return _this.deferred.promise; }; })(this); return this; }; return freeHandMgr; } ]); }).call(this); ; /*global _:true,angular:true,google:true, RichMarker:true */ (function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.models.child').factory('uiGmapMarkerChildModel', [ 'uiGmapModelKey', 'uiGmapGmapUtil', 'uiGmapLogger', 'uiGmapEventsHelper', 'uiGmapPropertyAction', 'uiGmapMarkerOptions', 'uiGmapIMarker', 'uiGmapMarkerManager', 'uiGmapPromise', function(ModelKey, GmapUtil, $log, EventsHelper, PropertyAction, MarkerOptions, IMarker, MarkerManager, uiGmapPromise) { var MarkerChildModel; MarkerChildModel = (function(superClass) { var destroy; extend(MarkerChildModel, superClass); MarkerChildModel.include(GmapUtil); MarkerChildModel.include(EventsHelper); MarkerChildModel.include(MarkerOptions); destroy = function(child) { if ((child != null ? child.gObject : void 0) != null) { child.removeEvents(child.externalListeners); child.removeEvents(child.internalListeners); if (child != null ? child.gObject : void 0) { if (child.removeFromManager) { child.gManager.remove(child.gObject); } child.gObject.setMap(null); return child.gObject = null; } } }; function MarkerChildModel(opts) { this.internalEvents = bind(this.internalEvents, this); this.setLabelOptions = bind(this.setLabelOptions, this); this.setOptions = bind(this.setOptions, this); this.setIcon = bind(this.setIcon, this); this.setCoords = bind(this.setCoords, this); this.isNotValid = bind(this.isNotValid, this); this.maybeSetScopeValue = bind(this.maybeSetScopeValue, this); this.createMarker = bind(this.createMarker, this); this.setMyScope = bind(this.setMyScope, this); this.updateModel = bind(this.updateModel, this); this.handleModelChanges = bind(this.handleModelChanges, this); this.destroy = bind(this.destroy, this); var action, ref, ref1, ref2, ref3, ref4, scope; scope = opts.scope, this.model = opts.model, this.keys = opts.keys, this.gMap = opts.gMap, this.defaults = (ref = opts.defaults) != null ? ref : {}, this.doClick = opts.doClick, this.gManager = opts.gManager, this.doDrawSelf = (ref1 = opts.doDrawSelf) != null ? ref1 : true, this.trackModel = (ref2 = opts.trackModel) != null ? ref2 : true, this.needRedraw = (ref3 = opts.needRedraw) != null ? ref3 : false, this.isScopeModel = (ref4 = opts.isScopeModel) != null ? ref4 : false; if (this.isScopeModel) { this.clonedModel = _.clone(this.model, true); } this.deferred = uiGmapPromise.defer(); _.each(this.keys, (function(_this) { return function(v, k) { var keyValue; keyValue = _this.keys[k]; if ((keyValue != null) && !_.isFunction(keyValue) && _.isString(keyValue)) { return _this[k + 'Key'] = keyValue; } }; })(this)); this.idKey = this.idKeyKey || 'id'; if (this.model[this.idKey] != null) { this.id = this.model[this.idKey]; } MarkerChildModel.__super__.constructor.call(this, scope); this.scope.getGMarker = (function(_this) { return function() { return _this.gObject; }; })(this); this.firstTime = true; if (this.trackModel) { this.scope.model = this.model; this.scope.$watch('model', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.handleModelChanges(newValue, oldValue); } }; })(this), true); } else { action = new PropertyAction((function(_this) { return function(calledKey) { if (_.isFunction(calledKey)) { calledKey = 'all'; } if (!_this.firstTime) { return _this.setMyScope(calledKey, scope); } }; })(this), false); _.each(this.keys, function(v, k) { return scope.$watch(k, action.sic(k), true); }); } this.scope.$on('$destroy', (function(_this) { return function() { return destroy(_this); }; })(this)); this.createMarker(this.model); $log.info(this); } MarkerChildModel.prototype.destroy = function(removeFromManager) { if (removeFromManager == null) { removeFromManager = true; } this.removeFromManager = removeFromManager; return this.scope.$destroy(); }; MarkerChildModel.prototype.handleModelChanges = function(newValue, oldValue) { var changes, ctr, len; changes = this.getChanges(newValue, oldValue, IMarker.keys); if (!this.firstTime) { ctr = 0; len = _.keys(changes).length; return _.each(changes, (function(_this) { return function(v, k) { var doDraw; ctr += 1; doDraw = len === ctr; _this.setMyScope(k, newValue, oldValue, false, true, doDraw); return _this.needRedraw = true; }; })(this)); } }; MarkerChildModel.prototype.updateModel = function(model) { if (this.isScopeModel) { this.clonedModel = _.clone(model, true); } return this.setMyScope('all', model, this.model); }; MarkerChildModel.prototype.renderGMarker = function(doDraw, validCb) { var coords, isSpiderfied, ref; if (doDraw == null) { doDraw = true; } coords = this.getProp('coords', this.scope, this.model); if (((ref = this.gManager) != null ? ref.isSpiderfied : void 0) != null) { isSpiderfied = this.gManager.isSpiderfied(); } if (coords != null) { if (!this.validateCoords(coords)) { $log.debug('MarkerChild does not have coords yet. They may be defined later.'); return; } if (validCb != null) { validCb(); } if (doDraw && this.gObject) { this.gManager.add(this.gObject); } if (isSpiderfied) { return this.gManager.markerSpiderfier.spiderListener(this.gObject, window.event); } } else { if (doDraw && this.gObject) { return this.gManager.remove(this.gObject); } } }; MarkerChildModel.prototype.setMyScope = function(thingThatChanged, model, oldModel, isInit, doDraw) { var justCreated; if (oldModel == null) { oldModel = void 0; } if (isInit == null) { isInit = false; } if (doDraw == null) { doDraw = true; } if (model == null) { model = this.model; } else { this.model = model; } if (!this.gObject) { this.setOptions(this.scope, doDraw); justCreated = true; } switch (thingThatChanged) { case 'all': return _.each(this.keys, (function(_this) { return function(v, k) { return _this.setMyScope(k, model, oldModel, isInit, doDraw); }; })(this)); case 'icon': return this.maybeSetScopeValue({ gSetter: this.setIcon, doDraw: doDraw }); case 'coords': return this.maybeSetScopeValue({ gSetter: this.setCoords, doDraw: doDraw }); case 'options': if (!justCreated) { return this.createMarker(model, oldModel, isInit, doDraw); } } }; MarkerChildModel.prototype.createMarker = function(model, oldModel, isInit, doDraw) { if (oldModel == null) { oldModel = void 0; } if (isInit == null) { isInit = false; } if (doDraw == null) { doDraw = true; } this.maybeSetScopeValue({ gSetter: this.setOptions, doDraw: doDraw }); return this.firstTime = false; }; MarkerChildModel.prototype.maybeSetScopeValue = function(arg) { var doDraw, gSetter, ref; gSetter = arg.gSetter, doDraw = (ref = arg.doDraw) != null ? ref : true; if (gSetter != null) { gSetter(this.scope, doDraw); } if (this.doDrawSelf && doDraw) { return this.gManager.draw(); } }; MarkerChildModel.prototype.isNotValid = function(scope, doCheckGmarker) { var hasIdenticalScopes, hasNoGmarker; if (doCheckGmarker == null) { doCheckGmarker = true; } hasNoGmarker = !doCheckGmarker ? false : this.gObject === void 0; hasIdenticalScopes = !this.trackModel ? scope.$id !== this.scope.$id : false; return hasIdenticalScopes || hasNoGmarker; }; MarkerChildModel.prototype.setCoords = function(scope, doDraw) { if (doDraw == null) { doDraw = true; } if (this.isNotValid(scope) || (this.gObject == null)) { return; } return this.renderGMarker(doDraw, (function(_this) { return function() { var newGValue, newModelVal, oldGValue; newModelVal = _this.getProp('coords', scope, _this.model); newGValue = _this.getCoords(newModelVal); oldGValue = _this.gObject.getPosition(); if ((oldGValue != null) && (newGValue != null)) { if (newGValue.lng() === oldGValue.lng() && newGValue.lat() === oldGValue.lat()) { return; } } _this.gObject.setPosition(newGValue); return _this.gObject.setVisible(_this.validateCoords(newModelVal)); }; })(this)); }; MarkerChildModel.prototype.setIcon = function(scope, doDraw) { if (doDraw == null) { doDraw = true; } if (this.isNotValid(scope) || (this.gObject == null)) { return; } return this.renderGMarker(doDraw, (function(_this) { return function() { var coords, newValue, oldValue; oldValue = _this.gObject.getIcon(); newValue = _this.getProp('icon', scope, _this.model); if (oldValue === newValue) { return; } _this.gObject.setIcon(newValue); coords = _this.getProp('coords', scope, _this.model); _this.gObject.setPosition(_this.getCoords(coords)); return _this.gObject.setVisible(_this.validateCoords(coords)); }; })(this)); }; MarkerChildModel.prototype.setOptions = function(scope, doDraw) { var ref; if (doDraw == null) { doDraw = true; } if (this.isNotValid(scope, false)) { return; } this.renderGMarker(doDraw, (function(_this) { return function() { var _options, coords, icon; coords = _this.getProp('coords', scope, _this.model); icon = _this.getProp('icon', scope, _this.model); _options = _this.getProp('options', scope, _this.model); _this.opts = _this.createOptions(coords, icon, _options); if (_this.isLabel(_this.gObject) !== _this.isLabel(_this.opts) && (_this.gObject != null)) { _this.gManager.remove(_this.gObject); _this.gObject = void 0; } if (_this.gObject != null) { _this.gObject.setOptions(_this.setLabelOptions(_this.opts)); } if (!_this.gObject) { if (_this.isLabel(_this.opts)) { _this.gObject = new MarkerWithLabel(_this.setLabelOptions(_this.opts)); } else if (_this.opts.content) { _this.gObject = new RichMarker(_this.opts); _this.gObject.getIcon = _this.gObject.getContent; _this.gObject.setIcon = _this.gObject.setContent; } else { _this.gObject = new google.maps.Marker(_this.opts); } _.extend(_this.gObject, { model: _this.model }); } if (_this.externalListeners) { _this.removeEvents(_this.externalListeners); } if (_this.internalListeners) { _this.removeEvents(_this.internalListeners); } _this.externalListeners = _this.setEvents(_this.gObject, _this.scope, _this.model, ['dragend']); _this.internalListeners = _this.setEvents(_this.gObject, { events: _this.internalEvents(), $evalAsync: function() {} }, _this.model); if (_this.id != null) { return _this.gObject.key = _this.id; } }; })(this)); if (this.gObject && (this.gObject.getMap() || this.gManager.type !== MarkerManager.type)) { this.deferred.resolve(this.gObject); } else { if (!this.gObject) { return this.deferred.reject('gObject is null'); } if (!(((ref = this.gObject) != null ? ref.getMap() : void 0) && this.gManager.type === MarkerManager.type)) { $log.debug('gObject has no map yet'); this.deferred.resolve(this.gObject); } } if (this.model[this.fitKey]) { return this.gManager.fit(); } }; MarkerChildModel.prototype.setLabelOptions = function(opts) { if (opts.labelAnchor) { opts.labelAnchor = this.getLabelPositionPoint(opts.labelAnchor); } return opts; }; MarkerChildModel.prototype.internalEvents = function() { return { dragend: (function(_this) { return function(marker, eventName, model, mousearg) { var events, modelToSet, newCoords; modelToSet = _this.trackModel ? _this.scope.model : _this.model; newCoords = _this.setCoordsFromEvent(_this.modelOrKey(modelToSet, _this.coordsKey), _this.gObject.getPosition()); modelToSet = _this.setVal(model, _this.coordsKey, newCoords); events = _this.scope.events; if ((events != null ? events.dragend : void 0) != null) { events.dragend(marker, eventName, modelToSet, mousearg); } return _this.scope.$apply(); }; })(this), click: (function(_this) { return function(marker, eventName, model, mousearg) { var click; click = _this.getProp('click', _this.scope, _this.model); if (_this.doClick && angular.isFunction(click)) { return _this.scope.$evalAsync(click(marker, eventName, _this.model, mousearg)); } }; })(this) }; }; return MarkerChildModel; })(ModelKey); return MarkerChildModel; } ]); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolygonChildModel', [ 'uiGmapBasePolyChildModel', 'uiGmapPolygonOptionsBuilder', function(BaseGen, Builder) { var PolygonChildModel, base, gFactory; gFactory = function(opts) { return new google.maps.Polygon(opts); }; base = new BaseGen(Builder, gFactory); return PolygonChildModel = (function(superClass) { extend(PolygonChildModel, superClass); function PolygonChildModel() { return PolygonChildModel.__super__.constructor.apply(this, arguments); } return PolygonChildModel; })(base); } ]); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolylineChildModel', [ 'uiGmapBasePolyChildModel', 'uiGmapPolylineOptionsBuilder', function(BaseGen, Builder) { var PolylineChildModel, base, gFactory; gFactory = function(opts) { return new google.maps.Polyline(opts); }; base = BaseGen(Builder, gFactory); return PolylineChildModel = (function(superClass) { extend(PolylineChildModel, superClass); function PolylineChildModel() { return PolylineChildModel.__super__.constructor.apply(this, arguments); } return PolylineChildModel; })(base); } ]); }).call(this); ; /*global _:true,angular:true,google:true */ (function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.models.child').factory('uiGmapWindowChildModel', [ 'uiGmapBaseObject', 'uiGmapGmapUtil', 'uiGmapLogger', '$compile', '$http', '$templateCache', 'uiGmapChromeFixes', 'uiGmapEventsHelper', function(BaseObject, GmapUtil, $log, $compile, $http, $templateCache, ChromeFixes, EventsHelper) { var WindowChildModel; WindowChildModel = (function(superClass) { extend(WindowChildModel, superClass); WindowChildModel.include(GmapUtil); WindowChildModel.include(EventsHelper); function WindowChildModel(opts) { this.updateModel = bind(this.updateModel, this); this.destroy = bind(this.destroy, this); this.remove = bind(this.remove, this); this.getLatestPosition = bind(this.getLatestPosition, this); this.hideWindow = bind(this.hideWindow, this); this.showWindow = bind(this.showWindow, this); this.handleClick = bind(this.handleClick, this); this.watchOptions = bind(this.watchOptions, this); this.watchCoords = bind(this.watchCoords, this); this.createGWin = bind(this.createGWin, this); this.watchElement = bind(this.watchElement, this); this.watchAndDoShow = bind(this.watchAndDoShow, this); this.doShow = bind(this.doShow, this); var maybeMarker, ref, ref1, ref2, ref3; this.model = (ref = opts.model) != null ? ref : {}, this.scope = opts.scope, this.opts = opts.opts, this.isIconVisibleOnClick = opts.isIconVisibleOnClick, this.gMap = opts.gMap, this.markerScope = opts.markerScope, this.element = opts.element, this.needToManualDestroy = (ref1 = opts.needToManualDestroy) != null ? ref1 : false, this.markerIsVisibleAfterWindowClose = (ref2 = opts.markerIsVisibleAfterWindowClose) != null ? ref2 : true, this.isScopeModel = (ref3 = opts.isScopeModel) != null ? ref3 : false; if (this.isScopeModel) { this.clonedModel = _.clone(this.model, true); } this.getGmarker = function() { var ref4, ref5; if (((ref4 = this.markerScope) != null ? ref4['getGMarker'] : void 0) != null) { return (ref5 = this.markerScope) != null ? ref5.getGMarker() : void 0; } }; this.listeners = []; this.createGWin(); maybeMarker = this.getGmarker(); if (maybeMarker != null) { maybeMarker.setClickable(true); } this.watchElement(); this.watchOptions(); this.watchCoords(); this.watchAndDoShow(); this.scope.$on('$destroy', (function(_this) { return function() { return _this.destroy(); }; })(this)); $log.info(this); } WindowChildModel.prototype.doShow = function(wasOpen) { if (this.scope.show === true || wasOpen) { return this.showWindow(); } else { return this.hideWindow(); } }; WindowChildModel.prototype.watchAndDoShow = function() { if (this.model.show != null) { this.scope.show = this.model.show; } this.scope.$watch('show', this.doShow, true); return this.doShow(); }; WindowChildModel.prototype.watchElement = function() { return this.scope.$watch((function(_this) { return function() { var ref, wasOpen; if (!(_this.element || _this.html)) { return; } if (_this.html !== _this.element.html() && _this.gObject) { if ((ref = _this.opts) != null) { ref.content = void 0; } wasOpen = _this.gObject.isOpen(); _this.remove(); return _this.createGWin(wasOpen); } }; })(this)); }; WindowChildModel.prototype.createGWin = function(isOpen) { var _opts, defaults, maybeMarker, ref, ref1; if (isOpen == null) { isOpen = false; } maybeMarker = this.getGmarker(); defaults = {}; if (this.opts != null) { if (this.scope.coords) { this.opts.position = this.getCoords(this.scope.coords); } defaults = this.opts; } if (this.element) { this.html = _.isObject(this.element) ? this.element.html() : this.element; } _opts = this.scope.options ? this.scope.options : defaults; this.opts = this.createWindowOptions(maybeMarker, this.markerScope || this.scope, this.html, _opts); if (this.opts != null) { if (!this.gObject) { if (this.opts.boxClass && (window.InfoBox && typeof window.InfoBox === 'function')) { this.gObject = new window.InfoBox(this.opts); } else { this.gObject = new google.maps.InfoWindow(this.opts); } this.listeners.push(google.maps.event.addListener(this.gObject, 'domready', function() { return ChromeFixes.maybeRepaint(this.content); })); this.listeners.push(google.maps.event.addListener(this.gObject, 'closeclick', (function(_this) { return function() { if (maybeMarker) { maybeMarker.setAnimation(_this.oldMarkerAnimation); if (_this.markerIsVisibleAfterWindowClose) { _.delay(function() { maybeMarker.setVisible(false); return maybeMarker.setVisible(_this.markerIsVisibleAfterWindowClose); }, 250); } } _this.gObject.close(); _this.model.show = false; if (_this.scope.closeClick != null) { return _this.scope.$evalAsync(_this.scope.closeClick()); } else { return _this.scope.$evalAsync(); } }; })(this))); } this.gObject.setContent(this.opts.content); this.handleClick(((ref = this.scope) != null ? (ref1 = ref.options) != null ? ref1.forceClick : void 0 : void 0) || isOpen); return this.doShow(this.gObject.isOpen()); } }; WindowChildModel.prototype.watchCoords = function() { var scope; scope = this.markerScope != null ? this.markerScope : this.scope; return scope.$watch('coords', (function(_this) { return function(newValue, oldValue) { var pos; if (newValue !== oldValue) { if (newValue == null) { _this.hideWindow(); } else if (!_this.validateCoords(newValue)) { $log.error("WindowChildMarker cannot render marker as scope.coords as no position on marker: " + (JSON.stringify(_this.model))); return; } pos = _this.getCoords(newValue); _this.doShow(); _this.gObject.setPosition(pos); if (_this.opts) { return _this.opts.position = pos; } } }; })(this), true); }; WindowChildModel.prototype.watchOptions = function() { return this.scope.$watch('options', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { _this.opts = newValue; if (_this.gObject != null) { _this.gObject.setOptions(_this.opts); if ((_this.opts.visible != null) && _this.opts.visible) { return _this.showWindow(); } else if (_this.opts.visible != null) { return _this.hideWindow(); } } } }; })(this), true); }; WindowChildModel.prototype.handleClick = function(forceClick) { var click, maybeMarker; if (this.gObject == null) { return; } maybeMarker = this.getGmarker(); click = (function(_this) { return function() { if (_this.gObject == null) { _this.createGWin(); } _this.showWindow(); if (maybeMarker != null) { _this.initialMarkerVisibility = maybeMarker.getVisible(); _this.oldMarkerAnimation = maybeMarker.getAnimation(); return maybeMarker.setVisible(_this.isIconVisibleOnClick); } }; })(this); if (forceClick) { click(); } if (maybeMarker) { return this.listeners = this.listeners.concat(this.setEvents(maybeMarker, { events: { click: click } }, this.model)); } }; WindowChildModel.prototype.showWindow = function() { var compiled, show, templateScope; if (this.gObject == null) { return; } templateScope = null; show = (function(_this) { return function() { var isOpen, maybeMarker, pos; if (!_this.gObject.isOpen()) { maybeMarker = _this.getGmarker(); if ((_this.gObject != null) && (_this.gObject.getPosition != null)) { pos = _this.gObject.getPosition(); } if (maybeMarker) { pos = maybeMarker.getPosition(); } if (!pos) { return; } _this.gObject.open(_this.gMap, maybeMarker); isOpen = _this.gObject.isOpen(); if (_this.model.show !== isOpen) { return _this.model.show = isOpen; } } }; })(this); if (this.scope.templateUrl) { $http.get(this.scope.templateUrl, { cache: $templateCache }).then((function(_this) { return function(content) { var compiled; templateScope = _this.scope.$new(); if (angular.isDefined(_this.scope.templateParameter)) { templateScope.parameter = _this.scope.templateParameter; } compiled = $compile(content.data)(templateScope); _this.gObject.setContent(compiled[0]); return show(); }; })(this)); } else if (this.scope.template) { templateScope = this.scope.$new(); if (angular.isDefined(this.scope.templateParameter)) { templateScope.parameter = this.scope.templateParameter; } compiled = $compile(this.scope.template)(templateScope); this.gObject.setContent(compiled[0]); show(); } else { show(); } return this.scope.$on('destroy', function() { return templateScope.$destroy(); }); }; WindowChildModel.prototype.hideWindow = function() { if ((this.gObject != null) && this.gObject.isOpen()) { return this.gObject.close(); } }; WindowChildModel.prototype.getLatestPosition = function(overridePos) { var maybeMarker; maybeMarker = this.getGmarker(); if ((this.gObject != null) && (maybeMarker != null) && !overridePos) { return this.gObject.setPosition(maybeMarker.getPosition()); } else { if (overridePos) { return this.gObject.setPosition(overridePos); } } }; WindowChildModel.prototype.remove = function() { this.hideWindow(); this.removeEvents(this.listeners); this.listeners.length = 0; delete this.gObject; return delete this.opts; }; WindowChildModel.prototype.destroy = function(manualOverride) { var ref; if (manualOverride == null) { manualOverride = false; } this.remove(); if (((this.scope != null) && !((ref = this.scope) != null ? ref.$$destroyed : void 0)) && (this.needToManualDestroy || manualOverride)) { return this.scope.$destroy(); } }; WindowChildModel.prototype.updateModel = function(model) { if (this.isScopeModel) { this.clonedModel = _.clone(model, true); } return _.extend(this.model, this.clonedModel || model); }; return WindowChildModel; })(BaseObject); return WindowChildModel; } ]); }).call(this); ; /*global _, angular */ (function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapBasePolysParentModel', [ '$timeout', 'uiGmapLogger', 'uiGmapModelKey', 'uiGmapModelsWatcher', 'uiGmapPropMap', 'uiGmap_async', 'uiGmapPromise', 'uiGmapFitHelper', function($timeout, $log, ModelKey, ModelsWatcher, PropMap, _async, uiGmapPromise, FitHelper) { return function(IPoly, PolyChildModel, gObjectName) { var BasePolysParentModel; return BasePolysParentModel = (function(superClass) { extend(BasePolysParentModel, superClass); BasePolysParentModel.include(ModelsWatcher); function BasePolysParentModel(scope, element, attrs, gMap1, defaults) { this.element = element; this.attrs = attrs; this.gMap = gMap1; this.defaults = defaults; this.maybeFit = bind(this.maybeFit, this); this.createChild = bind(this.createChild, this); this.pieceMeal = bind(this.pieceMeal, this); this.createAllNew = bind(this.createAllNew, this); this.watchIdKey = bind(this.watchIdKey, this); this.createChildScopes = bind(this.createChildScopes, this); this.watchDestroy = bind(this.watchDestroy, this); this.onDestroy = bind(this.onDestroy, this); this.rebuildAll = bind(this.rebuildAll, this); this.doINeedToWipe = bind(this.doINeedToWipe, this); this.watchModels = bind(this.watchModels, this); BasePolysParentModel.__super__.constructor.call(this, scope); this["interface"] = IPoly; this.$log = $log; this.plurals = new PropMap(); _.each(IPoly.scopeKeys, (function(_this) { return function(name) { return _this[name + 'Key'] = void 0; }; })(this)); this.models = void 0; this.firstTime = true; this.$log.info(this); this.createChildScopes(); } BasePolysParentModel.prototype.watchModels = function(scope) { /* This was watchCollection but not all model changes were being caught. TODO: Make the directive flexible in overriding whether we watch models (and depth) via watch or watchColleciton. */ return scope.$watch('models', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { if (_this.doINeedToWipe(newValue) || scope.doRebuildAll) { return _this.rebuildAll(scope, true, true); } else { return _this.createChildScopes(false); } } }; })(this), true); }; BasePolysParentModel.prototype.doINeedToWipe = function(newValue) { var newValueIsEmpty; newValueIsEmpty = newValue != null ? newValue.length === 0 : true; return this.plurals.length > 0 && newValueIsEmpty; }; BasePolysParentModel.prototype.rebuildAll = function(scope, doCreate, doDelete) { return this.onDestroy(doDelete).then((function(_this) { return function() { if (doCreate) { return _this.createChildScopes(); } }; })(this)); }; BasePolysParentModel.prototype.onDestroy = function() { BasePolysParentModel.__super__.onDestroy.call(this, this.scope); return _async.promiseLock(this, uiGmapPromise.promiseTypes["delete"], void 0, void 0, (function(_this) { return function() { return _async.each(_this.plurals.values(), function(child) { return child.destroy(true); }, _async.chunkSizeFrom(_this.scope.cleanchunk, false)).then(function() { var ref; return (ref = _this.plurals) != null ? ref.removeAll() : void 0; }); }; })(this)); }; BasePolysParentModel.prototype.watchDestroy = function(scope) { return scope.$on('$destroy', (function(_this) { return function() { return _this.rebuildAll(scope, false, true); }; })(this)); }; BasePolysParentModel.prototype.createChildScopes = function(isCreatingFromScratch) { if (isCreatingFromScratch == null) { isCreatingFromScratch = true; } if (angular.isUndefined(this.scope.models)) { this.$log.error("No models to create " + gObjectName + "s from! I Need direct models!"); return; } if ((this.gMap == null) || (this.scope.models == null)) { return; } this.watchIdKey(this.scope); if (isCreatingFromScratch) { return this.createAllNew(this.scope, false); } else { return this.pieceMeal(this.scope, false); } }; BasePolysParentModel.prototype.watchIdKey = function(scope) { this.setIdKey(scope); return scope.$watch('idKey', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue && (newValue == null)) { _this.idKey = newValue; return _this.rebuildAll(scope, true, true); } }; })(this)); }; BasePolysParentModel.prototype.createAllNew = function(scope, isArray) { var maybeCanceled; if (isArray == null) { isArray = false; } this.models = scope.models; if (this.firstTime) { this.watchModels(scope); this.watchDestroy(scope); } if (this.didQueueInitPromise(this, scope)) { return; } maybeCanceled = null; return _async.promiseLock(this, uiGmapPromise.promiseTypes.create, 'createAllNew', (function(canceledMsg) { return maybeCanceled = canceledMsg; }), (function(_this) { return function() { return _async.map(scope.models, function(model) { var child; child = _this.createChild(model, _this.gMap); if (maybeCanceled) { $log.debug('createNew should fall through safely'); child.isEnabled = false; } maybeCanceled; return child.pathPoints.getArray(); }, _async.chunkSizeFrom(scope.chunk)).then(function(pathPoints) { _this.maybeFit(pathPoints); return _this.firstTime = false; }); }; })(this)); }; BasePolysParentModel.prototype.pieceMeal = function(scope, isArray) { var maybeCanceled, payload; if (isArray == null) { isArray = true; } if (scope.$$destroyed) { return; } maybeCanceled = null; payload = null; this.models = scope.models; if ((scope != null) && this.modelsLength() && this.plurals.length) { return _async.promiseLock(this, uiGmapPromise.promiseTypes.update, 'pieceMeal', (function(canceledMsg) { return maybeCanceled = canceledMsg; }), (function(_this) { return function() { return uiGmapPromise.promise(function() { return _this.figureOutState(_this.idKey, scope, _this.plurals, _this.modelKeyComparison); }).then(function(state) { payload = state; if (payload.updates.length) { _async.each(payload.updates, function(obj) { _.extend(obj.child.scope, obj.model); return obj.child.model = obj.model; }); } return _async.each(payload.removals, function(child) { if (child != null) { child.destroy(); _this.plurals.remove(child.model[_this.idKey]); return maybeCanceled; } }, _async.chunkSizeFrom(scope.chunk)); }).then(function() { return _async.each(payload.adds, function(modelToAdd) { if (maybeCanceled) { $log.debug('pieceMeal should fall through safely'); } _this.createChild(modelToAdd, _this.gMap); return maybeCanceled; }, _async.chunkSizeFrom(scope.chunk)).then(function() { return _this.maybeFit(); }); }); }; })(this)); } else { this.inProgress = false; return this.rebuildAll(this.scope, true, true); } }; BasePolysParentModel.prototype.createChild = function(model, gMap) { var child, childScope; childScope = this.scope.$new(false); this.setChildScope(IPoly.scopeKeys, childScope, model); childScope.$watch('model', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.setChildScope(IPoly.scopeKeys, childScope, newValue); } }; })(this), true); childScope["static"] = this.scope["static"]; child = new PolyChildModel({ isScopeModel: true, scope: childScope, attrs: this.attrs, gMap: gMap, defaults: this.defaults, model: model, gObjectChangeCb: (function(_this) { return function() { return _this.maybeFit(); }; })(this) }); if (model[this.idKey] == null) { this.$log.error(gObjectName + " model has no id to assign a child to.\nThis is required for performance. Please assign id,\nor redirect id to a different key."); return; } this.plurals.put(model[this.idKey], child); return child; }; BasePolysParentModel.prototype.maybeFit = function(pathPoints) { if (pathPoints == null) { pathPoints = this.plurals.map(function(p) { return p.pathPoints; }); } if (this.scope.fit) { pathPoints = _.flatten(pathPoints); return FitHelper.fit(pathPoints, this.gMap); } }; return BasePolysParentModel; })(ModelKey); }; } ]); }).call(this); ; /*globals angular, _, google */ (function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapCircleParentModel', [ 'uiGmapLogger', '$timeout', 'uiGmapGmapUtil', 'uiGmapEventsHelper', 'uiGmapCircleOptionsBuilder', function($log, $timeout, GmapUtil, EventsHelper, Builder) { var CircleParentModel, _settingFromDirective; _settingFromDirective = function(scope, fn) { scope.settingFromDirective = true; fn(); return $timeout(function() { return scope.settingFromDirective = false; }); }; return CircleParentModel = (function(superClass) { extend(CircleParentModel, superClass); CircleParentModel.include(GmapUtil); CircleParentModel.include(EventsHelper); function CircleParentModel(scope, element, attrs, gMap, DEFAULTS) { var clean, gObject, lastRadius; this.attrs = attrs; this.gMap = gMap; this.DEFAULTS = DEFAULTS; this.scope = scope; lastRadius = null; clean = (function(_this) { return function() { lastRadius = null; if (_this.listeners != null) { _this.removeEvents(_this.listeners); return _this.listeners = void 0; } }; })(this); gObject = new google.maps.Circle(this.buildOpts(GmapUtil.getCoords(scope.center), scope.radius)); this.setMyOptions = (function(_this) { return function(newVals, oldVals) { if (scope.settingFromDirective) { return; } if (!(_.isEqual(newVals, oldVals) && newVals === oldVals && ((newVals != null) && (oldVals != null) ? newVals.coordinates === oldVals.coordinates : true))) { return gObject.setOptions(_this.buildOpts(GmapUtil.getCoords(scope.center), scope.radius)); } }; })(this); this.props = this.props.concat([ { prop: 'center', isColl: true }, { prop: 'fill', isColl: true }, 'radius', 'zIndex' ]); this.watchProps(); if (this.scope.control != null) { this.scope.control.getCircle = function() { return gObject; }; } clean(); this.listeners = this.setEvents(gObject, scope, scope, ['radius_changed']) || []; this.listeners.push(google.maps.event.addListener(gObject, 'radius_changed', function() { /* possible google bug, and or because a circle has two radii radius_changed appears to fire twice (original and new) which is not too helpful therefore we will check for radius changes manually and bail out if nothing has changed */ var newRadius, work; newRadius = gObject.getRadius(); if (newRadius === lastRadius) { return; } lastRadius = newRadius; work = function() { return _settingFromDirective(scope, function() { var ref, ref1; if (newRadius !== scope.radius) { scope.radius = newRadius; } if (((ref = scope.events) != null ? ref.radius_changed : void 0) && _.isFunction((ref1 = scope.events) != null ? ref1.radius_changed : void 0)) { return scope.events.radius_changed(gObject, 'radius_changed', scope, arguments); } }); }; if (!angular.mock) { return scope.$evalAsync(function() { return work(); }); } else { return work(); } })); this.listeners.push(google.maps.event.addListener(gObject, 'center_changed', function() { return scope.$evalAsync(function() { return _settingFromDirective(scope, function() { if (angular.isDefined(scope.center.type)) { scope.center.coordinates[1] = gObject.getCenter().lat(); return scope.center.coordinates[0] = gObject.getCenter().lng(); } else { scope.center.latitude = gObject.getCenter().lat(); return scope.center.longitude = gObject.getCenter().lng(); } }); }); })); scope.$on('$destroy', function() { clean(); return gObject.setMap(null); }); $log.info(this); } return CircleParentModel; })(Builder); } ]); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapDrawingManagerParentModel', [ 'uiGmapLogger', '$timeout', 'uiGmapBaseObject', 'uiGmapEventsHelper', function($log, $timeout, BaseObject, EventsHelper) { var DrawingManagerParentModel; return DrawingManagerParentModel = (function(superClass) { extend(DrawingManagerParentModel, superClass); DrawingManagerParentModel.include(EventsHelper); function DrawingManagerParentModel(scope, element, attrs, map) { var gObject, listeners; this.scope = scope; this.attrs = attrs; this.map = map; gObject = new google.maps.drawing.DrawingManager(this.scope.options); gObject.setMap(this.map); listeners = void 0; if (this.scope.control != null) { this.scope.control.getDrawingManager = function() { return gObject; }; } if (!this.scope["static"] && this.scope.options) { this.scope.$watch('options', function(newValue) { return gObject != null ? gObject.setOptions(newValue) : void 0; }, true); } if (this.scope.events != null) { listeners = this.setEvents(gObject, this.scope, this.scope); this.scope.$watch('events', (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { if (listeners != null) { _this.removeEvents(listeners); } return listeners = _this.setEvents(gObject, _this.scope, _this.scope); } }; })(this)); } this.scope.$on('$destroy', (function(_this) { return function() { if (listeners != null) { _this.removeEvents(listeners); } gObject.setMap(null); return gObject = null; }; })(this)); } return DrawingManagerParentModel; })(BaseObject); } ]); }).call(this); ; /* - interface for all markers to derrive from - to enforce a minimum set of requirements - attributes - coords - icon - implementation needed on watches */ (function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module("uiGmapgoogle-maps.directives.api.models.parent").factory("uiGmapIMarkerParentModel", [ "uiGmapModelKey", "uiGmapLogger", function(ModelKey, Logger) { var IMarkerParentModel; IMarkerParentModel = (function(superClass) { extend(IMarkerParentModel, superClass); IMarkerParentModel.prototype.DEFAULTS = {}; function IMarkerParentModel(scope1, element, attrs, map) { this.scope = scope1; this.element = element; this.attrs = attrs; this.map = map; this.onWatch = bind(this.onWatch, this); this.watch = bind(this.watch, this); this.validateScope = bind(this.validateScope, this); IMarkerParentModel.__super__.constructor.call(this, this.scope); this.$log = Logger; if (!this.validateScope(this.scope)) { throw new String("Unable to construct IMarkerParentModel due to invalid scope"); } this.doClick = angular.isDefined(this.attrs.click); if (this.scope.options != null) { this.DEFAULTS = this.scope.options; } this.watch('coords', this.scope); this.watch('icon', this.scope); this.watch('options', this.scope); this.scope.$on("$destroy", (function(_this) { return function() { return _this.onDestroy(_this.scope); }; })(this)); } IMarkerParentModel.prototype.validateScope = function(scope) { var ret; if (scope == null) { this.$log.error(this.constructor.name + ": invalid scope used"); return false; } ret = scope.coords != null; if (!ret) { this.$log.error(this.constructor.name + ": no valid coords attribute found"); return false; } return ret; }; IMarkerParentModel.prototype.watch = function(propNameToWatch, scope, equalityCheck) { if (equalityCheck == null) { equalityCheck = true; } return scope.$watch(propNameToWatch, (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { return _this.onWatch(propNameToWatch, scope, newValue, oldValue); } }; })(this), equalityCheck); }; IMarkerParentModel.prototype.onWatch = function(propNameToWatch, scope, newValue, oldValue) {}; return IMarkerParentModel; })(ModelKey); return IMarkerParentModel; } ]); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module("uiGmapgoogle-maps.directives.api.models.parent").factory("uiGmapIWindowParentModel", [ "uiGmapModelKey", "uiGmapGmapUtil", "uiGmapLogger", function(ModelKey, GmapUtil, Logger) { var IWindowParentModel; return IWindowParentModel = (function(superClass) { extend(IWindowParentModel, superClass); IWindowParentModel.include(GmapUtil); function IWindowParentModel(scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache) { IWindowParentModel.__super__.constructor.call(this, scope); this.$log = Logger; this.$timeout = $timeout; this.$compile = $compile; this.$http = $http; this.$templateCache = $templateCache; this.DEFAULTS = {}; if (scope.options != null) { this.DEFAULTS = scope.options; } } IWindowParentModel.prototype.getItem = function(scope, modelsPropToIterate, index) { if (modelsPropToIterate === 'models') { return scope[modelsPropToIterate][index]; } return scope[modelsPropToIterate].get(index); }; return IWindowParentModel; })(ModelKey); } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapLayerParentModel', [ 'uiGmapBaseObject', 'uiGmapLogger', '$timeout', function(BaseObject, Logger, $timeout) { var LayerParentModel; LayerParentModel = (function(superClass) { extend(LayerParentModel, superClass); function LayerParentModel(scope, element, attrs, gMap, onLayerCreated, $log) { this.scope = scope; this.element = element; this.attrs = attrs; this.gMap = gMap; this.onLayerCreated = onLayerCreated != null ? onLayerCreated : void 0; this.$log = $log != null ? $log : Logger; this.createGoogleLayer = bind(this.createGoogleLayer, this); if (this.attrs.type == null) { this.$log.info('type attribute for the layer directive is mandatory. Layer creation aborted!!'); return; } this.createGoogleLayer(); this.doShow = true; if (angular.isDefined(this.attrs.show)) { this.doShow = this.scope.show; } if (this.doShow && (this.gMap != null)) { this.gObject.setMap(this.gMap); } this.scope.$watch('show', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { _this.doShow = newValue; if (newValue) { return _this.gObject.setMap(_this.gMap); } else { return _this.gObject.setMap(null); } } }; })(this), true); this.scope.$watch('options', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue && _this.doShow) { return _this.gObject.setOptions(newValue); } }; })(this), true); this.scope.$on('$destroy', (function(_this) { return function() { return _this.gObject.setMap(null); }; })(this)); } LayerParentModel.prototype.createGoogleLayer = function() { var base; if (this.attrs.options == null) { this.gObject = this.attrs.namespace === void 0 ? new google.maps[this.attrs.type]() : new google.maps[this.attrs.namespace][this.attrs.type](); } else { this.gObject = this.attrs.namespace === void 0 ? new google.maps[this.attrs.type](this.scope.options) : new google.maps[this.attrs.namespace][this.attrs.type](this.scope.options); } if ((this.gObject != null) && this.doShow) { this.gObject.setMap(this.gMap); } if ((this.gObject != null) && (this.onLayerCreated != null)) { return typeof (base = this.onLayerCreated(this.scope, this.gObject)) === "function" ? base(this.gObject) : void 0; } }; return LayerParentModel; })(BaseObject); return LayerParentModel; } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapMapTypeParentModel', [ 'uiGmapBaseObject', 'uiGmapLogger', function(BaseObject, Logger) { var MapTypeParentModel; MapTypeParentModel = (function(superClass) { extend(MapTypeParentModel, superClass); function MapTypeParentModel(scope, element, attrs, gMap, $log, childModel, propMap) { var watchChildModelOptions, watchChildModelShow, watchOptions, watchShow; this.scope = scope; this.element = element; this.attrs = attrs; this.gMap = gMap; this.$log = $log != null ? $log : Logger; this.childModel = childModel; this.propMap = propMap; this.refreshShown = bind(this.refreshShown, this); this.hideOverlay = bind(this.hideOverlay, this); this.showOverlay = bind(this.showOverlay, this); this.refreshMapType = bind(this.refreshMapType, this); this.createMapType = bind(this.createMapType, this); if (this.scope.options == null) { this.$log.info('options attribute for the map-type directive is mandatory. Map type creation aborted!!'); return; } this.id = this.gMap.overlayMapTypesCount = this.gMap.overlayMapTypesCount + 1 || 0; this.doShow = true; this.createMapType(); this.refreshShown(); if (this.doShow && (this.gMap != null)) { this.showOverlay(); } watchChildModelShow = (function(_this) { return function() { return _this.childModel[_this.attrs.show]; }; })(this); watchShow = this.childModel ? watchChildModelShow : 'show'; this.scope.$watch(watchShow, (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { _this.doShow = newValue; if (newValue) { return _this.showOverlay(); } else { return _this.hideOverlay(); } } }; })(this)); watchChildModelOptions = (function(_this) { return function() { return _this.childModel[_this.attrs.options]; }; })(this); watchOptions = this.childModel ? watchChildModelOptions : 'options'; this.scope.$watchCollection(watchOptions, (function(_this) { return function(newValue, oldValue) { var different, mapTypeProps; if (!_.isEqual(newValue, oldValue)) { mapTypeProps = ['tileSize', 'maxZoom', 'minZoom', 'name', 'alt']; different = _.some(mapTypeProps, function(prop) { return !oldValue || !newValue || !_.isEqual(newValue[prop], oldValue[prop]); }); if (different) { return _this.refreshMapType(); } } }; })(this)); if (angular.isDefined(this.attrs.refresh)) { this.scope.$watch('refresh', (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { return _this.refreshMapType(); } }; })(this), true); } this.scope.$on('$destroy', (function(_this) { return function() { _this.hideOverlay(); return _this.mapType = null; }; })(this)); } MapTypeParentModel.prototype.createMapType = function() { var id, idAttr, mapType; mapType = this.childModel ? (this.attrs.options ? this.childModel[this.attrs.options] : this.childModel) : this.scope.options; if (mapType.getTile != null) { this.mapType = mapType; } else if (mapType.getTileUrl != null) { this.mapType = new google.maps.ImageMapType(mapType); } else { this.$log.info('options should provide either getTile or getTileUrl methods. Map type creation aborted!!'); return; } idAttr = this.attrs.id ? (this.childModel ? this.attrs.id : 'id') : void 0; id = idAttr ? (this.childModel ? this.childModel[idAttr] : this.scope[idAttr]) : void 0; if (id) { this.gMap.mapTypes.set(id, this.mapType); if (!angular.isDefined(this.attrs.show)) { this.doShow = false; } } this.mapType.layerId = this.id; if (this.childModel && angular.isDefined(this.scope.index)) { return this.propMap.put(this.mapType.layerId, this.scope.index); } }; MapTypeParentModel.prototype.refreshMapType = function() { this.hideOverlay(); this.mapType = null; this.createMapType(); if (this.doShow && (this.gMap != null)) { return this.showOverlay(); } }; MapTypeParentModel.prototype.showOverlay = function() { var found; if (angular.isDefined(this.scope.index)) { found = false; if (this.gMap.overlayMapTypes.getLength()) { this.gMap.overlayMapTypes.forEach((function(_this) { return function(mapType, index) { var layerIndex; if (!found) { layerIndex = _this.propMap.get(mapType.layerId.toString()); if (layerIndex > _this.scope.index || !angular.isDefined(layerIndex)) { found = true; _this.gMap.overlayMapTypes.insertAt(index, _this.mapType); } } }; })(this)); if (!found) { return this.gMap.overlayMapTypes.push(this.mapType); } } else { return this.gMap.overlayMapTypes.push(this.mapType); } } else { return this.gMap.overlayMapTypes.push(this.mapType); } }; MapTypeParentModel.prototype.hideOverlay = function() { var found; found = false; return this.gMap.overlayMapTypes.forEach((function(_this) { return function(mapType, index) { if (!found && mapType.layerId === _this.id) { found = true; _this.gMap.overlayMapTypes.removeAt(index); } }; })(this)); }; MapTypeParentModel.prototype.refreshShown = function() { return this.doShow = angular.isDefined(this.attrs.show) ? (this.childModel ? this.childModel[this.attrs.show] : this.scope.show) : true; }; return MapTypeParentModel; })(BaseObject); return MapTypeParentModel; } ]); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapMapTypesParentModel', [ 'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapMapTypeParentModel', 'uiGmapPropMap', function(BaseObject, Logger, MapTypeParentModel, PropMap) { var MapTypesParentModel; MapTypesParentModel = (function(superClass) { extend(MapTypesParentModel, superClass); function MapTypesParentModel(scope, element, attrs, gMap, $log) { var pMap; this.scope = scope; this.element = element; this.attrs = attrs; this.gMap = gMap; this.$log = $log != null ? $log : Logger; if (this.attrs.mapTypes == null) { this.$log.info('layers attribute for the map-types directive is mandatory. Map types creation aborted!!'); return; } pMap = new PropMap; this.scope.mapTypes.forEach((function(_this) { return function(l, i) { var childScope, mockAttr; mockAttr = { options: _this.scope.options, show: _this.scope.show, refresh: _this.scope.refresh }; childScope = _this.scope.$new(); childScope.index = i; new MapTypeParentModel(childScope, null, mockAttr, _this.gMap, _this.$log, l, pMap); }; })(this)); } return MapTypesParentModel; })(BaseObject); return MapTypesParentModel; } ]); }).call(this); ; /*global _:true,angular:true, */ (function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module("uiGmapgoogle-maps.directives.api.models.parent").factory("uiGmapMarkersParentModel", [ "uiGmapIMarkerParentModel", "uiGmapModelsWatcher", "uiGmapPropMap", "uiGmapMarkerChildModel", "uiGmap_async", "uiGmapClustererMarkerManager", "uiGmapMarkerManager", "$timeout", "uiGmapIMarker", "uiGmapPromise", "uiGmapGmapUtil", "uiGmapLogger", "uiGmapSpiderfierMarkerManager", function(IMarkerParentModel, ModelsWatcher, PropMap, MarkerChildModel, _async, ClustererMarkerManager, MarkerManager, $timeout, IMarker, uiGmapPromise, GmapUtil, $log, SpiderfierMarkerManager) { var MarkersParentModel, _setPlurals; _setPlurals = function(val, objToSet) { objToSet.plurals = new PropMap(); objToSet.scope.plurals = objToSet.plurals; return objToSet; }; MarkersParentModel = (function(superClass) { extend(MarkersParentModel, superClass); MarkersParentModel.include(GmapUtil); MarkersParentModel.include(ModelsWatcher); function MarkersParentModel(scope, element, attrs, map) { this.maybeExecMappedEvent = bind(this.maybeExecMappedEvent, this); this.onDestroy = bind(this.onDestroy, this); this.newChildMarker = bind(this.newChildMarker, this); this.pieceMeal = bind(this.pieceMeal, this); this.rebuildAll = bind(this.rebuildAll, this); this.createAllNew = bind(this.createAllNew, this); this.bindToTypeEvents = bind(this.bindToTypeEvents, this); this.createChildScopes = bind(this.createChildScopes, this); this.validateScope = bind(this.validateScope, this); this.onWatch = bind(this.onWatch, this); MarkersParentModel.__super__.constructor.call(this, scope, element, attrs, map); this["interface"] = IMarker; _setPlurals(new PropMap(), this); this.scope.pluralsUpdate = { updateCtr: 0 }; this.$log.info(this); this.doRebuildAll = this.scope.doRebuildAll != null ? this.scope.doRebuildAll : false; this.setIdKey(this.scope); this.scope.$watch('doRebuildAll', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.doRebuildAll = newValue; } }; })(this)); if (!this.modelsLength()) { this.modelsRendered = false; } this.scope.$watch('models', (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue) || !_this.modelsRendered) { if (newValue.length === 0 && oldValue.length === 0) { return; } _this.modelsRendered = true; return _this.onWatch('models', _this.scope, newValue, oldValue); } }; })(this), !this.isTrue(attrs.modelsbyref)); this.watch('doCluster', this.scope); this.watch('type', this.scope); this.watch('clusterOptions', this.scope); this.watch('clusterEvents', this.scope); this.watch('typeOptions', this.scope); this.watch('typeEvents', this.scope); this.watch('fit', this.scope); this.watch('idKey', this.scope); this.gManager = void 0; this.createAllNew(this.scope); } MarkersParentModel.prototype.onWatch = function(propNameToWatch, scope, newValue, oldValue) { if (propNameToWatch === "idKey" && newValue !== oldValue) { this.idKey = newValue; } if (this.doRebuildAll || (propNameToWatch === 'doCluster' || propNameToWatch === 'type')) { return this.rebuildAll(scope); } else { return this.pieceMeal(scope); } }; MarkersParentModel.prototype.validateScope = function(scope) { var modelsNotDefined; modelsNotDefined = angular.isUndefined(scope.models) || scope.models === void 0; if (modelsNotDefined) { this.$log.error(this.constructor.name + ": no valid models attribute found"); } return MarkersParentModel.__super__.validateScope.call(this, scope) || modelsNotDefined; }; /* Not used internally by this parent created for consistency for external control in the API */ MarkersParentModel.prototype.createChildScopes = function(isCreatingFromScratch) { if ((this.gMap == null) || (this.scope.models == null)) { return; } if (isCreatingFromScratch) { return this.createAllNew(this.scope, false); } else { return this.pieceMeal(this.scope, false); } }; MarkersParentModel.prototype.bindToTypeEvents = function(typeEvents, events) { var internalHandles, self; if (events == null) { events = ['click', 'mouseout', 'mouseover']; } /* You should only be binding to events that produce groups/clusters of somthing. Otherwise use the orginal event handle. For Example: Click on a cluster pushes a cluster/group obj through which has getMarkers However Spiderfy's click is for a single marker so this is not ideal for that. */ self = this; if (!this.origTypeEvents) { this.origTypeEvents = {}; _.each(events, (function(_this) { return function(eventName) { return _this.origTypeEvents[eventName] = typeEvents != null ? typeEvents[eventName] : void 0; }; })(this)); } else { angular.extend(typeEvents, this.origTypeEvents); } internalHandles = {}; _.each(events, function(eventName) { return internalHandles[eventName] = function(group) { return self.maybeExecMappedEvent(group, eventName); }; }); return angular.extend(typeEvents, internalHandles); }; MarkersParentModel.prototype.createAllNew = function(scope) { var isSpiderfied, maybeCanceled, typeEvents, typeOptions; if (this.gManager != null) { if (this.gManager instanceof SpiderfierMarkerManager) { isSpiderfied = this.gManager.isSpiderfied(); } this.gManager.clear(); delete this.gManager; } typeEvents = scope.typeEvents || scope.clusterEvents; typeOptions = scope.typeOptions || scope.clusterOptions; if (scope.doCluster || scope.type === 'cluster') { if (typeEvents != null) { this.bindToTypeEvents(typeEvents); } this.gManager = new ClustererMarkerManager(this.map, void 0, typeOptions, typeEvents); } else if (scope.type === 'spider') { if (typeEvents != null) { this.bindToTypeEvents(typeEvents, ['spiderfy', 'unspiderfy']); } this.gManager = new SpiderfierMarkerManager(this.map, void 0, typeOptions, typeEvents, this.scope); if (isSpiderfied) { this.gManager.spiderfy(); } } else { this.gManager = new MarkerManager(this.map); } if (this.didQueueInitPromise(this, scope)) { return; } maybeCanceled = null; return _async.promiseLock(this, uiGmapPromise.promiseTypes.create, 'createAllNew', (function(canceledMsg) { return maybeCanceled = canceledMsg; }), (function(_this) { return function() { return _async.each(scope.models, function(model) { _this.newChildMarker(model, scope); return maybeCanceled; }, _async.chunkSizeFrom(scope.chunk)).then(function() { _this.modelsRendered = true; if (scope.fit) { _this.gManager.fit(); } _this.gManager.draw(); return _this.scope.pluralsUpdate.updateCtr += 1; }, _async.chunkSizeFrom(scope.chunk)); }; })(this)); }; MarkersParentModel.prototype.rebuildAll = function(scope) { var ref; if (!scope.doRebuild && scope.doRebuild !== void 0) { return; } if ((ref = this.scope.plurals) != null ? ref.length : void 0) { return this.onDestroy(scope).then((function(_this) { return function() { return _this.createAllNew(scope); }; })(this)); } else { return this.createAllNew(scope); } }; MarkersParentModel.prototype.pieceMeal = function(scope) { var maybeCanceled, payload; if (scope.$$destroyed) { return; } maybeCanceled = null; payload = null; if (this.modelsLength() && this.scope.plurals.length) { return _async.promiseLock(this, uiGmapPromise.promiseTypes.update, 'pieceMeal', (function(canceledMsg) { return maybeCanceled = canceledMsg; }), (function(_this) { return function() { return uiGmapPromise.promise((function() { return _this.figureOutState(_this.idKey, scope, _this.scope.plurals, _this.modelKeyComparison); })).then(function(state) { payload = state; return _async.each(payload.removals, function(child) { if (child != null) { if (child.destroy != null) { child.destroy(); } _this.scope.plurals.remove(child.id); return maybeCanceled; } }, _async.chunkSizeFrom(scope.chunk)); }).then(function() { return _async.each(payload.adds, function(modelToAdd) { _this.newChildMarker(modelToAdd, scope); return maybeCanceled; }, _async.chunkSizeFrom(scope.chunk)); }).then(function() { return _async.each(payload.updates, function(update) { _this.updateChild(update.child, update.model); return maybeCanceled; }, _async.chunkSizeFrom(scope.chunk)); }).then(function() { if (payload.adds.length > 0 || payload.removals.length > 0 || payload.updates.length > 0) { scope.plurals = _this.scope.plurals; if (scope.fit) { _this.gManager.fit(); } _this.gManager.draw(); } return _this.scope.pluralsUpdate.updateCtr += 1; }); }; })(this)); } else { this.inProgress = false; return this.rebuildAll(scope); } }; MarkersParentModel.prototype.newChildMarker = function(model, scope) { var child, childScope, keys; if (!model) { throw 'model undefined'; } if (model[this.idKey] == null) { this.$log.error("Marker model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key."); return; } this.$log.info('child', child, 'markers', this.scope.markerModels); childScope = scope.$new(false); childScope.events = scope.events; keys = {}; IMarker.scopeKeys.forEach(function(k) { return keys[k] = scope[k]; }); child = new MarkerChildModel({ scope: childScope, model: model, keys: keys, gMap: this.map, defaults: this.DEFAULTS, doClick: this.doClick, gManager: this.gManager, doDrawSelf: false, isScopeModel: true }); this.scope.plurals.put(model[this.idKey], child); return child; }; MarkersParentModel.prototype.onDestroy = function(scope) { MarkersParentModel.__super__.onDestroy.call(this, scope); return _async.promiseLock(this, uiGmapPromise.promiseTypes["delete"], void 0, void 0, (function(_this) { return function() { return _async.each(_this.scope.plurals.values(), function(model) { if (model != null) { return model.destroy(false); } }, _async.chunkSizeFrom(_this.scope.cleanchunk, false)).then(function() { if (_this.gManager != null) { _this.gManager.destroy(); } _this.plurals.removeAll(); if (_this.plurals !== _this.scope.plurals) { console.error('plurals out of sync for MarkersParentModel'); } return _this.scope.pluralsUpdate.updateCtr += 1; }); }; })(this)); }; MarkersParentModel.prototype.maybeExecMappedEvent = function(group, fnName) { var pair, typeEvents; if (this.scope.$$destroyed) { return; } typeEvents = this.scope.typeEvents || this.scope.clusterEvents; if (_.isFunction(typeEvents != null ? typeEvents[fnName] : void 0)) { pair = this.mapTypeToPlurals(group); if (this.origTypeEvents[fnName]) { return this.origTypeEvents[fnName](pair.group, pair.mapped); } } }; MarkersParentModel.prototype.mapTypeToPlurals = function(group) { var arrayToMap, mapped, ref; if (_.isArray(group)) { arrayToMap = group; } else if (_.isFunction(group.getMarkers)) { arrayToMap = group.getMarkers(); } if (arrayToMap == null) { $log.error("Unable to map event as we cannot find the array group to map"); return; } if ((ref = this.scope.plurals.values()) != null ? ref.length : void 0) { mapped = arrayToMap.map((function(_this) { return function(g) { return _this.scope.plurals.get(g.key).model; }; })(this)); } else { mapped = []; } return { cluster: group, mapped: mapped, group: group }; }; MarkersParentModel.prototype.getItem = function(scope, modelsPropToIterate, index) { if (modelsPropToIterate === 'models') { return scope[modelsPropToIterate][index]; } return scope[modelsPropToIterate].get(index); }; return MarkersParentModel; })(IMarkerParentModel); return MarkersParentModel; } ]); }).call(this); ;(function() { ['Polygon', 'Polyline'].forEach(function(name) { return angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory("uiGmap" + name + "sParentModel", [ 'uiGmapBasePolysParentModel', "uiGmap" + name + "ChildModel", "uiGmapI" + name, function(BasePolysParentModel, ChildModel, IPoly) { return BasePolysParentModel(IPoly, ChildModel, name); } ]); }); }).call(this); ; /*globals angular, _, google */ (function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapRectangleParentModel', [ 'uiGmapLogger', 'uiGmapGmapUtil', 'uiGmapEventsHelper', 'uiGmapRectangleOptionsBuilder', function($log, GmapUtil, EventsHelper, Builder) { var RectangleParentModel; return RectangleParentModel = (function(superClass) { extend(RectangleParentModel, superClass); RectangleParentModel.include(GmapUtil); RectangleParentModel.include(EventsHelper); function RectangleParentModel(scope, element, attrs, gMap, DEFAULTS) { var bounds, clear, createBounds, dragging, fit, gObject, init, listeners, myListeners, settingBoundsFromScope, updateBounds; this.scope = scope; this.attrs = attrs; this.gMap = gMap; this.DEFAULTS = DEFAULTS; bounds = void 0; dragging = false; myListeners = []; listeners = void 0; fit = (function(_this) { return function() { if (_this.isTrue(_this.attrs.fit)) { return _this.fitMapBounds(_this.gMap, bounds); } }; })(this); createBounds = (function(_this) { return function() { var ref, ref1, ref2; if ((_this.scope.bounds != null) && (((ref = _this.scope.bounds) != null ? ref.sw : void 0) != null) && (((ref1 = _this.scope.bounds) != null ? ref1.ne : void 0) != null) && _this.validateBoundPoints(_this.scope.bounds)) { bounds = _this.convertBoundPoints(_this.scope.bounds); return $log.info("new new bounds created: " + (JSON.stringify(bounds))); } else if ((_this.scope.bounds.getNorthEast != null) && (_this.scope.bounds.getSouthWest != null)) { return bounds = _this.scope.bounds; } else { if (_this.scope.bounds != null) { return $log.error("Invalid bounds for newValue: " + (JSON.stringify((ref2 = _this.scope) != null ? ref2.bounds : void 0))); } } }; })(this); createBounds(); gObject = new google.maps.Rectangle(this.buildOpts(bounds)); $log.info("gObject (rectangle) created: " + gObject); settingBoundsFromScope = false; updateBounds = (function(_this) { return function() { var b, ne, sw; b = gObject.getBounds(); ne = b.getNorthEast(); sw = b.getSouthWest(); if (settingBoundsFromScope) { return; } return _this.scope.$evalAsync(function(s) { if ((s.bounds != null) && (s.bounds.sw != null) && (s.bounds.ne != null)) { s.bounds.ne = { latitude: ne.lat(), longitude: ne.lng() }; s.bounds.sw = { latitude: sw.lat(), longitude: sw.lng() }; } if ((s.bounds.getNorthEast != null) && (s.bounds.getSouthWest != null)) { return s.bounds = b; } }); }; })(this); init = (function(_this) { return function() { fit(); _this.removeEvents(myListeners); myListeners.push(google.maps.event.addListener(gObject, 'dragstart', function() { return dragging = true; })); myListeners.push(google.maps.event.addListener(gObject, 'dragend', function() { dragging = false; return updateBounds(); })); return myListeners.push(google.maps.event.addListener(gObject, 'bounds_changed', function() { if (dragging) { return; } return updateBounds(); })); }; })(this); clear = (function(_this) { return function() { _this.removeEvents(myListeners); if (listeners != null) { _this.removeEvents(listeners); } return gObject.setMap(null); }; })(this); if (bounds != null) { init(); } this.scope.$watch('bounds', (function(newValue, oldValue) { var isNew; if (_.isEqual(newValue, oldValue) && (bounds != null) || dragging) { return; } settingBoundsFromScope = true; if (newValue == null) { clear(); return; } if (bounds == null) { isNew = true; } else { fit(); } createBounds(); gObject.setBounds(bounds); settingBoundsFromScope = false; if (isNew && (bounds != null)) { return init(); } }), true); this.setMyOptions = (function(_this) { return function(newVals, oldVals) { if (!_.isEqual(newVals, oldVals)) { if ((bounds != null) && (newVals != null)) { return gObject.setOptions(_this.buildOpts(bounds)); } } }; })(this); this.props.push('bounds'); this.watchProps(this.props); if (this.attrs.events != null) { listeners = this.setEvents(gObject, this.scope, this.scope); this.scope.$watch('events', (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { if (listeners != null) { _this.removeEvents(listeners); } return listeners = _this.setEvents(gObject, _this.scope, _this.scope); } }; })(this)); } this.scope.$on('$destroy', function() { return clear(); }); $log.info(this); } return RectangleParentModel; })(Builder); } ]); }).call(this); ; /*global angular:true, google:true */ (function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapSearchBoxParentModel', [ 'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapEventsHelper', function(BaseObject, Logger, EventsHelper) { var SearchBoxParentModel; SearchBoxParentModel = (function(superClass) { extend(SearchBoxParentModel, superClass); SearchBoxParentModel.include(EventsHelper); function SearchBoxParentModel(scope, element, attrs, gMap, ctrlPosition, template, $log) { var controlDiv; this.scope = scope; this.element = element; this.attrs = attrs; this.gMap = gMap; this.ctrlPosition = ctrlPosition; this.template = template; this.$log = $log != null ? $log : Logger; this.setVisibility = bind(this.setVisibility, this); this.getBounds = bind(this.getBounds, this); this.setBounds = bind(this.setBounds, this); this.createSearchBox = bind(this.createSearchBox, this); this.addToParentDiv = bind(this.addToParentDiv, this); this.addAsMapControl = bind(this.addAsMapControl, this); this.init = bind(this.init, this); if (this.attrs.template == null) { this.$log.error('template attribute for the search-box directive is mandatory. Places Search Box creation aborted!!'); return; } if (angular.isUndefined(this.scope.options)) { this.scope.options = {}; this.scope.options.visible = true; } if (angular.isUndefined(this.scope.options.visible)) { this.scope.options.visible = true; } if (angular.isUndefined(this.scope.options.autocomplete)) { this.scope.options.autocomplete = false; } this.visible = this.scope.options.visible; this.autocomplete = this.scope.options.autocomplete; controlDiv = angular.element('<div></div>'); controlDiv.append(this.template); this.input = controlDiv.find('input')[0]; this.init(); } SearchBoxParentModel.prototype.init = function() { this.createSearchBox(); this.scope.$watch('options', (function(_this) { return function(newValue, oldValue) { if (angular.isObject(newValue)) { if (newValue.bounds != null) { _this.setBounds(newValue.bounds); } if (newValue.visible != null) { if (_this.visible !== newValue.visible) { return _this.setVisibility(newValue.visible); } } } }; })(this), true); if (this.attrs.parentdiv != null) { this.addToParentDiv(); } else { this.addAsMapControl(); } if (!this.visible) { this.setVisibility(this.visible); } if (this.autocomplete) { this.listener = google.maps.event.addListener(this.gObject, 'place_changed', (function(_this) { return function() { return _this.places = _this.gObject.getPlace(); }; })(this)); } else { this.listener = google.maps.event.addListener(this.gObject, 'places_changed', (function(_this) { return function() { return _this.places = _this.gObject.getPlaces(); }; })(this)); } this.listeners = this.setEvents(this.gObject, this.scope, this.scope); this.$log.info(this); this.scope.$on('$stateChangeSuccess', (function(_this) { return function() { if (_this.attrs.parentdiv != null) { return _this.addToParentDiv(); } }; })(this)); return this.scope.$on('$destroy', (function(_this) { return function() { return _this.gObject = null; }; })(this)); }; SearchBoxParentModel.prototype.addAsMapControl = function() { return this.gMap.controls[google.maps.ControlPosition[this.ctrlPosition]].push(this.input); }; SearchBoxParentModel.prototype.addToParentDiv = function() { var ref; this.parentDiv = angular.element(document.getElementById(this.scope.parentdiv)); if ((ref = this.parentDiv) != null ? ref.length : void 0) { return this.parentDiv.append(this.input); } }; SearchBoxParentModel.prototype.createSearchBox = function() { if (this.autocomplete) { return this.gObject = new google.maps.places.Autocomplete(this.input, this.scope.options); } else { return this.gObject = new google.maps.places.SearchBox(this.input, this.scope.options); } }; SearchBoxParentModel.prototype.setBounds = function(bounds) { if (angular.isUndefined(bounds.isEmpty)) { this.$log.error('Error: SearchBoxParentModel setBounds. Bounds not an instance of LatLngBounds.'); } else { if (bounds.isEmpty() === false) { if (this.gObject != null) { return this.gObject.setBounds(bounds); } } } }; SearchBoxParentModel.prototype.getBounds = function() { return this.gObject.getBounds(); }; SearchBoxParentModel.prototype.setVisibility = function(val) { if (this.attrs.parentdiv != null) { if (val === false) { this.parentDiv.addClass("ng-hide"); } else { this.parentDiv.removeClass("ng-hide"); } } else { if (val === false) { this.gMap.controls[google.maps.ControlPosition[this.ctrlPosition]].clear(); } else { this.gMap.controls[google.maps.ControlPosition[this.ctrlPosition]].push(this.input); } } return this.visible = val; }; return SearchBoxParentModel; })(BaseObject); return SearchBoxParentModel; } ]); }).call(this); ; /*global _,angular */ /* WindowsChildModel generator where there are many ChildModels to a parent. */ (function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapWindowsParentModel', [ 'uiGmapIWindowParentModel', 'uiGmapModelsWatcher', 'uiGmapPropMap', 'uiGmapWindowChildModel', 'uiGmapLinked', 'uiGmap_async', 'uiGmapLogger', '$timeout', '$compile', '$http', '$templateCache', '$interpolate', 'uiGmapPromise', 'uiGmapIWindow', 'uiGmapGmapUtil', function(IWindowParentModel, ModelsWatcher, PropMap, WindowChildModel, Linked, _async, $log, $timeout, $compile, $http, $templateCache, $interpolate, uiGmapPromise, IWindow, GmapUtil) { var WindowsParentModel; WindowsParentModel = (function(superClass) { extend(WindowsParentModel, superClass); WindowsParentModel.include(ModelsWatcher); function WindowsParentModel(scope, element, attrs, ctrls, gMap1, markersScope) { this.gMap = gMap1; this.markersScope = markersScope; this.modelKeyComparison = bind(this.modelKeyComparison, this); this.interpolateContent = bind(this.interpolateContent, this); this.setChildScope = bind(this.setChildScope, this); this.createWindow = bind(this.createWindow, this); this.setContentKeys = bind(this.setContentKeys, this); this.pieceMeal = bind(this.pieceMeal, this); this.createAllNew = bind(this.createAllNew, this); this.watchIdKey = bind(this.watchIdKey, this); this.createChildScopes = bind(this.createChildScopes, this); this.watchOurScope = bind(this.watchOurScope, this); this.watchDestroy = bind(this.watchDestroy, this); this.onDestroy = bind(this.onDestroy, this); this.rebuildAll = bind(this.rebuildAll, this); this.doINeedToWipe = bind(this.doINeedToWipe, this); this.watchModels = bind(this.watchModels, this); this.go = bind(this.go, this); WindowsParentModel.__super__.constructor.call(this, scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache); this["interface"] = IWindow; this.plurals = new PropMap(); _.each(IWindow.scopeKeys, (function(_this) { return function(name) { return _this[name + 'Key'] = void 0; }; })(this)); this.linked = new Linked(scope, element, attrs, ctrls); this.contentKeys = void 0; this.isIconVisibleOnClick = void 0; this.firstTime = true; this.firstWatchModels = true; this.$log.info(self); this.parentScope = void 0; this.go(scope); } WindowsParentModel.prototype.go = function(scope) { this.watchOurScope(scope); this.doRebuildAll = this.scope.doRebuildAll != null ? this.scope.doRebuildAll : false; scope.$watch('doRebuildAll', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.doRebuildAll = newValue; } }; })(this)); return this.createChildScopes(); }; WindowsParentModel.prototype.watchModels = function(scope) { var itemToWatch; itemToWatch = this.markersScope != null ? 'pluralsUpdate' : 'models'; return scope.$watch(itemToWatch, (function(_this) { return function(newValue, oldValue) { var doScratch; if (!_.isEqual(newValue, oldValue) || _this.firstWatchModels) { _this.firstWatchModels = false; if (_this.doRebuildAll || _this.doINeedToWipe(scope.models)) { return _this.rebuildAll(scope, true, true); } else { doScratch = _this.plurals.length === 0; if (_this.existingPieces != null) { return _.last(_this.existingPieces._content).then(function() { return _this.createChildScopes(doScratch); }); } else { return _this.createChildScopes(doScratch); } } } }; })(this), true); }; WindowsParentModel.prototype.doINeedToWipe = function(newValue) { var newValueIsEmpty; newValueIsEmpty = newValue != null ? newValue.length === 0 : true; return this.plurals.length > 0 && newValueIsEmpty; }; WindowsParentModel.prototype.rebuildAll = function(scope, doCreate, doDelete) { return this.onDestroy(doDelete).then((function(_this) { return function() { if (doCreate) { return _this.createChildScopes(); } }; })(this)); }; WindowsParentModel.prototype.onDestroy = function(scope) { WindowsParentModel.__super__.onDestroy.call(this, this.scope); return _async.promiseLock(this, uiGmapPromise.promiseTypes["delete"], void 0, void 0, (function(_this) { return function() { return _async.each(_this.plurals.values(), function(child) { return child.destroy(true); }, _async.chunkSizeFrom(_this.scope.cleanchunk, false)).then(function() { var ref; return (ref = _this.plurals) != null ? ref.removeAll() : void 0; }); }; })(this)); }; WindowsParentModel.prototype.watchDestroy = function(scope) { return scope.$on('$destroy', (function(_this) { return function() { _this.firstWatchModels = true; _this.firstTime = true; return _this.rebuildAll(scope, false, true); }; })(this)); }; WindowsParentModel.prototype.watchOurScope = function(scope) { return _.each(IWindow.scopeKeys, (function(_this) { return function(name) { var nameKey; nameKey = name + 'Key'; return _this[nameKey] = typeof scope[name] === 'function' ? scope[name]() : scope[name]; }; })(this)); }; WindowsParentModel.prototype.createChildScopes = function(isCreatingFromScratch) { var modelsNotDefined, ref, ref1; if (isCreatingFromScratch == null) { isCreatingFromScratch = true; } /* being that we cannot tell the difference in Key String vs. a normal value string (TemplateUrl) we will assume that all scope values are string expressions either pointing to a key (propName) or using 'self' to point the model as container/object of interest. This may force redundant information into the model, but this appears to be the most flexible approach. */ this.isIconVisibleOnClick = true; if (angular.isDefined(this.linked.attrs.isiconvisibleonclick)) { this.isIconVisibleOnClick = this.linked.scope.isIconVisibleOnClick; } modelsNotDefined = angular.isUndefined(this.linked.scope.models); if (modelsNotDefined && (this.markersScope === void 0 || (((ref = this.markersScope) != null ? ref.plurals : void 0) === void 0 || ((ref1 = this.markersScope) != null ? ref1.models : void 0) === void 0))) { this.$log.error('No models to create windows from! Need direct models or models derived from markers!'); return; } if (this.gMap != null) { if (this.linked.scope.models != null) { this.watchIdKey(this.linked.scope); if (isCreatingFromScratch) { return this.createAllNew(this.linked.scope, false); } else { return this.pieceMeal(this.linked.scope, false); } } else { this.parentScope = this.markersScope; this.watchIdKey(this.parentScope); if (isCreatingFromScratch) { return this.createAllNew(this.markersScope, true, 'plurals', false); } else { return this.pieceMeal(this.markersScope, true, 'plurals', false); } } } }; WindowsParentModel.prototype.watchIdKey = function(scope) { this.setIdKey(scope); return scope.$watch('idKey', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue && (newValue == null)) { _this.idKey = newValue; return _this.rebuildAll(scope, true, true); } }; })(this)); }; WindowsParentModel.prototype.createAllNew = function(scope, hasGMarker, modelsPropToIterate, isArray) { var maybeCanceled; if (modelsPropToIterate == null) { modelsPropToIterate = 'models'; } if (isArray == null) { isArray = false; } if (this.firstTime) { this.watchModels(scope); this.watchDestroy(scope); } this.setContentKeys(scope.models); if (this.didQueueInitPromise(this, scope)) { return; } maybeCanceled = null; return _async.promiseLock(this, uiGmapPromise.promiseTypes.create, 'createAllNew', (function(canceledMsg) { return maybeCanceled = canceledMsg; }), (function(_this) { return function() { return _async.each(scope.models, function(model) { var gMarker, ref; gMarker = hasGMarker ? (ref = _this.getItem(scope, modelsPropToIterate, model[_this.idKey])) != null ? ref.gObject : void 0 : void 0; if (!maybeCanceled) { if (!gMarker && _this.markersScope) { $log.error('Unable to get gMarker from markersScope!'); } _this.createWindow(model, gMarker, _this.gMap); } return maybeCanceled; }, _async.chunkSizeFrom(scope.chunk)).then(function() { return _this.firstTime = false; }); }; })(this)); }; WindowsParentModel.prototype.pieceMeal = function(scope, hasGMarker, modelsPropToIterate, isArray) { var maybeCanceled, payload; if (modelsPropToIterate == null) { modelsPropToIterate = 'models'; } if (isArray == null) { isArray = true; } if (scope.$$destroyed) { return; } maybeCanceled = null; payload = null; if ((scope != null) && this.modelsLength() && this.plurals.length) { return _async.promiseLock(this, uiGmapPromise.promiseTypes.update, 'pieceMeal', (function(canceledMsg) { return maybeCanceled = canceledMsg; }), (function(_this) { return function() { return uiGmapPromise.promise((function() { return _this.figureOutState(_this.idKey, scope, _this.plurals, _this.modelKeyComparison); })).then(function(state) { payload = state; return _async.each(payload.removals, function(child) { if (child != null) { _this.plurals.remove(child.id); if (child.destroy != null) { child.destroy(true); } return maybeCanceled; } }, _async.chunkSizeFrom(scope.chunk)); }).then(function() { return _async.each(payload.adds, function(modelToAdd) { var gMarker, ref; gMarker = (ref = _this.getItem(scope, modelsPropToIterate, modelToAdd[_this.idKey])) != null ? ref.gObject : void 0; if (!gMarker) { throw 'Gmarker undefined'; } _this.createWindow(modelToAdd, gMarker, _this.gMap); return maybeCanceled; }); }).then(function() { return _async.each(payload.updates, function(update) { _this.updateChild(update.child, update.model); return maybeCanceled; }, _async.chunkSizeFrom(scope.chunk)); }); }; })(this)); } else { $log.debug('pieceMeal: rebuildAll'); return this.rebuildAll(this.scope, true, true); } }; WindowsParentModel.prototype.setContentKeys = function(models) { if (this.modelsLength(models)) { return this.contentKeys = Object.keys(models[0]); } }; WindowsParentModel.prototype.createWindow = function(model, gMarker, gMap) { var child, childScope, fakeElement, opts, ref, ref1; childScope = this.linked.scope.$new(false); this.setChildScope(childScope, model); childScope.$watch('model', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.setChildScope(childScope, newValue); } }; })(this), true); fakeElement = { html: (function(_this) { return function() { return _this.interpolateContent(_this.linked.element.html(), model); }; })(this) }; this.DEFAULTS = this.scopeOrModelVal(this.optionsKey, this.scope, model) || {}; opts = this.createWindowOptions(gMarker, childScope, fakeElement.html(), this.DEFAULTS); child = new WindowChildModel({ model: model, scope: childScope, opts: opts, isIconVisibleOnClick: this.isIconVisibleOnClick, gMap: gMap, markerScope: (ref = this.markersScope) != null ? (ref1 = ref.plurals.get(model[this.idKey])) != null ? ref1.scope : void 0 : void 0, element: fakeElement, needToManualDestroy: false, markerIsVisibleAfterWindowClose: true, isScopeModel: true }); if (model[this.idKey] == null) { this.$log.error('Window model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key.'); return; } this.plurals.put(model[this.idKey], child); return child; }; WindowsParentModel.prototype.setChildScope = function(childScope, model) { _.each(IWindow.scopeKeys, (function(_this) { return function(name) { var nameKey, newValue; nameKey = name + 'Key'; newValue = _this[nameKey] === 'self' ? model : model[_this[nameKey]]; if (newValue !== childScope[name]) { return childScope[name] = newValue; } }; })(this)); return childScope.model = model; }; WindowsParentModel.prototype.interpolateContent = function(content, model) { var exp, i, interpModel, key, len, ref; if (this.contentKeys === void 0 || this.contentKeys.length === 0) { return; } exp = $interpolate(content); interpModel = {}; ref = this.contentKeys; for (i = 0, len = ref.length; i < len; i++) { key = ref[i]; interpModel[key] = model[key]; } return exp(interpModel); }; WindowsParentModel.prototype.modelKeyComparison = function(model1, model2) { var isEqual, scope; scope = this.scope.coords != null ? this.scope : this.parentScope; if (scope == null) { throw 'No scope or parentScope set!'; } isEqual = GmapUtil.equalCoords(this.evalModelHandle(model1, scope.coords), this.evalModelHandle(model2, scope.coords)); if (!isEqual) { return isEqual; } isEqual = _.every(_.without(this["interface"].scopeKeys, 'coords'), (function(_this) { return function(k) { return _this.evalModelHandle(model1, scope[k]) === _this.evalModelHandle(model2, scope[k]); }; })(this)); return isEqual; }; return WindowsParentModel; })(IWindowParentModel); return WindowsParentModel; } ]); }).call(this); ; /*global angular, _ */ (function() { angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapCircle", [ "uiGmapICircle", "uiGmapCircleParentModel", function(ICircle, CircleParentModel) { return _.extend(ICircle, { link: function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then(function(gMap) { return new CircleParentModel(scope, element, attrs, gMap); }); } }); } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapControl", [ "uiGmapIControl", "$http", "$templateCache", "$compile", "$controller", 'uiGmapGoogleMapApi', function(IControl, $http, $templateCache, $compile, $controller, GoogleMapApi) { var Control; return Control = (function(superClass) { extend(Control, superClass); function Control() { this.link = bind(this.link, this); Control.__super__.constructor.call(this); } Control.prototype.transclude = true; Control.prototype.link = function(scope, element, attrs, ctrl, transclude) { return GoogleMapApi.then((function(_this) { return function(maps) { var hasTranscludedContent, index, position; hasTranscludedContent = angular.isUndefined(scope.template); index = angular.isDefined(scope.index && !isNaN(parseInt(scope.index))) ? parseInt(scope.index) : void 0; position = angular.isDefined(scope.position) ? scope.position.toUpperCase().replace(/-/g, '_') : 'TOP_CENTER'; if (!maps.ControlPosition[position]) { _this.$log.error('mapControl: invalid position property'); return; } return IControl.mapPromise(scope, ctrl).then(function(map) { var control, controlDiv, pushControl; control = void 0; controlDiv = angular.element('<div></div>'); pushControl = function(map, control, index) { if (index) { control[0].index = index; } return map.controls[google.maps.ControlPosition[position]].push(control[0]); }; if (hasTranscludedContent) { return transclude(function(transcludeEl) { controlDiv.append(transcludeEl); return pushControl(map, controlDiv.children(), index); }); } else { return $http.get(scope.template, { cache: $templateCache }).then(function(arg) { var data, templateCtrl, templateScope; data = arg.data; templateScope = scope.$new(); controlDiv.append(data); if (angular.isDefined(scope.controller)) { templateCtrl = $controller(scope.controller, { $scope: templateScope }); controlDiv.children().data('$ngControllerController', templateCtrl); } return control = $compile(controlDiv.children())(templateScope); })["catch"](function(error) { return _this.$log.error('mapControl: template could not be found'); }).then(function() { return pushControl(map, control, index); }); } }); }; })(this)); }; return Control; })(IControl); } ]); }).call(this); ; /*globals angular, _ */ (function() { angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapDragZoom', [ 'uiGmapCtrlHandle', 'uiGmapPropertyAction', function(CtrlHandle, PropertyAction) { return { restrict: 'EMA', transclude: true, template: '<div class="angular-google-map-dragzoom" ng-transclude style="display: none"></div>', require: '^' + 'uiGmapGoogleMap', scope: { keyboardkey: '=', options: '=', spec: '=' }, controller: [ '$scope', '$element', function($scope, $element) { $scope.ctrlType = 'uiGmapDragZoom'; return _.extend(this, CtrlHandle.handle($scope, $element)); } ], link: function(scope, element, attrs, ctrl) { return CtrlHandle.mapPromise(scope, ctrl).then(function(map) { var enableKeyDragZoom, setKeyAction, setOptionsAction; enableKeyDragZoom = function(opts) { return map.enableKeyDragZoom(opts); }; setKeyAction = new PropertyAction(function(key, newVal) { if (newVal) { return enableKeyDragZoom({ key: newVal }); } else { return enableKeyDragZoom(); } }); setOptionsAction = new PropertyAction(function(key, newVal) { if (newVal) { return enableKeyDragZoom(newVal); } }); scope.$watch('keyboardkey', setKeyAction.sic('keyboardkey')); setKeyAction.sic(scope.keyboardkey); scope.$watch('options', setOptionsAction.sic('options')); return setOptionsAction.sic(scope.options); }); } }; } ]); }).call(this); ;(function() { angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapDrawingManager", [ "uiGmapIDrawingManager", "uiGmapDrawingManagerParentModel", function(IDrawingManager, DrawingManagerParentModel) { return _.extend(IDrawingManager, { link: function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then(function(map) { return new DrawingManagerParentModel(scope, element, attrs, map); }); } }); } ]); }).call(this); ; /* - Link up Polygons to be sent back to a controller - inject the draw function into a controllers scope so that controller can call the directive to draw on demand - draw function creates the DrawFreeHandChildModel which manages itself */ (function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapApiFreeDrawPolygons', [ 'uiGmapLogger', 'uiGmapBaseObject', 'uiGmapCtrlHandle', 'uiGmapDrawFreeHandChildModel', 'uiGmapLodash', function($log, BaseObject, CtrlHandle, DrawFreeHandChildModel, uiGmapLodash) { var FreeDrawPolygons; return FreeDrawPolygons = (function(superClass) { extend(FreeDrawPolygons, superClass); function FreeDrawPolygons() { this.link = bind(this.link, this); return FreeDrawPolygons.__super__.constructor.apply(this, arguments); } FreeDrawPolygons.include(CtrlHandle); FreeDrawPolygons.prototype.restrict = 'EMA'; FreeDrawPolygons.prototype.replace = true; FreeDrawPolygons.prototype.require = '^' + 'uiGmapGoogleMap'; FreeDrawPolygons.prototype.scope = { polygons: '=', draw: '=' }; FreeDrawPolygons.prototype.link = function(scope, element, attrs, ctrl) { return this.mapPromise(scope, ctrl).then((function(_this) { return function(map) { var freeHand, listener; if (!scope.polygons) { return $log.error('No polygons to bind to!'); } if (!_.isArray(scope.polygons)) { return $log.error('Free Draw Polygons must be of type Array!'); } freeHand = new DrawFreeHandChildModel(map, ctrl.getScope()); listener = void 0; return scope.draw = function() { if (typeof listener === "function") { listener(); } return freeHand.engage(scope.polygons).then(function() { var firstTime; firstTime = true; return listener = scope.$watchCollection('polygons', function(newValue, oldValue) { var removals; if (firstTime || newValue === oldValue) { firstTime = false; return; } removals = uiGmapLodash.differenceObjects(oldValue, newValue); return removals.forEach(function(p) { return p.setMap(null); }); }); }); }; }; })(this)); }; return FreeDrawPolygons; })(BaseObject); } ]); }).call(this); ;(function() { angular.module("uiGmapgoogle-maps.directives.api").service("uiGmapICircle", [ function() { return { restrict: "EA", replace: true, require: '^' + 'uiGmapGoogleMap', scope: { center: "=center", radius: "=radius", stroke: "=stroke", fill: "=fill", clickable: "=", draggable: "=", editable: "=", geodesic: "=", icons: "=icons", visible: "=", events: "=", control: "=", zIndex: "=zindex" } }; } ]); }).call(this); ; /* - interface for all controls to derive from - to enforce a minimum set of requirements - attributes - template - position - controller - index */ (function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapIControl", [ "uiGmapBaseObject", "uiGmapLogger", "uiGmapCtrlHandle", function(BaseObject, Logger, CtrlHandle) { var IControl; return IControl = (function(superClass) { extend(IControl, superClass); IControl.extend(CtrlHandle); function IControl() { this.restrict = 'EA'; this.replace = true; this.require = '^' + 'uiGmapGoogleMap'; this.scope = { template: '@template', position: '@position', controller: '@controller', index: '@index' }; this.$log = Logger; } IControl.prototype.link = function(scope, element, attrs, ctrl) { throw new Error("Not implemented!!"); }; return IControl; })(BaseObject); } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapIDrawingManager', [ function() { return { restrict: 'EA', replace: true, require: '^' + 'uiGmapGoogleMap', scope: { "static": '@', control: '=', options: '=', events: '=' } }; } ]); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIMarker', [ 'uiGmapBaseObject', 'uiGmapCtrlHandle', function(BaseObject, CtrlHandle) { var IMarker; return IMarker = (function(superClass) { extend(IMarker, superClass); IMarker.scope = { coords: '=coords', icon: '=icon', click: '&click', options: '=options', events: '=events', fit: '=fit', idKey: '=idkey', control: '=control' }; IMarker.scopeKeys = _.keys(IMarker.scope); IMarker.keys = IMarker.scopeKeys; IMarker.extend(CtrlHandle); function IMarker() { this.restrict = 'EMA'; this.require = '^' + 'uiGmapGoogleMap'; this.priority = -1; this.transclude = true; this.replace = true; this.scope = _.extend(this.scope || {}, IMarker.scope); } return IMarker; })(BaseObject); } ]); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIPolygon', [ 'uiGmapGmapUtil', 'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapCtrlHandle', function(GmapUtil, BaseObject, Logger, CtrlHandle) { var IPolygon; return IPolygon = (function(superClass) { extend(IPolygon, superClass); IPolygon.scope = { path: '=path', stroke: '=stroke', clickable: '=', draggable: '=', editable: '=', geodesic: '=', fill: '=', icons: '=icons', visible: '=', "static": '=', events: '=', zIndex: '=zindex', fit: '=', control: '=control' }; IPolygon.scopeKeys = _.keys(IPolygon.scope); IPolygon.include(GmapUtil); IPolygon.extend(CtrlHandle); function IPolygon() {} IPolygon.prototype.restrict = 'EMA'; IPolygon.prototype.replace = true; IPolygon.prototype.require = '^' + 'uiGmapGoogleMap'; IPolygon.prototype.scope = IPolygon.scope; IPolygon.prototype.DEFAULTS = {}; IPolygon.prototype.$log = Logger; return IPolygon; })(BaseObject); } ]); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIPolyline', [ 'uiGmapGmapUtil', 'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapCtrlHandle', function(GmapUtil, BaseObject, Logger, CtrlHandle) { var IPolyline; return IPolyline = (function(superClass) { extend(IPolyline, superClass); IPolyline.scope = { path: '=', stroke: '=', clickable: '=', draggable: '=', editable: '=', geodesic: '=', icons: '=', visible: '=', "static": '=', fit: '=', events: '=', zIndex: '=zindex' }; IPolyline.scopeKeys = _.keys(IPolyline.scope); IPolyline.include(GmapUtil); IPolyline.extend(CtrlHandle); function IPolyline() {} IPolyline.prototype.restrict = 'EMA'; IPolyline.prototype.replace = true; IPolyline.prototype.require = '^' + 'uiGmapGoogleMap'; IPolyline.prototype.scope = IPolyline.scope; IPolyline.prototype.DEFAULTS = {}; IPolyline.prototype.$log = Logger; return IPolyline; })(BaseObject); } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapIRectangle', [ function() { 'use strict'; return { restrict: 'EMA', require: '^' + 'uiGmapGoogleMap', replace: true, scope: { bounds: '=', stroke: '=', clickable: '=', draggable: '=', editable: '=', fill: '=', visible: '=', events: '=' } }; } ]); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIWindow', [ 'uiGmapBaseObject', 'uiGmapChildEvents', 'uiGmapCtrlHandle', function(BaseObject, ChildEvents, CtrlHandle) { var IWindow; return IWindow = (function(superClass) { extend(IWindow, superClass); IWindow.scope = { coords: '=coords', template: '=template', templateUrl: '=templateurl', templateParameter: '=templateparameter', isIconVisibleOnClick: '=isiconvisibleonclick', closeClick: '&closeclick', options: '=options', control: '=control', show: '=show' }; IWindow.scopeKeys = _.keys(IWindow.scope); IWindow.include(ChildEvents); IWindow.extend(CtrlHandle); function IWindow() { this.restrict = 'EMA'; this.template = void 0; this.transclude = true; this.priority = -100; this.require = '^' + 'uiGmapGoogleMap'; this.replace = true; this.scope = _.extend(this.scope || {}, IWindow.scope); } return IWindow; })(BaseObject); } ]); }).call(this); ; /*globals angular,_,google */ (function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapMap', ['$timeout', '$q', '$log', 'uiGmapGmapUtil', 'uiGmapBaseObject', 'uiGmapCtrlHandle', 'uiGmapIsReady', 'uiGmapuuid', 'uiGmapExtendGWin', 'uiGmapExtendMarkerClusterer', 'uiGmapGoogleMapsUtilV3', 'uiGmapGoogleMapApi', 'uiGmapEventsHelper', 'uiGmapGoogleMapObjectManager', function($timeout, $q, $log, uiGmapGmapUtil, uiGmapBaseObject, uiGmapCtrlHandle, uiGmapIsReady, uiGmapuuid, uiGmapExtendGWin, uiGmapExtendMarkerClusterer, uiGmapGoogleMapsUtilV3, uiGmapGoogleMapApi, uiGmapEventsHelper, uiGmapGoogleMapObjectManager) { var DEFAULTS, Map, initializeItems; DEFAULTS = void 0; initializeItems = [uiGmapGoogleMapsUtilV3, uiGmapExtendGWin, uiGmapExtendMarkerClusterer]; return Map = (function(superClass) { extend(Map, superClass); Map.include(uiGmapGmapUtil); function Map() { this.link = bind(this.link, this); var ctrlFn; ctrlFn = function($scope) { var ctrlObj, retCtrl; retCtrl = void 0; $scope.$on('$destroy', function() { return uiGmapIsReady.decrement(); }); ctrlObj = uiGmapCtrlHandle.handle($scope); $scope.ctrlType = 'Map'; $scope.deferred.promise.then(function() { return initializeItems.forEach(function(i) { return i.init(); }); }); ctrlObj.getMap = function() { return $scope.map; }; retCtrl = _.extend(this, ctrlObj); return retCtrl; }; this.controller = ['$scope', ctrlFn]; } Map.prototype.restrict = 'EMA'; Map.prototype.transclude = true; Map.prototype.replace = false; Map.prototype.template = "<div class=\"angular-google-map\"><div class=\"angular-google-map-container\">\n</div><div ng-transclude style=\"display: none\"></div></div>"; Map.prototype.scope = { center: '=', zoom: '=', dragging: '=', control: '=', options: '=', events: '=', eventOpts: '=', styles: '=', bounds: '=', update: '=' }; Map.prototype.link = function(scope, element, attrs) { var listeners; listeners = []; scope.$on('$destroy', function() { uiGmapEventsHelper.removeEvents(listeners); if (attrs.recycleMapInstance === 'true' && scope.map) { uiGmapGoogleMapObjectManager.recycleMapInstance(scope.map); return scope.map = null; } }); scope.idleAndZoomChanged = false; return uiGmapGoogleMapApi.then((function(_this) { return function(maps) { var _gMap, customListeners, disabledEvents, dragging, el, eventName, getEventHandler, mapOptions, maybeHookToEvent, opts, ref, resolveSpawned, settingFromDirective, spawned, type, updateCenter, zoomPromise; DEFAULTS = { mapTypeId: maps.MapTypeId.ROADMAP }; spawned = uiGmapIsReady.spawn(); resolveSpawned = function() { return spawned.deferred.resolve({ instance: spawned.instance, map: _gMap }); }; if (!angular.isDefined(scope.center) && !angular.isDefined(scope.bounds)) { $log.error('angular-google-maps: a center or bounds property is required'); return; } if (!angular.isDefined(scope.center)) { scope.center = new google.maps.LatLngBounds(_this.getCoords(scope.bounds.southwest), _this.getCoords(scope.bounds.northeast)).getCenter(); } if (!angular.isDefined(scope.zoom)) { scope.zoom = 10; } el = angular.element(element); el.addClass('angular-google-map'); opts = { options: {} }; if (attrs.options) { opts.options = scope.options; } if (attrs.styles) { opts.styles = scope.styles; } if (attrs.type) { type = attrs.type.toUpperCase(); if (google.maps.MapTypeId.hasOwnProperty(type)) { opts.mapTypeId = google.maps.MapTypeId[attrs.type.toUpperCase()]; } else { $log.error("angular-google-maps: invalid map type '" + attrs.type + "'"); } } mapOptions = angular.extend({}, DEFAULTS, opts, { center: _this.getCoords(scope.center), zoom: scope.zoom, bounds: scope.bounds }); if (attrs.recycleMapInstance === 'true') { _gMap = uiGmapGoogleMapObjectManager.createMapInstance(el.find('div')[1], mapOptions); } else { _gMap = new google.maps.Map(el.find('div')[1], mapOptions); } _gMap['uiGmap_id'] = uiGmapuuid.generate(); dragging = false; listeners.push(google.maps.event.addListenerOnce(_gMap, 'idle', function() { scope.deferred.resolve(_gMap); return resolveSpawned(); })); disabledEvents = attrs.events && (((ref = scope.events) != null ? ref.blacklist : void 0) != null) ? scope.events.blacklist : []; if (_.isString(disabledEvents)) { disabledEvents = [disabledEvents]; } maybeHookToEvent = function(eventName, fn, prefn) { if (!_.includes(disabledEvents, eventName)) { if (prefn) { prefn(); } return listeners.push(google.maps.event.addListener(_gMap, eventName, function() { var ref1; if (!((ref1 = scope.update) != null ? ref1.lazy : void 0)) { return fn(); } })); } }; if (!_.includes(disabledEvents, 'all')) { maybeHookToEvent('dragstart', function() { dragging = true; return scope.$evalAsync(function(s) { if (s.dragging != null) { return s.dragging = dragging; } }); }); maybeHookToEvent('dragend', function() { dragging = false; return scope.$evalAsync(function(s) { if (s.dragging != null) { return s.dragging = dragging; } }); }); updateCenter = function(c, s) { var cLat, cLng; if (c == null) { c = _gMap.center; } if (s == null) { s = scope; } if (!_.includes(disabledEvents, 'center')) { cLat = c.lat(); cLng = c.lng(); if (angular.isDefined(s.center.type)) { if (s.center.coordinates[1] !== cLat) { s.center.coordinates[1] = cLat; } if (s.center.coordinates[0] !== cLng) { return s.center.coordinates[0] = cLng; } } else { if (s.center.latitude !== cLat) { s.center.latitude = cLat; } if (s.center.longitude !== cLng) { return s.center.longitude = cLng; } } } }; settingFromDirective = false; maybeHookToEvent('idle', function() { var b, ne, sw; b = _gMap.getBounds(); ne = b.getNorthEast(); sw = b.getSouthWest(); settingFromDirective = true; return scope.$evalAsync(function(s) { updateCenter(); if (!_.isUndefined(s.bounds) && !_.includes(disabledEvents, 'bounds')) { s.bounds.northeast = { latitude: ne.lat(), longitude: ne.lng() }; s.bounds.southwest = { latitude: sw.lat(), longitude: sw.lng() }; } if (!_.includes(disabledEvents, 'zoom')) { s.zoom = _gMap.zoom; scope.idleAndZoomChanged = !scope.idleAndZoomChanged; } return settingFromDirective = false; }); }); } if (angular.isDefined(scope.events) && scope.events !== null && angular.isObject(scope.events)) { getEventHandler = function(eventName) { return function() { return scope.events[eventName].apply(scope, [_gMap, eventName, arguments]); }; }; customListeners = []; for (eventName in scope.events) { if (scope.events.hasOwnProperty(eventName) && angular.isFunction(scope.events[eventName])) { customListeners.push(google.maps.event.addListener(_gMap, eventName, getEventHandler(eventName))); } } listeners.concat(customListeners); } _gMap.getOptions = function() { return mapOptions; }; scope.map = _gMap; if ((attrs.control != null) && (scope.control != null)) { scope.control.refresh = function(maybeCoords) { var coords, ref1, ref2; if (_gMap == null) { return; } if (((typeof google !== "undefined" && google !== null ? (ref1 = google.maps) != null ? (ref2 = ref1.event) != null ? ref2.trigger : void 0 : void 0 : void 0) != null) && (_gMap != null)) { google.maps.event.trigger(_gMap, 'resize'); } if (((maybeCoords != null ? maybeCoords.latitude : void 0) != null) && ((maybeCoords != null ? maybeCoords.longitude : void 0) != null)) { coords = _this.getCoords(maybeCoords); if (_this.isTrue(attrs.pan)) { return _gMap.panTo(coords); } else { return _gMap.setCenter(coords); } } }; scope.control.getGMap = function() { return _gMap; }; scope.control.getMapOptions = function() { return mapOptions; }; scope.control.getCustomEventListeners = function() { return customListeners; }; scope.control.removeEvents = function(yourListeners) { return uiGmapEventsHelper.removeEvents(yourListeners); }; } scope.$watch('center', function(newValue, oldValue) { var coords; if (newValue === oldValue || settingFromDirective) { return; } coords = _this.getCoords(scope.center); if (coords.lat() === _gMap.center.lat() && coords.lng() === _gMap.center.lng()) { return; } if (!dragging) { if (!_this.validateCoords(newValue)) { $log.error("Invalid center for newValue: " + (JSON.stringify(newValue))); } if (_this.isTrue(attrs.pan) && scope.zoom === _gMap.zoom) { return _gMap.panTo(coords); } else { return _gMap.setCenter(coords); } } }, true); zoomPromise = null; scope.$watch('zoom', function(newValue, oldValue) { var ref1, ref2; if (newValue == null) { return; } if (_.isEqual(newValue, oldValue) || (_gMap != null ? _gMap.getZoom() : void 0) === (scope != null ? scope.zoom : void 0) || settingFromDirective) { return; } if (zoomPromise != null) { $timeout.cancel(zoomPromise); } return zoomPromise = $timeout(function() { return _gMap.setZoom(newValue); }, ((ref1 = scope.eventOpts) != null ? (ref2 = ref1.debounce) != null ? ref2.zoomMs : void 0 : void 0) + 20, false); }); scope.$watch('bounds', function(newValue, oldValue) { var bounds, ne, ref1, ref2, ref3, ref4, sw; if (newValue === oldValue) { return; } if (((newValue != null ? (ref1 = newValue.northeast) != null ? ref1.latitude : void 0 : void 0) == null) || ((newValue != null ? (ref2 = newValue.northeast) != null ? ref2.longitude : void 0 : void 0) == null) || ((newValue != null ? (ref3 = newValue.southwest) != null ? ref3.latitude : void 0 : void 0) == null) || ((newValue != null ? (ref4 = newValue.southwest) != null ? ref4.longitude : void 0 : void 0) == null)) { $log.error("Invalid map bounds for new value: " + (JSON.stringify(newValue))); return; } ne = new google.maps.LatLng(newValue.northeast.latitude, newValue.northeast.longitude); sw = new google.maps.LatLng(newValue.southwest.latitude, newValue.southwest.longitude); bounds = new google.maps.LatLngBounds(sw, ne); return _gMap.fitBounds(bounds); }); return ['options', 'styles'].forEach(function(toWatch) { return scope.$watch(toWatch, function(newValue, oldValue) { if (_.isEqual(newValue, oldValue)) { return; } if (toWatch === 'options') { opts.options = newValue; } else { opts.options[toWatch] = newValue; } if (_gMap != null) { return _gMap.setOptions(opts); } }, true); }); }; })(this)); }; return Map; })(uiGmapBaseObject); }]); }).call(this); ; /*global _:true,angular:true */ (function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapMarker", [ "uiGmapIMarker", "uiGmapMarkerChildModel", "uiGmapMarkerManager", "uiGmapLogger", function(IMarker, MarkerChildModel, MarkerManager, $log) { var Marker; return Marker = (function(superClass) { extend(Marker, superClass); function Marker() { Marker.__super__.constructor.call(this); this.template = '<span class="angular-google-map-marker" ng-transclude></span>'; $log.info(this); } Marker.prototype.controller = [ '$scope', '$element', function($scope, $element) { $scope.ctrlType = 'Marker'; return _.extend(this, IMarker.handle($scope, $element)); } ]; Marker.prototype.link = function(scope, element, attrs, ctrl) { var mapPromise; mapPromise = IMarker.mapPromise(scope, ctrl); mapPromise.then(function(gMap) { var gManager, keys, m; gManager = new MarkerManager(gMap); keys = _.object(IMarker.keys, IMarker.keys); m = new MarkerChildModel({ scope: scope, model: scope, keys: keys, gMap: gMap, doClick: true, gManager: gManager, doDrawSelf: false, trackModel: false }); m.deferred.promise.then(function(gMarker) { return scope.deferred.resolve(gMarker); }); if (scope.control != null) { return scope.control.getGMarkers = gManager.getGMarkers; } }); return scope.$on('$destroy', function() { var gManager; if (typeof gManager !== "undefined" && gManager !== null) { gManager.clear(); } return gManager = null; }); }; return Marker; })(IMarker); } ]); }).call(this); ; /*global _:true,angular:true */ (function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapMarkers", [ "uiGmapIMarker", "uiGmapPlural", "uiGmapMarkersParentModel", "uiGmap_sync", "uiGmapLogger", function(IMarker, Plural, MarkersParentModel, _sync, $log) { var Markers; return Markers = (function(superClass) { extend(Markers, superClass); function Markers() { Markers.__super__.constructor.call(this); this.template = '<span class="angular-google-map-markers" ng-transclude></span>'; Plural.extend(this, { doCluster: '=?docluster', clusterOptions: '=clusteroptions', clusterEvents: '=clusterevents', modelsByRef: '=modelsbyref', type: '=?type', typeOptions: '=?typeoptions', typeEvents: '=?typeevents', deepComparison: '=?deepcomparison' }); $log.info(this); } Markers.prototype.controller = [ '$scope', '$element', function($scope, $element) { $scope.ctrlType = 'Markers'; return _.extend(this, IMarker.handle($scope, $element)); } ]; Markers.prototype.link = function(scope, element, attrs, ctrl) { var parentModel, ready; parentModel = void 0; ready = function() { return scope.deferred.resolve(); }; return IMarker.mapPromise(scope, ctrl).then(function(map) { var mapScope; mapScope = ctrl.getScope(); mapScope.$watch('idleAndZoomChanged', function() { return _.defer(parentModel.gManager.draw); }); parentModel = new MarkersParentModel(scope, element, attrs, map); Plural.link(scope, parentModel); if (scope.control != null) { scope.control.getGMarkers = function() { var ref; return (ref = parentModel.gManager) != null ? ref.getGMarkers() : void 0; }; scope.control.getChildMarkers = function() { return parentModel.plurals; }; } return _.last(parentModel.existingPieces._content).then(function() { return ready(); }); }); }; return Markers; })(IMarker); } ]); }).call(this); ; /*global angular */ (function() { angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapPlural', [ function() { var _initControl; _initControl = function(scope, parent) { if (scope.control == null) { return; } scope.control.updateModels = function(models) { scope.models = models; return parent.createChildScopes(false); }; scope.control.newModels = function(models) { scope.models = models; return parent.rebuildAll(scope, true, true); }; scope.control.clean = function() { return parent.rebuildAll(scope, false, true); }; scope.control.getPlurals = function() { return parent.plurals; }; scope.control.getManager = function() { return parent.gManager; }; scope.control.hasManager = function() { return (parent.gManager != null) === true; }; return scope.control.managerDraw = function() { var ref; if (scope.control.hasManager()) { return (ref = scope.control.getManager()) != null ? ref.draw() : void 0; } }; }; return { extend: function(obj, obj2) { return _.extend(obj.scope || {}, obj2 || {}, { idKey: '=idkey', doRebuildAll: '=dorebuildall', models: '=models', chunk: '=chunk', cleanchunk: '=cleanchunk', control: '=control', deepComparison: '=deepcomparison' }); }, link: function(scope, parent) { return _initControl(scope, parent); } }; } ]); }).call(this); ; /*global angular */ (function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolygon', [ 'uiGmapIPolygon', '$timeout', 'uiGmapPolygonChildModel', function(IPolygon, $timeout, PolygonChild) { var Polygon; return Polygon = (function(superClass) { extend(Polygon, superClass); function Polygon() { this.link = bind(this.link, this); return Polygon.__super__.constructor.apply(this, arguments); } Polygon.prototype.link = function(scope, element, attrs, mapCtrl) { var children, promise; children = []; promise = IPolygon.mapPromise(scope, mapCtrl); if (scope.control != null) { scope.control.getInstance = this; scope.control.polygons = children; scope.control.promise = promise; } return promise.then((function(_this) { return function(gMap) { return children.push(new PolygonChild({ scope: scope, attrs: attrs, gMap: gMap, defaults: _this.DEFAULTS })); }; })(this)); }; return Polygon; })(IPolygon); } ]); }).call(this); ; /*global angular:true */ (function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolygons', [ 'uiGmapIPolygon', '$timeout', 'uiGmapPolygonsParentModel', 'uiGmapPlural', function(Interface, $timeout, ParentModel, Plural) { var Polygons; return Polygons = (function(superClass) { extend(Polygons, superClass); function Polygons() { this.link = bind(this.link, this); Polygons.__super__.constructor.call(this); Plural.extend(this); this.$log.info(this); } Polygons.prototype.link = function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then((function(_this) { return function(map) { if (angular.isUndefined(scope.path) || scope.path === null) { _this.$log.warn('polygons: no valid path attribute found'); } if (!scope.models) { _this.$log.warn('polygons: no models found to create from'); } return Plural.link(scope, new ParentModel(scope, element, attrs, map, _this.DEFAULTS)); }; })(this)); }; return Polygons; })(Interface); } ]); }).call(this); ; /*global angular */ (function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolyline', [ 'uiGmapIPolyline', '$timeout', 'uiGmapPolylineChildModel', function(IPolyline, $timeout, PolylineChildModel) { var Polyline; return Polyline = (function(superClass) { extend(Polyline, superClass); function Polyline() { this.link = bind(this.link, this); return Polyline.__super__.constructor.apply(this, arguments); } Polyline.prototype.link = function(scope, element, attrs, mapCtrl) { return IPolyline.mapPromise(scope, mapCtrl).then((function(_this) { return function(gMap) { if (angular.isUndefined(scope.path) || scope.path === null || !_this.validatePath(scope.path)) { _this.$log.warn('polyline: no valid path attribute found'); } return new PolylineChildModel({ scope: scope, attrs: attrs, gMap: gMap, defaults: _this.DEFAULTS }); }; })(this)); }; return Polyline; })(IPolyline); } ]); }).call(this); ; /*global angular */ (function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolylines', [ 'uiGmapIPolyline', '$timeout', 'uiGmapPolylinesParentModel', 'uiGmapPlural', function(IPolyline, $timeout, PolylinesParentModel, Plural) { var Polylines; return Polylines = (function(superClass) { extend(Polylines, superClass); function Polylines() { this.link = bind(this.link, this); Polylines.__super__.constructor.call(this); Plural.extend(this); this.$log.info(this); } Polylines.prototype.link = function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then((function(_this) { return function(gMap) { if (angular.isUndefined(scope.path) || scope.path === null) { _this.$log.warn('polylines: no valid path attribute found'); } if (!scope.models) { _this.$log.warn('polylines: no models found to create from'); } return Plural.link(scope, new PolylinesParentModel(scope, element, attrs, gMap, _this.DEFAULTS)); }; })(this)); }; return Polylines; })(IPolyline); } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapRectangle', [ 'uiGmapLogger', 'uiGmapGmapUtil', 'uiGmapIRectangle', 'uiGmapRectangleParentModel', function($log, GmapUtil, IRectangle, RectangleParentModel) { return _.extend(IRectangle, { link: function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then(function(gMap) { return new RectangleParentModel(scope, element, attrs, gMap); }); } }); } ]); }).call(this); ; /*global angular:true */ (function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapWindow', [ 'uiGmapIWindow', 'uiGmapGmapUtil', 'uiGmapWindowChildModel', 'uiGmapLodash', 'uiGmapLogger', function(IWindow, GmapUtil, WindowChildModel, uiGmapLodash, $log) { var Window; return Window = (function(superClass) { extend(Window, superClass); Window.include(GmapUtil); function Window() { this.link = bind(this.link, this); Window.__super__.constructor.call(this); this.require = ['^' + 'uiGmapGoogleMap', '^?' + 'uiGmapMarker']; this.template = '<span class="angular-google-maps-window" ng-transclude></span>'; $log.debug(this); this.childWindows = []; } Window.prototype.link = function(scope, element, attrs, ctrls) { var markerCtrl, markerScope; markerCtrl = ctrls.length > 1 && (ctrls[1] != null) ? ctrls[1] : void 0; markerScope = markerCtrl != null ? markerCtrl.getScope() : void 0; this.mapPromise = IWindow.mapPromise(scope, ctrls[0]); return this.mapPromise.then((function(_this) { return function(gMap) { var isIconVisibleOnClick; isIconVisibleOnClick = true; if (angular.isDefined(attrs.isiconvisibleonclick)) { isIconVisibleOnClick = scope.isIconVisibleOnClick; } if (!markerCtrl) { _this.init(scope, element, isIconVisibleOnClick, gMap); return; } return markerScope.deferred.promise.then(function(gMarker) { return _this.init(scope, element, isIconVisibleOnClick, gMap, markerScope); }); }; })(this)); }; Window.prototype.init = function(scope, element, isIconVisibleOnClick, gMap, markerScope) { var childWindow, defaults, gMarker, hasScopeCoords, opts; defaults = scope.options != null ? scope.options : {}; hasScopeCoords = (scope != null) && this.validateCoords(scope.coords); if ((markerScope != null ? markerScope['getGMarker'] : void 0) != null) { gMarker = markerScope.getGMarker(); } opts = hasScopeCoords ? this.createWindowOptions(gMarker, scope, element.html(), defaults) : defaults; if (gMap != null) { childWindow = new WindowChildModel({ scope: scope, opts: opts, isIconVisibleOnClick: isIconVisibleOnClick, gMap: gMap, markerScope: markerScope, element: element }); this.childWindows.push(childWindow); scope.$on('$destroy', (function(_this) { return function() { _this.childWindows = uiGmapLodash.withoutObjects(_this.childWindows, [childWindow], function(child1, child2) { return child1.scope.$id === child2.scope.$id; }); return _this.childWindows.length = 0; }; })(this)); } if (scope.control != null) { scope.control.getGWindows = (function(_this) { return function() { return _this.childWindows.map(function(child) { return child.gObject; }); }; })(this); scope.control.getChildWindows = (function(_this) { return function() { return _this.childWindows; }; })(this); scope.control.getPlurals = scope.control.getChildWindows; scope.control.showWindow = (function(_this) { return function() { return _this.childWindows.map(function(child) { return child.showWindow(); }); }; })(this); scope.control.hideWindow = (function(_this) { return function() { return _this.childWindows.map(function(child) { return child.hideWindow(); }); }; })(this); } if ((this.onChildCreation != null) && (childWindow != null)) { return this.onChildCreation(childWindow); } }; return Window; })(IWindow); } ]); }).call(this); ; /*global angular */ (function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapWindows', [ 'uiGmapIWindow', 'uiGmapPlural', 'uiGmapWindowsParentModel', 'uiGmapPromise', 'uiGmapLogger', function(IWindow, Plural, WindowsParentModel, uiGmapPromise, $log) { /* Windows directive where many windows map to the models property */ var Windows; return Windows = (function(superClass) { extend(Windows, superClass); function Windows() { this.link = bind(this.link, this); Windows.__super__.constructor.call(this); this.require = ['^' + 'uiGmapGoogleMap', '^?' + 'uiGmapMarkers']; this.template = '<span class="angular-google-maps-windows" ng-transclude></span>'; Plural.extend(this); $log.debug(this); } Windows.prototype.link = function(scope, element, attrs, ctrls) { var mapScope, markerCtrl, markerScope; mapScope = ctrls[0].getScope(); markerCtrl = ctrls.length > 1 && (ctrls[1] != null) ? ctrls[1] : void 0; markerScope = markerCtrl != null ? markerCtrl.getScope() : void 0; return mapScope.deferred.promise.then((function(_this) { return function(map) { var promise, ref; promise = (markerScope != null ? (ref = markerScope.deferred) != null ? ref.promise : void 0 : void 0) || uiGmapPromise.resolve(); return promise.then(function() { var pieces, ref1; pieces = (ref1 = _this.parentModel) != null ? ref1.existingPieces : void 0; if (pieces) { return pieces.then(function() { return _this.init(scope, element, attrs, ctrls, map, markerScope); }); } else { return _this.init(scope, element, attrs, ctrls, map, markerScope); } }); }; })(this)); }; Windows.prototype.init = function(scope, element, attrs, ctrls, map, additionalScope) { var parentModel; parentModel = new WindowsParentModel(scope, element, attrs, ctrls, map, additionalScope); Plural.link(scope, parentModel); if (scope.control != null) { scope.control.getGWindows = function() { return parentModel.plurals.map(function(child) { return child.gObject; }); }; return scope.control.getChildWindows = function() { return parentModel.plurals; }; } }; return Windows; })(IWindow); } ]); }).call(this); ; /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready Nick Baugh - https://github.com/niftylettuce */ /*globals angular */ (function() { angular.module("uiGmapgoogle-maps").directive("uiGmapGoogleMap", ['uiGmapMap', function(uiGmapMap) { return new uiGmapMap(); }]); }).call(this); ; /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ /* Map marker directive This directive is used to create a marker on an existing map. This directive creates a new scope. {attribute coords required} object containing latitude and longitude properties {attribute icon optional} string url to image used for marker icon {attribute animate optional} if set to false, the marker won't be animated (on by default) */ (function() { angular.module('uiGmapgoogle-maps').directive('uiGmapMarker', [ '$timeout', 'uiGmapMarker', function($timeout, Marker) { return new Marker($timeout); } ]); }).call(this); ; /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ /* Map marker directive This directive is used to create a marker on an existing map. This directive creates a new scope. {attribute coords required} object containing latitude and longitude properties {attribute icon optional} string url to image used for marker icon {attribute animate optional} if set to false, the marker won't be animated (on by default) */ (function() { angular.module('uiGmapgoogle-maps').directive('uiGmapMarkers', [ '$timeout', 'uiGmapMarkers', function($timeout, Markers) { return new Markers($timeout); } ]); }).call(this); ; /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready Rick Huizinga - https://plus.google.com/+RickHuizinga */ (function() { angular.module('uiGmapgoogle-maps').directive('uiGmapPolygon', [ 'uiGmapPolygon', function(Polygon) { return new Polygon(); } ]); }).call(this); ; /* @authors Julian Popescu - https://github.com/jpopesculian Rick Huizinga - https://plus.google.com/+RickHuizinga */ (function() { angular.module('uiGmapgoogle-maps').directive("uiGmapCircle", [ "uiGmapCircle", function(Circle) { return Circle; } ]); }).call(this); ; /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ (function() { angular.module("uiGmapgoogle-maps").directive("uiGmapPolyline", [ "uiGmapPolyline", function(Polyline) { return new Polyline(); } ]); }).call(this); ; /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ (function() { angular.module('uiGmapgoogle-maps').directive('uiGmapPolylines', [ 'uiGmapPolylines', function(Polylines) { return new Polylines(); } ]); }).call(this); ; /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready Chentsu Lin - https://github.com/ChenTsuLin */ (function() { angular.module("uiGmapgoogle-maps").directive("uiGmapRectangle", [ "uiGmapLogger", "uiGmapRectangle", function($log, Rectangle) { return Rectangle; } ]); }).call(this); ; /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ /* Map info window directive This directive is used to create an info window on an existing map. This directive creates a new scope. {attribute coords required} object containing latitude and longitude properties {attribute show optional} map will show when this expression returns true */ (function() { angular.module("uiGmapgoogle-maps").directive("uiGmapWindow", [ "$timeout", "$compile", "$http", "$templateCache", "uiGmapWindow", function($timeout, $compile, $http, $templateCache, Window) { return new Window($timeout, $compile, $http, $templateCache); } ]); }).call(this); ; /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ /* Map info window directive This directive is used to create an info window on an existing map. This directive creates a new scope. {attribute coords required} object containing latitude and longitude properties {attribute show optional} map will show when this expression returns true */ (function() { angular.module("uiGmapgoogle-maps").directive("uiGmapWindows", [ "$timeout", "$compile", "$http", "$templateCache", "$interpolate", "uiGmapWindows", function($timeout, $compile, $http, $templateCache, $interpolate, Windows) { return new Windows($timeout, $compile, $http, $templateCache, $interpolate); } ]); }).call(this); ; /* @authors: - Nicolas Laplante https://plus.google.com/108189012221374960701 - Nicholas McCready - https://twitter.com/nmccready */ /* Map Layer directive This directive is used to create any type of Layer from the google maps sdk. This directive creates a new scope. {attribute show optional} true (default) shows the trafficlayer otherwise it is hidden */ (function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; angular.module('uiGmapgoogle-maps').directive('uiGmapLayer', [ '$timeout', 'uiGmapLogger', 'uiGmapLayerParentModel', function($timeout, Logger, LayerParentModel) { var Layer; Layer = (function() { function Layer() { this.link = bind(this.link, this); this.$log = Logger; this.restrict = 'EMA'; this.require = '^' + 'uiGmapGoogleMap'; this.priority = -1; this.transclude = true; this.template = '<span class=\'angular-google-map-layer\' ng-transclude></span>'; this.replace = true; this.scope = { show: '=show', type: '=type', namespace: '=namespace', options: '=options', onCreated: '&oncreated' }; } Layer.prototype.link = function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then((function(_this) { return function(map) { if (scope.onCreated != null) { return new LayerParentModel(scope, element, attrs, map, scope.onCreated); } else { return new LayerParentModel(scope, element, attrs, map); } }; })(this)); }; return Layer; })(); return new Layer(); } ]); }).call(this); ; /* @authors Adam Kreitals, [email protected] */ /* mapControl directive This directive is used to create a custom control element on an existing map. This directive creates a new scope. {attribute template required} string url of the template to be used for the control {attribute position optional} string position of the control of the form top-left or TOP_LEFT defaults to TOP_CENTER {attribute controller optional} string controller to be applied to the template {attribute index optional} number index for controlling the order of similarly positioned mapControl elements */ (function() { angular.module("uiGmapgoogle-maps").directive("uiGmapMapControl", [ "uiGmapControl", function(Control) { return new Control(); } ]); }).call(this); ; /* @authors Nicholas McCready - https://twitter.com/nmccready */ (function() { angular.module('uiGmapgoogle-maps').directive('uiGmapDragZoom', [ 'uiGmapDragZoom', function(DragZoom) { return DragZoom; } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps').directive("uiGmapDrawingManager", [ "uiGmapDrawingManager", function(DrawingManager) { return DrawingManager; } ]); }).call(this); ; /* @authors Nicholas McCready - https://twitter.com/nmccready * Brunt of the work is in DrawFreeHandChildModel */ (function() { angular.module('uiGmapgoogle-maps').directive('uiGmapFreeDrawPolygons', [ 'uiGmapApiFreeDrawPolygons', function(FreeDrawPolygons) { return new FreeDrawPolygons(); } ]); }).call(this); ; /* Map Layer directive This directive is used to create any type of Layer from the google maps sdk. This directive creates a new scope. {attribute show optional} true (default) shows the trafficlayer otherwise it is hidden */ (function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; angular.module("uiGmapgoogle-maps").directive("uiGmapMapType", [ "$timeout", "uiGmapLogger", "uiGmapMapTypeParentModel", function($timeout, Logger, MapTypeParentModel) { var MapType; MapType = (function() { function MapType() { this.link = bind(this.link, this); this.$log = Logger; this.restrict = "EMA"; this.require = '^' + 'uiGmapGoogleMap'; this.priority = -1; this.transclude = true; this.template = '<span class=\"angular-google-map-layer\" ng-transclude></span>'; this.replace = true; this.scope = { show: "=show", options: '=options', refresh: '=refresh', id: '@' }; } MapType.prototype.link = function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then((function(_this) { return function(map) { return new MapTypeParentModel(scope, element, attrs, map); }; })(this)); }; return MapType; })(); return new MapType(); } ]); }).call(this); ; /* Map Layers directive This directive is used to create any type of Layer from the google maps sdk. This directive creates a new scope. */ (function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; angular.module('uiGmapgoogle-maps').directive("uiGmapMapTypes", [ "$timeout", "uiGmapLogger", "uiGmapMapTypesParentModel", function($timeout, Logger, MapTypesParentModel) { var MapTypes; MapTypes = (function() { function MapTypes() { this.link = bind(this.link, this); this.$log = Logger; this.restrict = "EMA"; this.require = '^' + 'uiGmapGoogleMap'; this.priority = -1; this.transclude = true; this.template = '<span class=\"angular-google-map-layers\" ng-transclude></span>'; this.scope = { mapTypes: "=mapTypes", show: "=show", options: "=options", refresh: "=refresh", id: "=idKey" }; } MapTypes.prototype.link = function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then((function(_this) { return function(map) { return new MapTypesParentModel(scope, element, attrs, map); }; })(this)); }; return MapTypes; })(); return new MapTypes(); } ]); }).call(this); ; /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready Rick Huizinga - https://plus.google.com/+RickHuizinga */ (function() { angular.module('uiGmapgoogle-maps').directive('uiGmapPolygons', [ 'uiGmapPolygons', function(Polygons) { return new Polygons(); } ]); }).call(this); ; /* @authors: - Nicolas Laplante https://plus.google.com/108189012221374960701 - Nicholas McCready - https://twitter.com/nmccready - Carrie Kengle - http://about.me/carrie */ /* Places Search Box directive This directive is used to create a Places Search Box. This directive creates a new scope. {attribute input required} HTMLInputElement {attribute options optional} The options that can be set on a SearchBox object (google.maps.places.SearchBoxOptions object specification) */ (function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; angular.module('uiGmapgoogle-maps').directive('uiGmapSearchBox', [ 'uiGmapGoogleMapApi', 'uiGmapLogger', 'uiGmapSearchBoxParentModel', '$http', '$templateCache', '$compile', function(GoogleMapApi, Logger, SearchBoxParentModel, $http, $templateCache, $compile) { var SearchBox; SearchBox = (function() { SearchBox.prototype.require = 'ngModel'; function SearchBox() { this.link = bind(this.link, this); this.$log = Logger; this.restrict = 'EMA'; this.require = '^' + 'uiGmapGoogleMap'; this.priority = -1; this.transclude = true; this.template = '<span class=\'angular-google-map-search\' ng-transclude></span>'; this.replace = true; this.scope = { template: '=template', events: '=events', position: '=?position', options: '=?options', parentdiv: '=?parentdiv', ngModel: "=?" }; } SearchBox.prototype.link = function(scope, element, attrs, mapCtrl) { return GoogleMapApi.then((function(_this) { return function(maps) { if (scope.template == null) { $templateCache.put('uigmap-searchbox-default.tpl.html', '<input type="text">'); scope.template = 'uigmap-searchbox-default.tpl.html'; } return $http.get(scope.template, { cache: $templateCache }).then(function(arg) { var data; data = arg.data; if (angular.isUndefined(scope.events)) { _this.$log.error('searchBox: the events property is required'); return; } return mapCtrl.getScope().deferred.promise.then(function(map) { var ctrlPosition; ctrlPosition = angular.isDefined(scope.position) ? scope.position.toUpperCase().replace(/-/g, '_') : 'TOP_LEFT'; if (!maps.ControlPosition[ctrlPosition]) { _this.$log.error('searchBox: invalid position property'); return; } return new SearchBoxParentModel(scope, element, attrs, map, ctrlPosition, $compile(data)(scope)); }); }); }; })(this)); }; return SearchBox; })(); return new SearchBox(); } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps').directive('uiGmapShow', [ '$animate', 'uiGmapLogger', function($animate, $log) { return { scope: { 'uiGmapShow': '=', 'uiGmapAfterShow': '&', 'uiGmapAfterHide': '&' }, link: function(scope, element) { var angular_post_1_3_handle, angular_pre_1_3_handle, handle; angular_post_1_3_handle = function(animateAction, cb) { return $animate[animateAction](element, 'ng-hide').then(function() { return cb(); }); }; angular_pre_1_3_handle = function(animateAction, cb) { return $animate[animateAction](element, 'ng-hide', cb); }; handle = function(animateAction, cb) { if (angular.version.major > 1) { return $log.error("uiGmapShow is not supported for Angular Major greater than 1.\nYour Major is " + angular.version.major + "\""); } if (angular.version.major === 1 && angular.version.minor < 3) { return angular_pre_1_3_handle(animateAction, cb); } return angular_post_1_3_handle(animateAction, cb); }; return scope.$watch('uiGmapShow', function(show) { if (show) { handle('removeClass', scope.uiGmapAfterShow); } if (!show) { return handle('addClass', scope.uiGmapAfterHide); } }); } }; } ]); }).call(this); ; /* @authors: - Nicholas McCready - https://twitter.com/nmccready */ /* StreetViewPanorama Directive to care of basic initialization of StreetViewPanorama */ (function() { angular.module('uiGmapgoogle-maps').directive('uiGmapStreetViewPanorama', [ 'uiGmapGoogleMapApi', 'uiGmapLogger', 'uiGmapGmapUtil', 'uiGmapEventsHelper', function(GoogleMapApi, $log, GmapUtil, EventsHelper) { var name; name = 'uiGmapStreetViewPanorama'; return { restrict: 'EMA', template: '<div class="angular-google-map-street-view-panorama"></div>', replace: true, scope: { focalcoord: '=', radius: '=?', events: '=?', options: '=?', control: '=?', povoptions: '=?', imagestatus: '=' }, link: function(scope, element, attrs) { return GoogleMapApi.then((function(_this) { return function(maps) { var clean, create, didCreateOptionsFromDirective, firstTime, handleSettings, listeners, opts, pano, povOpts, sv; pano = void 0; sv = void 0; didCreateOptionsFromDirective = false; listeners = void 0; opts = null; povOpts = null; clean = function() { EventsHelper.removeEvents(listeners); if (pano != null) { pano.unbind('position'); pano.setVisible(false); } if (sv != null) { if ((sv != null ? sv.setVisible : void 0) != null) { sv.setVisible(false); } return sv = void 0; } }; handleSettings = function(perspectivePoint, focalPoint) { var heading; heading = google.maps.geometry.spherical.computeHeading(perspectivePoint, focalPoint); didCreateOptionsFromDirective = true; scope.radius = scope.radius || 50; povOpts = angular.extend({ heading: heading, zoom: 1, pitch: 0 }, scope.povoptions || {}); opts = opts = angular.extend({ navigationControl: false, addressControl: false, linksControl: false, position: perspectivePoint, pov: povOpts, visible: true }, scope.options || {}); return didCreateOptionsFromDirective = false; }; create = function() { var focalPoint; if (!scope.focalcoord) { $log.error(name + ": focalCoord needs to be defined"); return; } if (!scope.radius) { $log.error(name + ": needs a radius to set the camera view from its focal target."); return; } clean(); if (sv == null) { sv = new google.maps.StreetViewService(); } if (scope.events) { listeners = EventsHelper.setEvents(sv, scope, scope); } focalPoint = GmapUtil.getCoords(scope.focalcoord); return sv.getPanoramaByLocation(focalPoint, scope.radius, function(streetViewPanoramaData, status) { var ele, perspectivePoint, ref; if (scope.imagestatus != null) { scope.imagestatus = status; } if (((ref = scope.events) != null ? ref.image_status_changed : void 0) != null) { scope.events.image_status_changed(sv, 'image_status_changed', scope, status); } if (status === "OK") { perspectivePoint = streetViewPanoramaData.location.latLng; handleSettings(perspectivePoint, focalPoint); ele = element[0]; return pano = new google.maps.StreetViewPanorama(ele, opts); } }); }; if (scope.control != null) { scope.control.getOptions = function() { return opts; }; scope.control.getPovOptions = function() { return povOpts; }; scope.control.getGObject = function() { return sv; }; scope.control.getGPano = function() { return pano; }; } scope.$watch('options', function(newValue, oldValue) { if (newValue === oldValue || newValue === opts || didCreateOptionsFromDirective) { return; } return create(); }); firstTime = true; scope.$watch('focalcoord', function(newValue, oldValue) { if (newValue === oldValue && !firstTime) { return; } if (newValue == null) { return; } firstTime = false; return create(); }); return scope.$on('$destroy', function() { return clean(); }); }; })(this)); } }; } ]); }).call(this); ;angular.module('uiGmapgoogle-maps.wrapped') .service('uiGmapuuid', function() { //BEGIN REPLACE /* istanbul ignore next */ /* Version: core-1.0 The MIT License: Copyright (c) 2012 LiosK. */ function UUID(){}UUID.generate=function(){var a=UUID._gri,b=UUID._ha;return b(a(32),8)+"-"+b(a(16),4)+"-"+b(16384|a(12),4)+"-"+b(32768|a(14),4)+"-"+b(a(48),12)};UUID._gri=function(a){return 0>a?NaN:30>=a?0|Math.random()*(1<<a):53>=a?(0|1073741824*Math.random())+1073741824*(0|Math.random()*(1<<a-30)):NaN};UUID._ha=function(a,b){for(var c=a.toString(16),d=b-c.length,e="0";0<d;d>>>=1,e+=e)d&1&&(c=e+c);return c}; //END REPLACE return UUID; }); ;// wrap the utility libraries needed in ./lib // http://google-maps-utility-library-v3.googlecode.com/svn/ angular.module('uiGmapgoogle-maps.wrapped') .service('uiGmapGoogleMapsUtilV3', function () { return { init: _.once(function () { //BEGIN REPLACE /* istanbul ignore next */ +function(){ function ClusterIcon(cluster,styles){cluster.getMarkerClusterer().extend(ClusterIcon,google.maps.OverlayView),this.cluster_=cluster,this.className_=cluster.getMarkerClusterer().getClusterClass(),this.styles_=styles,this.center_=null,this.div_=null,this.sums_=null,this.visible_=!1,this.setMap(cluster.getMap())}function Cluster(mc){this.markerClusterer_=mc,this.map_=mc.getMap(),this.gridSize_=mc.getGridSize(),this.minClusterSize_=mc.getMinimumClusterSize(),this.averageCenter_=mc.getAverageCenter(),this.hideLabel_=mc.getHideLabel(),this.markers_=[],this.center_=null,this.bounds_=null,this.clusterIcon_=new ClusterIcon(this,mc.getStyles())}function MarkerClusterer(map,opt_markers,opt_options){this.extend(MarkerClusterer,google.maps.OverlayView),opt_markers=opt_markers||[],opt_options=opt_options||{},this.markers_=[],this.clusters_=[],this.listeners_=[],this.activeMap_=null,this.ready_=!1,this.gridSize_=opt_options.gridSize||60,this.minClusterSize_=opt_options.minimumClusterSize||2,this.maxZoom_=opt_options.maxZoom||null,this.styles_=opt_options.styles||[],this.title_=opt_options.title||"",this.zoomOnClick_=!0,void 0!==opt_options.zoomOnClick&&(this.zoomOnClick_=opt_options.zoomOnClick),this.averageCenter_=!1,void 0!==opt_options.averageCenter&&(this.averageCenter_=opt_options.averageCenter),this.ignoreHidden_=!1,void 0!==opt_options.ignoreHidden&&(this.ignoreHidden_=opt_options.ignoreHidden),this.enableRetinaIcons_=!1,void 0!==opt_options.enableRetinaIcons&&(this.enableRetinaIcons_=opt_options.enableRetinaIcons),this.hideLabel_=!1,void 0!==opt_options.hideLabel&&(this.hideLabel_=opt_options.hideLabel),this.imagePath_=opt_options.imagePath||MarkerClusterer.IMAGE_PATH,this.imageExtension_=opt_options.imageExtension||MarkerClusterer.IMAGE_EXTENSION,this.imageSizes_=opt_options.imageSizes||MarkerClusterer.IMAGE_SIZES,this.calculator_=opt_options.calculator||MarkerClusterer.CALCULATOR,this.batchSize_=opt_options.batchSize||MarkerClusterer.BATCH_SIZE,this.batchSizeIE_=opt_options.batchSizeIE||MarkerClusterer.BATCH_SIZE_IE,this.clusterClass_=opt_options.clusterClass||"cluster",-1!==navigator.userAgent.toLowerCase().indexOf("msie")&&(this.batchSize_=this.batchSizeIE_),this.setupStyles_(),this.addMarkers(opt_markers,!0),this.setMap(map)}ClusterIcon.prototype.onAdd=function(){var cMouseDownInCluster,cDraggingMapByCluster,cClusterIcon=this;this.div_=document.createElement("div"),this.div_.className=this.className_,this.visible_&&this.show(),this.getPanes().overlayMouseTarget.appendChild(this.div_),this.boundsChangedListener_=google.maps.event.addListener(this.getMap(),"bounds_changed",function(){cDraggingMapByCluster=cMouseDownInCluster}),google.maps.event.addDomListener(this.div_,"mousedown",function(){cMouseDownInCluster=!0,cDraggingMapByCluster=!1}),google.maps.event.addDomListener(this.div_,"click",function(e){if(cMouseDownInCluster=!1,!cDraggingMapByCluster){var theBounds,mz,mc=cClusterIcon.cluster_.getMarkerClusterer();google.maps.event.trigger(mc,"click",cClusterIcon.cluster_),google.maps.event.trigger(mc,"clusterclick",cClusterIcon.cluster_),mc.getZoomOnClick()&&(mz=mc.getMaxZoom(),theBounds=cClusterIcon.cluster_.getBounds(),mc.getMap().fitBounds(theBounds),setTimeout(function(){mc.getMap().fitBounds(theBounds),null!==mz&&mc.getMap().getZoom()>mz&&mc.getMap().setZoom(mz+1)},100)),e.cancelBubble=!0,e.stopPropagation&&e.stopPropagation()}}),google.maps.event.addDomListener(this.div_,"mouseover",function(){var mc=cClusterIcon.cluster_.getMarkerClusterer();google.maps.event.trigger(mc,"mouseover",cClusterIcon.cluster_)}),google.maps.event.addDomListener(this.div_,"mouseout",function(){var mc=cClusterIcon.cluster_.getMarkerClusterer();google.maps.event.trigger(mc,"mouseout",cClusterIcon.cluster_)})},ClusterIcon.prototype.onRemove=function(){this.div_&&this.div_.parentNode&&(this.hide(),google.maps.event.removeListener(this.boundsChangedListener_),google.maps.event.clearInstanceListeners(this.div_),this.div_.parentNode.removeChild(this.div_),this.div_=null)},ClusterIcon.prototype.draw=function(){if(this.visible_){var pos=this.getPosFromLatLng_(this.center_);this.div_.style.top=pos.y+"px",this.div_.style.left=pos.x+"px"}},ClusterIcon.prototype.hide=function(){this.div_&&(this.div_.style.display="none"),this.visible_=!1},ClusterIcon.prototype.show=function(){if(this.div_){var img="",bp=this.backgroundPosition_.split(" "),spriteH=parseInt(bp[0].trim(),10),spriteV=parseInt(bp[1].trim(),10),pos=this.getPosFromLatLng_(this.center_);this.div_.style.cssText=this.createCss(pos),img="<img src='"+this.url_+"' style='position: absolute; top: "+spriteV+"px; left: "+spriteH+"px; ",img+=this.cluster_.getMarkerClusterer().enableRetinaIcons_?"width: "+this.width_+"px;height: "+this.height_+"px;":"clip: rect("+-1*spriteV+"px, "+(-1*spriteH+this.width_)+"px, "+(-1*spriteV+this.height_)+"px, "+-1*spriteH+"px);",img+="'>",this.div_.innerHTML=img+"<div style='position: absolute;top: "+this.anchorText_[0]+"px;left: "+this.anchorText_[1]+"px;color: "+this.textColor_+";font-size: "+this.textSize_+"px;font-family: "+this.fontFamily_+";font-weight: "+this.fontWeight_+";font-style: "+this.fontStyle_+";text-decoration: "+this.textDecoration_+";text-align: center;width: "+this.width_+"px;line-height:"+this.height_+"px;'>"+(this.cluster_.hideLabel_?" ":this.sums_.text)+"</div>",this.div_.title="undefined"==typeof this.sums_.title||""===this.sums_.title?this.cluster_.getMarkerClusterer().getTitle():this.sums_.title,this.div_.style.display=""}this.visible_=!0},ClusterIcon.prototype.useStyle=function(sums){this.sums_=sums;var index=Math.max(0,sums.index-1);index=Math.min(this.styles_.length-1,index);var style=this.styles_[index];this.url_=style.url,this.height_=style.height,this.width_=style.width,this.anchorText_=style.anchorText||[0,0],this.anchorIcon_=style.anchorIcon||[parseInt(this.height_/2,10),parseInt(this.width_/2,10)],this.textColor_=style.textColor||"black",this.textSize_=style.textSize||11,this.textDecoration_=style.textDecoration||"none",this.fontWeight_=style.fontWeight||"bold",this.fontStyle_=style.fontStyle||"normal",this.fontFamily_=style.fontFamily||"Arial,sans-serif",this.backgroundPosition_=style.backgroundPosition||"0 0"},ClusterIcon.prototype.setCenter=function(center){this.center_=center},ClusterIcon.prototype.createCss=function(pos){var style=[];return style.push("cursor: pointer;"),style.push("position: absolute; top: "+pos.y+"px; left: "+pos.x+"px;"),style.push("width: "+this.width_+"px; height: "+this.height_+"px;"),style.join("")},ClusterIcon.prototype.getPosFromLatLng_=function(latlng){var pos=this.getProjection().fromLatLngToDivPixel(latlng);return pos.x-=this.anchorIcon_[1],pos.y-=this.anchorIcon_[0],pos.x=parseInt(pos.x,10),pos.y=parseInt(pos.y,10),pos},Cluster.prototype.getSize=function(){return this.markers_.length},Cluster.prototype.getMarkers=function(){return this.markers_},Cluster.prototype.getCenter=function(){return this.center_},Cluster.prototype.getMap=function(){return this.map_},Cluster.prototype.getMarkerClusterer=function(){return this.markerClusterer_},Cluster.prototype.getBounds=function(){var i,bounds=new google.maps.LatLngBounds(this.center_,this.center_),markers=this.getMarkers();for(i=0;i<markers.length;i++)bounds.extend(markers[i].getPosition());return bounds},Cluster.prototype.remove=function(){this.clusterIcon_.setMap(null),this.markers_=[],delete this.markers_},Cluster.prototype.addMarker=function(marker){var i,mCount,mz;if(this.isMarkerAlreadyAdded_(marker))return!1;if(this.center_){if(this.averageCenter_){var l=this.markers_.length+1,lat=(this.center_.lat()*(l-1)+marker.getPosition().lat())/l,lng=(this.center_.lng()*(l-1)+marker.getPosition().lng())/l;this.center_=new google.maps.LatLng(lat,lng),this.calculateBounds_()}}else this.center_=marker.getPosition(),this.calculateBounds_();if(marker.isAdded=!0,this.markers_.push(marker),mCount=this.markers_.length,mz=this.markerClusterer_.getMaxZoom(),null!==mz&&this.map_.getZoom()>mz)marker.getMap()!==this.map_&&marker.setMap(this.map_);else if(mCount<this.minClusterSize_)marker.getMap()!==this.map_&&marker.setMap(this.map_);else if(mCount===this.minClusterSize_)for(i=0;mCount>i;i++)this.markers_[i].setMap(null);else marker.setMap(null);return!0},Cluster.prototype.isMarkerInClusterBounds=function(marker){return this.bounds_.contains(marker.getPosition())},Cluster.prototype.calculateBounds_=function(){var bounds=new google.maps.LatLngBounds(this.center_,this.center_);this.bounds_=this.markerClusterer_.getExtendedBounds(bounds)},Cluster.prototype.updateIcon_=function(){var mCount=this.markers_.length,mz=this.markerClusterer_.getMaxZoom();if(null!==mz&&this.map_.getZoom()>mz)return void this.clusterIcon_.hide();if(mCount<this.minClusterSize_)return void this.clusterIcon_.hide();var numStyles=this.markerClusterer_.getStyles().length,sums=this.markerClusterer_.getCalculator()(this.markers_,numStyles);this.clusterIcon_.setCenter(this.center_),this.clusterIcon_.useStyle(sums),this.clusterIcon_.show()},Cluster.prototype.isMarkerAlreadyAdded_=function(marker){for(var i=0,n=this.markers_.length;n>i;i++)if(marker===this.markers_[i])return!0;return!1},MarkerClusterer.prototype.onAdd=function(){var cMarkerClusterer=this;this.activeMap_=this.getMap(),this.ready_=!0,this.repaint(),this.listeners_=[google.maps.event.addListener(this.getMap(),"zoom_changed",function(){cMarkerClusterer.resetViewport_(!1),(this.getZoom()===(this.get("minZoom")||0)||this.getZoom()===this.get("maxZoom"))&&google.maps.event.trigger(this,"idle")}),google.maps.event.addListener(this.getMap(),"idle",function(){cMarkerClusterer.redraw_()})]},MarkerClusterer.prototype.onRemove=function(){var i;for(i=0;i<this.markers_.length;i++)this.markers_[i].getMap()!==this.activeMap_&&this.markers_[i].setMap(this.activeMap_);for(i=0;i<this.clusters_.length;i++)this.clusters_[i].remove();for(this.clusters_=[],i=0;i<this.listeners_.length;i++)google.maps.event.removeListener(this.listeners_[i]);this.listeners_=[],this.activeMap_=null,this.ready_=!1},MarkerClusterer.prototype.draw=function(){},MarkerClusterer.prototype.setupStyles_=function(){var i,size;if(!(this.styles_.length>0))for(i=0;i<this.imageSizes_.length;i++)size=this.imageSizes_[i],this.styles_.push({url:this.imagePath_+(i+1)+"."+this.imageExtension_,height:size,width:size})},MarkerClusterer.prototype.fitMapToMarkers=function(){var i,markers=this.getMarkers(),bounds=new google.maps.LatLngBounds;for(i=0;i<markers.length;i++)bounds.extend(markers[i].getPosition());this.getMap().fitBounds(bounds)},MarkerClusterer.prototype.getGridSize=function(){return this.gridSize_},MarkerClusterer.prototype.setGridSize=function(gridSize){this.gridSize_=gridSize},MarkerClusterer.prototype.getMinimumClusterSize=function(){return this.minClusterSize_},MarkerClusterer.prototype.setMinimumClusterSize=function(minimumClusterSize){this.minClusterSize_=minimumClusterSize},MarkerClusterer.prototype.getMaxZoom=function(){return this.maxZoom_},MarkerClusterer.prototype.setMaxZoom=function(maxZoom){this.maxZoom_=maxZoom},MarkerClusterer.prototype.getStyles=function(){return this.styles_},MarkerClusterer.prototype.setStyles=function(styles){this.styles_=styles},MarkerClusterer.prototype.getTitle=function(){return this.title_},MarkerClusterer.prototype.setTitle=function(title){this.title_=title},MarkerClusterer.prototype.getZoomOnClick=function(){return this.zoomOnClick_},MarkerClusterer.prototype.setZoomOnClick=function(zoomOnClick){this.zoomOnClick_=zoomOnClick},MarkerClusterer.prototype.getAverageCenter=function(){return this.averageCenter_},MarkerClusterer.prototype.setAverageCenter=function(averageCenter){this.averageCenter_=averageCenter},MarkerClusterer.prototype.getIgnoreHidden=function(){return this.ignoreHidden_},MarkerClusterer.prototype.setIgnoreHidden=function(ignoreHidden){this.ignoreHidden_=ignoreHidden},MarkerClusterer.prototype.getEnableRetinaIcons=function(){return this.enableRetinaIcons_},MarkerClusterer.prototype.setEnableRetinaIcons=function(enableRetinaIcons){this.enableRetinaIcons_=enableRetinaIcons},MarkerClusterer.prototype.getImageExtension=function(){return this.imageExtension_},MarkerClusterer.prototype.setImageExtension=function(imageExtension){this.imageExtension_=imageExtension},MarkerClusterer.prototype.getImagePath=function(){return this.imagePath_},MarkerClusterer.prototype.setImagePath=function(imagePath){this.imagePath_=imagePath},MarkerClusterer.prototype.getImageSizes=function(){return this.imageSizes_},MarkerClusterer.prototype.setImageSizes=function(imageSizes){this.imageSizes_=imageSizes},MarkerClusterer.prototype.getCalculator=function(){return this.calculator_},MarkerClusterer.prototype.setCalculator=function(calculator){this.calculator_=calculator},MarkerClusterer.prototype.setHideLabel=function(hideLabel){this.hideLabel_=hideLabel},MarkerClusterer.prototype.getHideLabel=function(){return this.hideLabel_},MarkerClusterer.prototype.getBatchSizeIE=function(){return this.batchSizeIE_},MarkerClusterer.prototype.setBatchSizeIE=function(batchSizeIE){this.batchSizeIE_=batchSizeIE},MarkerClusterer.prototype.getClusterClass=function(){return this.clusterClass_},MarkerClusterer.prototype.setClusterClass=function(clusterClass){this.clusterClass_=clusterClass},MarkerClusterer.prototype.getMarkers=function(){return this.markers_},MarkerClusterer.prototype.getTotalMarkers=function(){return this.markers_.length},MarkerClusterer.prototype.getClusters=function(){return this.clusters_},MarkerClusterer.prototype.getTotalClusters=function(){return this.clusters_.length},MarkerClusterer.prototype.addMarker=function(marker,opt_nodraw){this.pushMarkerTo_(marker),opt_nodraw||this.redraw_()},MarkerClusterer.prototype.addMarkers=function(markers,opt_nodraw){var key;for(key in markers)markers.hasOwnProperty(key)&&this.pushMarkerTo_(markers[key]);opt_nodraw||this.redraw_()},MarkerClusterer.prototype.pushMarkerTo_=function(marker){if(marker.getDraggable()){var cMarkerClusterer=this;google.maps.event.addListener(marker,"dragend",function(){cMarkerClusterer.ready_&&(this.isAdded=!1,cMarkerClusterer.repaint())})}marker.isAdded=!1,this.markers_.push(marker)},MarkerClusterer.prototype.removeMarker=function(marker,opt_nodraw,opt_noMapRemove){var removeFromMap=!0&&!opt_noMapRemove,removed=this.removeMarker_(marker,removeFromMap);return!opt_nodraw&&removed&&this.repaint(),removed},MarkerClusterer.prototype.removeMarkers=function(markers,opt_nodraw,opt_noMapRemove){var i,r,removed=!1,removeFromMap=!0&&!opt_noMapRemove;for(i=0;i<markers.length;i++)r=this.removeMarker_(markers[i],removeFromMap),removed=removed||r;return!opt_nodraw&&removed&&this.repaint(),removed},MarkerClusterer.prototype.removeMarker_=function(marker,removeFromMap){var i,index=-1;if(this.markers_.indexOf)index=this.markers_.indexOf(marker);else for(i=0;i<this.markers_.length;i++)if(marker===this.markers_[i]){index=i;break}return-1===index?!1:(removeFromMap&&marker.setMap(null),this.markers_.splice(index,1),!0)},MarkerClusterer.prototype.clearMarkers=function(){this.resetViewport_(!0),this.markers_=[]},MarkerClusterer.prototype.repaint=function(){var oldClusters=this.clusters_.slice();this.clusters_=[],this.resetViewport_(!1),this.redraw_(),setTimeout(function(){var i;for(i=0;i<oldClusters.length;i++)oldClusters[i].remove()},0)},MarkerClusterer.prototype.getExtendedBounds=function(bounds){var projection=this.getProjection(),tr=new google.maps.LatLng(bounds.getNorthEast().lat(),bounds.getNorthEast().lng()),bl=new google.maps.LatLng(bounds.getSouthWest().lat(),bounds.getSouthWest().lng()),trPix=projection.fromLatLngToDivPixel(tr);trPix.x+=this.gridSize_,trPix.y-=this.gridSize_;var blPix=projection.fromLatLngToDivPixel(bl);blPix.x-=this.gridSize_,blPix.y+=this.gridSize_;var ne=projection.fromDivPixelToLatLng(trPix),sw=projection.fromDivPixelToLatLng(blPix);return bounds.extend(ne),bounds.extend(sw),bounds},MarkerClusterer.prototype.redraw_=function(){this.createClusters_(0)},MarkerClusterer.prototype.resetViewport_=function(opt_hide){var i,marker;for(i=0;i<this.clusters_.length;i++)this.clusters_[i].remove();for(this.clusters_=[],i=0;i<this.markers_.length;i++)marker=this.markers_[i],marker.isAdded=!1,opt_hide&&marker.setMap(null)},MarkerClusterer.prototype.distanceBetweenPoints_=function(p1,p2){var R=6371,dLat=(p2.lat()-p1.lat())*Math.PI/180,dLon=(p2.lng()-p1.lng())*Math.PI/180,a=Math.sin(dLat/2)*Math.sin(dLat/2)+Math.cos(p1.lat()*Math.PI/180)*Math.cos(p2.lat()*Math.PI/180)*Math.sin(dLon/2)*Math.sin(dLon/2),c=2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a)),d=R*c;return d},MarkerClusterer.prototype.isMarkerInBounds_=function(marker,bounds){return bounds.contains(marker.getPosition())},MarkerClusterer.prototype.addToClosestCluster_=function(marker){var i,d,cluster,center,distance=4e4,clusterToAddTo=null;for(i=0;i<this.clusters_.length;i++)cluster=this.clusters_[i],center=cluster.getCenter(),center&&(d=this.distanceBetweenPoints_(center,marker.getPosition()),distance>d&&(distance=d,clusterToAddTo=cluster));clusterToAddTo&&clusterToAddTo.isMarkerInClusterBounds(marker)?clusterToAddTo.addMarker(marker):(cluster=new Cluster(this),cluster.addMarker(marker),this.clusters_.push(cluster))},MarkerClusterer.prototype.createClusters_=function(iFirst){var i,marker,mapBounds,cMarkerClusterer=this;if(this.ready_){0===iFirst&&(google.maps.event.trigger(this,"clusteringbegin",this),"undefined"!=typeof this.timerRefStatic&&(clearTimeout(this.timerRefStatic),delete this.timerRefStatic)),mapBounds=this.getMap().getZoom()>3?new google.maps.LatLngBounds(this.getMap().getBounds().getSouthWest(),this.getMap().getBounds().getNorthEast()):new google.maps.LatLngBounds(new google.maps.LatLng(85.02070771743472,-178.48388434375),new google.maps.LatLng(-85.08136444384544,178.00048865625));var bounds=this.getExtendedBounds(mapBounds),iLast=Math.min(iFirst+this.batchSize_,this.markers_.length);for(i=iFirst;iLast>i;i++)marker=this.markers_[i],!marker.isAdded&&this.isMarkerInBounds_(marker,bounds)&&(!this.ignoreHidden_||this.ignoreHidden_&&marker.getVisible())&&this.addToClosestCluster_(marker);if(iLast<this.markers_.length)this.timerRefStatic=setTimeout(function(){cMarkerClusterer.createClusters_(iLast)},0);else for(delete this.timerRefStatic,google.maps.event.trigger(this,"clusteringend",this),i=0;i<this.clusters_.length;i++)this.clusters_[i].updateIcon_()}},MarkerClusterer.prototype.extend=function(obj1,obj2){return function(object){var property;for(property in object.prototype)this.prototype[property]=object.prototype[property];return this}.apply(obj1,[obj2])},MarkerClusterer.CALCULATOR=function(markers,numStyles){for(var index=0,title="",count=markers.length.toString(),dv=count;0!==dv;)dv=parseInt(dv/10,10),index++;return index=Math.min(index,numStyles),{text:count,index:index,title:title}},MarkerClusterer.BATCH_SIZE=2e3,MarkerClusterer.BATCH_SIZE_IE=500,MarkerClusterer.IMAGE_PATH="//cdn.rawgit.com/mahnunchik/markerclustererplus/master/images/m",MarkerClusterer.IMAGE_EXTENSION="png",MarkerClusterer.IMAGE_SIZES=[53,56,66,78,90],"function"!=typeof String.prototype.trim&&(String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g,"")}); /** * google-maps-utility-library-v3-infobox * * @version: 1.1.14 * @author: Gary Little (inspired by proof-of-concept code from Pamela Fox of Google) * @contributors: Nicholas McCready * @date: Fri May 13 2016 16:35:27 GMT-0400 (EDT) * @license: Apache License 2.0 */ /** * @fileoverview InfoBox extends the Google Maps JavaScript API V3 <tt>OverlayView</tt> class. * <p> * An InfoBox behaves like a <tt>google.maps.InfoWindow</tt>, but it supports several * additional properties for advanced styling. An InfoBox can also be used as a map label. * <p> * An InfoBox also fires the same events as a <tt>google.maps.InfoWindow</tt>. */ /*jslint browser:true */ /*global google */ /** * @name InfoBoxOptions * @class This class represents the optional parameter passed to the {@link InfoBox} constructor. * @property {string|Node} content The content of the InfoBox (plain text or an HTML DOM node). * @property {boolean} [disableAutoPan=false] Disable auto-pan on <tt>open</tt>. * @property {number} maxWidth The maximum width (in pixels) of the InfoBox. Set to 0 if no maximum. * @property {Size} pixelOffset The offset (in pixels) from the top left corner of the InfoBox * (or the bottom left corner if the <code>alignBottom</code> property is <code>true</code>) * to the map pixel corresponding to <tt>position</tt>. * @property {LatLng} position The geographic location at which to display the InfoBox. * @property {number} zIndex The CSS z-index style value for the InfoBox. * Note: This value overrides a zIndex setting specified in the <tt>boxStyle</tt> property. * @property {string} [boxClass="infoBox"] The name of the CSS class defining the styles for the InfoBox container. * @property {Object} [boxStyle] An object literal whose properties define specific CSS * style values to be applied to the InfoBox. Style values defined here override those that may * be defined in the <code>boxClass</code> style sheet. If this property is changed after the * InfoBox has been created, all previously set styles (except those defined in the style sheet) * are removed from the InfoBox before the new style values are applied. * @property {string} closeBoxMargin The CSS margin style value for the close box. * The default is "2px" (a 2-pixel margin on all sides). * @property {string} closeBoxURL The URL of the image representing the close box. * Note: The default is the URL for Google's standard close box. * Set this property to "" if no close box is required. * @property {Size} infoBoxClearance Minimum offset (in pixels) from the InfoBox to the * map edge after an auto-pan. * @property {boolean} [isHidden=false] Hide the InfoBox on <tt>open</tt>. * [Deprecated in favor of the <tt>visible</tt> property.] * @property {boolean} [visible=true] Show the InfoBox on <tt>open</tt>. * @property {boolean} alignBottom Align the bottom left corner of the InfoBox to the <code>position</code> * location (default is <tt>false</tt> which means that the top left corner of the InfoBox is aligned). * @property {string} pane The pane where the InfoBox is to appear (default is "floatPane"). * Set the pane to "mapPane" if the InfoBox is being used as a map label. * Valid pane names are the property names for the <tt>google.maps.MapPanes</tt> object. * @property {boolean} enableEventPropagation Propagate mousedown, mousemove, mouseover, mouseout, * mouseup, click, dblclick, touchstart, touchend, touchmove, and contextmenu events in the InfoBox * (default is <tt>false</tt> to mimic the behavior of a <tt>google.maps.InfoWindow</tt>). Set * this property to <tt>true</tt> if the InfoBox is being used as a map label. */ /** * Creates an InfoBox with the options specified in {@link InfoBoxOptions}. * Call <tt>InfoBox.open</tt> to add the box to the map. * @constructor * @param {InfoBoxOptions} [opt_opts] */ function InfoBox(opt_opts) { opt_opts = opt_opts || {}; google.maps.OverlayView.apply(this, arguments); // Standard options (in common with google.maps.InfoWindow): // this.content_ = opt_opts.content || ""; this.disableAutoPan_ = opt_opts.disableAutoPan || false; this.maxWidth_ = opt_opts.maxWidth || 0; this.pixelOffset_ = opt_opts.pixelOffset || new google.maps.Size(0, 0); this.position_ = opt_opts.position || new google.maps.LatLng(0, 0); this.zIndex_ = opt_opts.zIndex || null; // Additional options (unique to InfoBox): // this.boxClass_ = opt_opts.boxClass || "infoBox"; this.boxStyle_ = opt_opts.boxStyle || {}; this.closeBoxMargin_ = opt_opts.closeBoxMargin || "2px"; this.closeBoxURL_ = opt_opts.closeBoxURL || "http://www.google.com/intl/en_us/mapfiles/close.gif"; if (opt_opts.closeBoxURL === "") { this.closeBoxURL_ = ""; } this.infoBoxClearance_ = opt_opts.infoBoxClearance || new google.maps.Size(1, 1); if (typeof opt_opts.visible === "undefined") { if (typeof opt_opts.isHidden === "undefined") { opt_opts.visible = true; } else { opt_opts.visible = !opt_opts.isHidden; } } this.isHidden_ = !opt_opts.visible; this.alignBottom_ = opt_opts.alignBottom || false; this.pane_ = opt_opts.pane || "floatPane"; this.enableEventPropagation_ = opt_opts.enableEventPropagation || false; this.div_ = null; this.closeListener_ = null; this.moveListener_ = null; this.contextListener_ = null; this.eventListeners_ = null; this.fixedWidthSet_ = null; } /* InfoBox extends OverlayView in the Google Maps API v3. */ InfoBox.prototype = new google.maps.OverlayView(); /** * Creates the DIV representing the InfoBox. * @private */ InfoBox.prototype.createInfoBoxDiv_ = function () { var i; var events; var bw; var me = this; // This handler prevents an event in the InfoBox from being passed on to the map. // var cancelHandler = function (e) { e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } }; // This handler ignores the current event in the InfoBox and conditionally prevents // the event from being passed on to the map. It is used for the contextmenu event. // var ignoreHandler = function (e) { e.returnValue = false; if (e.preventDefault) { e.preventDefault(); } if (!me.enableEventPropagation_) { cancelHandler(e); } }; if (!this.div_) { this.div_ = document.createElement("div"); this.setBoxStyle_(); if (typeof this.content_.nodeType === "undefined") { this.div_.innerHTML = this.getCloseBoxImg_() + this.content_; } else { this.div_.innerHTML = this.getCloseBoxImg_(); this.div_.appendChild(this.content_); } // Add the InfoBox DIV to the DOM this.getPanes()[this.pane_].appendChild(this.div_); this.addClickHandler_(); if (this.div_.style.width) { this.fixedWidthSet_ = true; } else { if (this.maxWidth_ !== 0 && this.div_.offsetWidth > this.maxWidth_) { this.div_.style.width = this.maxWidth_; this.div_.style.overflow = "auto"; this.fixedWidthSet_ = true; } else { // The following code is needed to overcome problems with MSIE bw = this.getBoxWidths_(); this.div_.style.width = (this.div_.offsetWidth - bw.left - bw.right) + "px"; this.fixedWidthSet_ = false; } } this.panBox_(this.disableAutoPan_); if (!this.enableEventPropagation_) { this.eventListeners_ = []; // Cancel event propagation. // // Note: mousemove not included (to resolve Issue 152) events = ["mousedown", "mouseover", "mouseout", "mouseup", "click", "dblclick", "touchstart", "touchend", "touchmove"]; for (i = 0; i < events.length; i++) { this.eventListeners_.push(google.maps.event.addDomListener(this.div_, events[i], cancelHandler)); } // Workaround for Google bug that causes the cursor to change to a pointer // when the mouse moves over a marker underneath InfoBox. this.eventListeners_.push(google.maps.event.addDomListener(this.div_, "mouseover", function (e) { this.style.cursor = "default"; })); } this.contextListener_ = google.maps.event.addDomListener(this.div_, "contextmenu", ignoreHandler); /** * This event is fired when the DIV containing the InfoBox's content is attached to the DOM. * @name InfoBox#domready * @event */ google.maps.event.trigger(this, "domready"); } }; /** * Returns the HTML <IMG> tag for the close box. * @private */ InfoBox.prototype.getCloseBoxImg_ = function () { var img = ""; if (this.closeBoxURL_ !== "") { img = "<img"; img += " src='" + this.closeBoxURL_ + "'"; img += " align=right"; // Do this because Opera chokes on style='float: right;' img += " style='"; img += " position: relative;"; // Required by MSIE img += " cursor: pointer;"; img += " margin: " + this.closeBoxMargin_ + ";"; img += "'>"; } return img; }; /** * Adds the click handler to the InfoBox close box. * @private */ InfoBox.prototype.addClickHandler_ = function () { var closeBox; if (this.closeBoxURL_ !== "") { closeBox = this.div_.firstChild; this.closeListener_ = google.maps.event.addDomListener(closeBox, "click", this.getCloseClickHandler_()); } else { this.closeListener_ = null; } }; /** * Returns the function to call when the user clicks the close box of an InfoBox. * @private */ InfoBox.prototype.getCloseClickHandler_ = function () { var me = this; return function (e) { // 1.0.3 fix: Always prevent propagation of a close box click to the map: e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } /** * This event is fired when the InfoBox's close box is clicked. * @name InfoBox#closeclick * @event */ google.maps.event.trigger(me, "closeclick"); me.close(); }; }; /** * Pans the map so that the InfoBox appears entirely within the map's visible area. * @private */ InfoBox.prototype.panBox_ = function (disablePan) { var map; var bounds; var xOffset = 0, yOffset = 0; if (!disablePan) { map = this.getMap(); if (map instanceof google.maps.Map) { // Only pan if attached to map, not panorama if (!map.getBounds().contains(this.position_)) { // Marker not in visible area of map, so set center // of map to the marker position first. map.setCenter(this.position_); } bounds = map.getBounds(); var mapDiv = map.getDiv(); var mapWidth = mapDiv.offsetWidth; var mapHeight = mapDiv.offsetHeight; var iwOffsetX = this.pixelOffset_.width; var iwOffsetY = this.pixelOffset_.height; var iwWidth = this.div_.offsetWidth; var iwHeight = this.div_.offsetHeight; var padX = this.infoBoxClearance_.width; var padY = this.infoBoxClearance_.height; var pixPosition = this.getProjection().fromLatLngToContainerPixel(this.position_); if (pixPosition.x < (-iwOffsetX + padX)) { xOffset = pixPosition.x + iwOffsetX - padX; } else if ((pixPosition.x + iwWidth + iwOffsetX + padX) > mapWidth) { xOffset = pixPosition.x + iwWidth + iwOffsetX + padX - mapWidth; } if (this.alignBottom_) { if (pixPosition.y < (-iwOffsetY + padY + iwHeight)) { yOffset = pixPosition.y + iwOffsetY - padY - iwHeight; } else if ((pixPosition.y + iwOffsetY + padY) > mapHeight) { yOffset = pixPosition.y + iwOffsetY + padY - mapHeight; } } else { if (pixPosition.y < (-iwOffsetY + padY)) { yOffset = pixPosition.y + iwOffsetY - padY; } else if ((pixPosition.y + iwHeight + iwOffsetY + padY) > mapHeight) { yOffset = pixPosition.y + iwHeight + iwOffsetY + padY - mapHeight; } } if (!(xOffset === 0 && yOffset === 0)) { // Move the map to the shifted center. // var c = map.getCenter(); map.panBy(xOffset, yOffset); } } } }; /** * Sets the style of the InfoBox by setting the style sheet and applying * other specific styles requested. * @private */ InfoBox.prototype.setBoxStyle_ = function () { var i, boxStyle; if (this.div_) { // Apply style values from the style sheet defined in the boxClass parameter: this.div_.className = this.boxClass_; // Clear existing inline style values: this.div_.style.cssText = ""; // Apply style values defined in the boxStyle parameter: boxStyle = this.boxStyle_; for (i in boxStyle) { if (boxStyle.hasOwnProperty(i)) { this.div_.style[i] = boxStyle[i]; } } // Fix for iOS disappearing InfoBox problem. // See http://stackoverflow.com/questions/9229535/google-maps-markers-disappear-at-certain-zoom-level-only-on-iphone-ipad this.div_.style.WebkitTransform = "translateZ(0)"; // Fix up opacity style for benefit of MSIE: // if (typeof this.div_.style.opacity !== "undefined" && this.div_.style.opacity !== "") { // See http://www.quirksmode.org/css/opacity.html this.div_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(Opacity=" + (this.div_.style.opacity * 100) + ")\""; this.div_.style.filter = "alpha(opacity=" + (this.div_.style.opacity * 100) + ")"; } // Apply required styles: // this.div_.style.position = "absolute"; this.div_.style.visibility = 'hidden'; if (this.zIndex_ !== null) { this.div_.style.zIndex = this.zIndex_; } } }; /** * Get the widths of the borders of the InfoBox. * @private * @return {Object} widths object (top, bottom left, right) */ InfoBox.prototype.getBoxWidths_ = function () { var computedStyle; var bw = {top: 0, bottom: 0, left: 0, right: 0}; var box = this.div_; if (document.defaultView && document.defaultView.getComputedStyle) { computedStyle = box.ownerDocument.defaultView.getComputedStyle(box, ""); if (computedStyle) { // The computed styles are always in pixel units (good!) bw.top = parseInt(computedStyle.borderTopWidth, 10) || 0; bw.bottom = parseInt(computedStyle.borderBottomWidth, 10) || 0; bw.left = parseInt(computedStyle.borderLeftWidth, 10) || 0; bw.right = parseInt(computedStyle.borderRightWidth, 10) || 0; } } else if (document.documentElement.currentStyle) { // MSIE if (box.currentStyle) { // The current styles may not be in pixel units, but assume they are (bad!) bw.top = parseInt(box.currentStyle.borderTopWidth, 10) || 0; bw.bottom = parseInt(box.currentStyle.borderBottomWidth, 10) || 0; bw.left = parseInt(box.currentStyle.borderLeftWidth, 10) || 0; bw.right = parseInt(box.currentStyle.borderRightWidth, 10) || 0; } } return bw; }; /** * Invoked when <tt>close</tt> is called. Do not call it directly. */ InfoBox.prototype.onRemove = function () { if (this.div_) { this.div_.parentNode.removeChild(this.div_); this.div_ = null; } }; /** * Draws the InfoBox based on the current map projection and zoom level. */ InfoBox.prototype.draw = function () { this.createInfoBoxDiv_(); var pixPosition = this.getProjection().fromLatLngToDivPixel(this.position_); this.div_.style.left = (pixPosition.x + this.pixelOffset_.width) + "px"; if (this.alignBottom_) { this.div_.style.bottom = -(pixPosition.y + this.pixelOffset_.height) + "px"; } else { this.div_.style.top = (pixPosition.y + this.pixelOffset_.height) + "px"; } if (this.isHidden_) { this.div_.style.visibility = "hidden"; } else { this.div_.style.visibility = "visible"; } }; /** * Sets the options for the InfoBox. Note that changes to the <tt>maxWidth</tt>, * <tt>closeBoxMargin</tt>, <tt>closeBoxURL</tt>, and <tt>enableEventPropagation</tt> * properties have no affect until the current InfoBox is <tt>close</tt>d and a new one * is <tt>open</tt>ed. * @param {InfoBoxOptions} opt_opts */ InfoBox.prototype.setOptions = function (opt_opts) { if (typeof opt_opts.boxClass !== "undefined") { // Must be first this.boxClass_ = opt_opts.boxClass; this.setBoxStyle_(); } if (typeof opt_opts.boxStyle !== "undefined") { // Must be second this.boxStyle_ = opt_opts.boxStyle; this.setBoxStyle_(); } if (typeof opt_opts.content !== "undefined") { this.setContent(opt_opts.content); } if (typeof opt_opts.disableAutoPan !== "undefined") { this.disableAutoPan_ = opt_opts.disableAutoPan; } if (typeof opt_opts.maxWidth !== "undefined") { this.maxWidth_ = opt_opts.maxWidth; } if (typeof opt_opts.pixelOffset !== "undefined") { this.pixelOffset_ = opt_opts.pixelOffset; } if (typeof opt_opts.alignBottom !== "undefined") { this.alignBottom_ = opt_opts.alignBottom; } if (typeof opt_opts.position !== "undefined") { this.setPosition(opt_opts.position); } if (typeof opt_opts.zIndex !== "undefined") { this.setZIndex(opt_opts.zIndex); } if (typeof opt_opts.closeBoxMargin !== "undefined") { this.closeBoxMargin_ = opt_opts.closeBoxMargin; } if (typeof opt_opts.closeBoxURL !== "undefined") { this.closeBoxURL_ = opt_opts.closeBoxURL; } if (typeof opt_opts.infoBoxClearance !== "undefined") { this.infoBoxClearance_ = opt_opts.infoBoxClearance; } if (typeof opt_opts.isHidden !== "undefined") { this.isHidden_ = opt_opts.isHidden; } if (typeof opt_opts.visible !== "undefined") { this.isHidden_ = !opt_opts.visible; } if (typeof opt_opts.enableEventPropagation !== "undefined") { this.enableEventPropagation_ = opt_opts.enableEventPropagation; } if (this.div_) { this.draw(); } }; /** * Sets the content of the InfoBox. * The content can be plain text or an HTML DOM node. * @param {string|Node} content */ InfoBox.prototype.setContent = function (content) { this.content_ = content; if (this.div_) { if (this.closeListener_) { google.maps.event.removeListener(this.closeListener_); this.closeListener_ = null; } // Odd code required to make things work with MSIE. // if (!this.fixedWidthSet_) { this.div_.style.width = ""; } if (typeof content.nodeType === "undefined") { this.div_.innerHTML = this.getCloseBoxImg_() + content; } else { this.div_.innerHTML = this.getCloseBoxImg_(); this.div_.appendChild(content); } // Perverse code required to make things work with MSIE. // (Ensures the close box does, in fact, float to the right.) // if (!this.fixedWidthSet_) { this.div_.style.width = this.div_.offsetWidth + "px"; if (typeof content.nodeType === "undefined") { this.div_.innerHTML = this.getCloseBoxImg_() + content; } else { this.div_.innerHTML = this.getCloseBoxImg_(); this.div_.appendChild(content); } } this.addClickHandler_(); } /** * This event is fired when the content of the InfoBox changes. * @name InfoBox#content_changed * @event */ google.maps.event.trigger(this, "content_changed"); }; /** * Sets the geographic location of the InfoBox. * @param {LatLng} latlng */ InfoBox.prototype.setPosition = function (latlng) { this.position_ = latlng; if (this.div_) { this.draw(); } /** * This event is fired when the position of the InfoBox changes. * @name InfoBox#position_changed * @event */ google.maps.event.trigger(this, "position_changed"); }; /** * Sets the zIndex style for the InfoBox. * @param {number} index */ InfoBox.prototype.setZIndex = function (index) { this.zIndex_ = index; if (this.div_) { this.div_.style.zIndex = index; } /** * This event is fired when the zIndex of the InfoBox changes. * @name InfoBox#zindex_changed * @event */ google.maps.event.trigger(this, "zindex_changed"); }; /** * Sets the visibility of the InfoBox. * @param {boolean} isVisible */ InfoBox.prototype.setVisible = function (isVisible) { this.isHidden_ = !isVisible; if (this.div_) { this.div_.style.visibility = (this.isHidden_ ? "hidden" : "visible"); } }; /** * Returns the content of the InfoBox. * @returns {string} */ InfoBox.prototype.getContent = function () { return this.content_; }; /** * Returns the geographic location of the InfoBox. * @returns {LatLng} */ InfoBox.prototype.getPosition = function () { return this.position_; }; /** * Returns the zIndex for the InfoBox. * @returns {number} */ InfoBox.prototype.getZIndex = function () { return this.zIndex_; }; /** * Returns a flag indicating whether the InfoBox is visible. * @returns {boolean} */ InfoBox.prototype.getVisible = function () { var isVisible; if ((typeof this.getMap() === "undefined") || (this.getMap() === null)) { isVisible = false; } else { isVisible = !this.isHidden_; } return isVisible; }; /** * Shows the InfoBox. [Deprecated; use <tt>setVisible</tt> instead.] */ InfoBox.prototype.show = function () { this.isHidden_ = false; if (this.div_) { this.div_.style.visibility = "visible"; } }; /** * Hides the InfoBox. [Deprecated; use <tt>setVisible</tt> instead.] */ InfoBox.prototype.hide = function () { this.isHidden_ = true; if (this.div_) { this.div_.style.visibility = "hidden"; } }; /** * Adds the InfoBox to the specified map or Street View panorama. If <tt>anchor</tt> * (usually a <tt>google.maps.Marker</tt>) is specified, the position * of the InfoBox is set to the position of the <tt>anchor</tt>. If the * anchor is dragged to a new location, the InfoBox moves as well. * @param {Map|StreetViewPanorama} map * @param {MVCObject} [anchor] */ InfoBox.prototype.open = function (map, anchor) { var me = this; if (anchor) { this.position_ = anchor.getPosition(); this.moveListener_ = google.maps.event.addListener(anchor, "position_changed", function () { me.setPosition(this.getPosition()); }); } this.setMap(map); if (this.div_) { this.panBox_(); } }; /** * Removes the InfoBox from the map. */ InfoBox.prototype.close = function () { var i; if (this.closeListener_) { google.maps.event.removeListener(this.closeListener_); this.closeListener_ = null; } if (this.eventListeners_) { for (i = 0; i < this.eventListeners_.length; i++) { google.maps.event.removeListener(this.eventListeners_[i]); } this.eventListeners_ = null; } if (this.moveListener_) { google.maps.event.removeListener(this.moveListener_); this.moveListener_ = null; } if (this.contextListener_) { google.maps.event.removeListener(this.contextListener_); this.contextListener_ = null; } this.setMap(null); }; /** * google-maps-utility-library-v3-keydragzoom * * @version: 2.0.9 * @author: Nianwei Liu [nianwei at gmail dot com] & Gary Little [gary at luxcentral dot com] * @contributors: undefined * @date: Fri May 13 2016 13:45:18 GMT-0400 (EDT) * @license: Apache License 2.0 */ /** * @fileoverview This library adds a drag zoom capability to a V3 Google map. * When drag zoom is enabled, holding down a designated hot key <code>(shift | ctrl | alt)</code> * while dragging a box around an area of interest will zoom the map in to that area when * the mouse button is released. Optionally, a visual control can also be supplied for turning * a drag zoom operation on and off. * Only one line of code is needed: <code>google.maps.Map.enableKeyDragZoom();</code> * <p> * NOTE: Do not use Ctrl as the hot key with Google Maps JavaScript API V3 since, unlike with V2, * it causes a context menu to appear when running on the Macintosh. * <p> * Note that if the map's container has a border around it, the border widths must be specified * in pixel units (or as thin, medium, or thick). This is required because of an MSIE limitation. * <p>NL: 2009-05-28: initial port to core API V3. * <br>NL: 2009-11-02: added a temp fix for -moz-transform for FF3.5.x using code from Paul Kulchenko (http://notebook.kulchenko.com/maps/gridmove). * <br>NL: 2010-02-02: added a fix for IE flickering on divs onmousemove, caused by scroll value when get mouse position. * <br>GL: 2010-06-15: added a visual control option. */ (function () { /*jslint browser:true */ /*global window,google */ /* Utility functions use "var funName=function()" syntax to allow use of the */ /* Dean Edwards Packer compression tool (with Shrink variables, without Base62 encode). */ /** * Converts "thin", "medium", and "thick" to pixel widths * in an MSIE environment. Not called for other browsers * because getComputedStyle() returns pixel widths automatically. * @param {string} widthValue The value of the border width parameter. */ var toPixels = function (widthValue) { var px; switch (widthValue) { case "thin": px = "2px"; break; case "medium": px = "4px"; break; case "thick": px = "6px"; break; default: px = widthValue; } return px; }; /** * Get the widths of the borders of an HTML element. * * @param {Node} h The HTML element. * @return {Object} The width object {top, bottom left, right}. */ var getBorderWidths = function (h) { var computedStyle; var bw = {}; if (document.defaultView && document.defaultView.getComputedStyle) { computedStyle = h.ownerDocument.defaultView.getComputedStyle(h, ""); if (computedStyle) { // The computed styles are always in pixel units (good!) bw.top = parseInt(computedStyle.borderTopWidth, 10) || 0; bw.bottom = parseInt(computedStyle.borderBottomWidth, 10) || 0; bw.left = parseInt(computedStyle.borderLeftWidth, 10) || 0; bw.right = parseInt(computedStyle.borderRightWidth, 10) || 0; return bw; } } else if (document.documentElement.currentStyle) { // MSIE if (h.currentStyle) { // The current styles may not be in pixel units so try to convert (bad!) bw.top = parseInt(toPixels(h.currentStyle.borderTopWidth), 10) || 0; bw.bottom = parseInt(toPixels(h.currentStyle.borderBottomWidth), 10) || 0; bw.left = parseInt(toPixels(h.currentStyle.borderLeftWidth), 10) || 0; bw.right = parseInt(toPixels(h.currentStyle.borderRightWidth), 10) || 0; return bw; } } // Shouldn't get this far for any modern browser bw.top = parseInt(h.style["border-top-width"], 10) || 0; bw.bottom = parseInt(h.style["border-bottom-width"], 10) || 0; bw.left = parseInt(h.style["border-left-width"], 10) || 0; bw.right = parseInt(h.style["border-right-width"], 10) || 0; return bw; }; // Page scroll values for use by getMousePosition. To prevent flickering on MSIE // they are calculated only when the document actually scrolls, not every time the // mouse moves (as they would be if they were calculated inside getMousePosition). var scroll = { x: 0, y: 0 }; var getScrollValue = function (e) { scroll.x = (typeof document.documentElement.scrollLeft !== "undefined" ? document.documentElement.scrollLeft : document.body.scrollLeft); scroll.y = (typeof document.documentElement.scrollTop !== "undefined" ? document.documentElement.scrollTop : document.body.scrollTop); }; getScrollValue(); /** * Get the position of the mouse relative to the document. * @param {Event} e The mouse event. * @return {Object} The position object {left, top}. */ var getMousePosition = function (e) { var posX = 0, posY = 0; e = e || window.event; if (typeof e.pageX !== "undefined") { posX = e.pageX; posY = e.pageY; } else if (typeof e.clientX !== "undefined") { // MSIE posX = e.clientX + scroll.x; posY = e.clientY + scroll.y; } return { left: posX, top: posY }; }; /** * Get the position of an HTML element relative to the document. * @param {Node} h The HTML element. * @return {Object} The position object {left, top}. */ var getElementPosition = function (h) { var posX = h.offsetLeft; var posY = h.offsetTop; var parent = h.offsetParent; // Add offsets for all ancestors in the hierarchy while (parent !== null) { // Adjust for scrolling elements which may affect the map position. // // See http://www.howtocreate.co.uk/tutorials/javascript/browserspecific // // "...make sure that every element [on a Web page] with an overflow // of anything other than visible also has a position style set to // something other than the default static..." if (parent !== document.body && parent !== document.documentElement) { posX -= parent.scrollLeft; posY -= parent.scrollTop; } // See http://groups.google.com/group/google-maps-js-api-v3/browse_thread/thread/4cb86c0c1037a5e5 // Example: http://notebook.kulchenko.com/maps/gridmove var m = parent; // This is the "normal" way to get offset information: var moffx = m.offsetLeft; var moffy = m.offsetTop; // This covers those cases where a transform is used: if (!moffx && !moffy && window.getComputedStyle) { var matrix = document.defaultView.getComputedStyle(m, null).MozTransform || document.defaultView.getComputedStyle(m, null).WebkitTransform; if (matrix) { if (typeof matrix === "string") { var parms = matrix.split(","); moffx += parseInt(parms[4], 10) || 0; moffy += parseInt(parms[5], 10) || 0; } } } posX += moffx; posY += moffy; parent = parent.offsetParent; } return { left: posX, top: posY }; }; /** * Set the properties of an object to those from another object. * @param {Object} obj The target object. * @param {Object} vals The source object. */ var setVals = function (obj, vals) { if (obj && vals) { for (var x in vals) { if (vals.hasOwnProperty(x)) { obj[x] = vals[x]; } } } return obj; }; /** * Set the opacity. If op is not passed in, this function just performs an MSIE fix. * @param {Node} h The HTML element. * @param {number} op The opacity value (0-1). */ var setOpacity = function (h, op) { if (typeof op !== "undefined") { h.style.opacity = op; } if (typeof h.style.opacity !== "undefined" && h.style.opacity !== "") { h.style.filter = "alpha(opacity=" + (h.style.opacity * 100) + ")"; } }; /** * @name KeyDragZoomOptions * @class This class represents the optional parameter passed into <code>google.maps.Map.enableKeyDragZoom</code>. * @property {string} [key="shift"] The hot key to hold down to activate a drag zoom, <code>shift | ctrl | alt</code>. * NOTE: Do not use Ctrl as the hot key with Google Maps JavaScript API V3 since, unlike with V2, * it causes a context menu to appear when running on the Macintosh. Also note that the * <code>alt</code> hot key refers to the Option key on a Macintosh. * @property {Object} [boxStyle={border: "4px solid #736AFF"}] * An object literal defining the CSS styles of the zoom box. * Border widths must be specified in pixel units (or as thin, medium, or thick). * @property {Object} [veilStyle={backgroundColor: "gray", opacity: 0.25, cursor: "crosshair"}] * An object literal defining the CSS styles of the veil pane which covers the map when a drag * zoom is activated. The previous name for this property was <code>paneStyle</code> but the use * of this name is now deprecated. * @property {boolean} [noZoom=false] A flag indicating whether to disable zooming after an area is * selected. Set this to <code>true</code> to allow KeyDragZoom to be used as a simple area * selection tool. * @property {boolean} [visualEnabled=false] A flag indicating whether a visual control is to be used. * @property {string} [visualClass=""] The name of the CSS class defining the styles for the visual * control. To prevent the visual control from being printed, set this property to the name of * a class, defined inside a <code>@media print</code> rule, which sets the CSS * <code>display</code> style to <code>none</code>. * @property {ControlPosition} [visualPosition=google.maps.ControlPosition.LEFT_TOP] * The position of the visual control. * @property {Size} [visualPositionOffset=google.maps.Size(35, 0)] The width and height values * provided by this property are the offsets (in pixels) from the location at which the control * would normally be drawn to the desired drawing location. * @property {number} [visualPositionIndex=null] The index of the visual control. * The index is for controlling the placement of the control relative to other controls at the * position given by <code>visualPosition</code>; controls with a lower index are placed first. * Use a negative value to place the control <i>before</i> any default controls. No index is * generally required. * @property {String} [visualSprite="http://maps.gstatic.com/mapfiles/ftr/controls/dragzoom_btn.png"] * The URL of the sprite image used for showing the visual control in the on, off, and hot * (i.e., when the mouse is over the control) states. The three images within the sprite must * be the same size and arranged in on-hot-off order in a single row with no spaces between images. * @property {Size} [visualSize=google.maps.Size(20, 20)] The width and height values provided by * this property are the size (in pixels) of each of the images within <code>visualSprite</code>. * @property {Object} [visualTips={off: "Turn on drag zoom mode", on: "Turn off drag zoom mode"}] * An object literal defining the help tips that appear when * the mouse moves over the visual control. The <code>off</code> property is the tip to be shown * when the control is off and the <code>on</code> property is the tip to be shown when the * control is on. */ /** * @name DragZoom * @class This class represents a drag zoom object for a map. The object is activated by holding down the hot key * or by turning on the visual control. * This object is created when <code>google.maps.Map.enableKeyDragZoom</code> is called; it cannot be created directly. * Use <code>google.maps.Map.getDragZoomObject</code> to gain access to this object in order to attach event listeners. * @param {Map} map The map to which the DragZoom object is to be attached. * @param {KeyDragZoomOptions} [opt_zoomOpts] The optional parameters. */ function DragZoom(map, opt_zoomOpts) { var me = this; var ov = new google.maps.OverlayView(); ov.onAdd = function () { me.init_(map, opt_zoomOpts); }; ov.draw = function () { }; ov.onRemove = function () { }; ov.setMap(map); this.prjov_ = ov; } /** * Initialize the tool. * @param {Map} map The map to which the DragZoom object is to be attached. * @param {KeyDragZoomOptions} [opt_zoomOpts] The optional parameters. */ DragZoom.prototype.init_ = function (map, opt_zoomOpts) { var i; var me = this; this.map_ = map; opt_zoomOpts = opt_zoomOpts || {}; this.key_ = opt_zoomOpts.key || "shift"; this.key_ = this.key_.toLowerCase(); this.borderWidths_ = getBorderWidths(this.map_.getDiv()); this.veilDiv_ = []; for (i = 0; i < 4; i++) { this.veilDiv_[i] = document.createElement("div"); // Prevents selection of other elements on the webpage // when a drag zoom operation is in progress: this.veilDiv_[i].onselectstart = function () { return false; }; // Apply default style values for the veil: setVals(this.veilDiv_[i].style, { backgroundColor: "gray", opacity: 0.25, cursor: "crosshair" }); // Apply style values specified in veilStyle parameter: setVals(this.veilDiv_[i].style, opt_zoomOpts.paneStyle); // Old option name was "paneStyle" setVals(this.veilDiv_[i].style, opt_zoomOpts.veilStyle); // New name is "veilStyle" // Apply mandatory style values: setVals(this.veilDiv_[i].style, { position: "absolute", overflow: "hidden", display: "none" }); // Workaround for Firefox Shift-Click problem: if (this.key_ === "shift") { this.veilDiv_[i].style.MozUserSelect = "none"; } setOpacity(this.veilDiv_[i]); // An IE fix: If the background is transparent it cannot capture mousedown // events, so if it is, change the background to white with 0 opacity. if (this.veilDiv_[i].style.backgroundColor === "transparent") { this.veilDiv_[i].style.backgroundColor = "white"; setOpacity(this.veilDiv_[i], 0); } this.map_.getDiv().appendChild(this.veilDiv_[i]); } this.noZoom_ = opt_zoomOpts.noZoom || false; this.visualEnabled_ = opt_zoomOpts.visualEnabled || false; this.visualClass_ = opt_zoomOpts.visualClass || ""; this.visualPosition_ = opt_zoomOpts.visualPosition || google.maps.ControlPosition.LEFT_TOP; this.visualPositionOffset_ = opt_zoomOpts.visualPositionOffset || new google.maps.Size(35, 0); this.visualPositionIndex_ = opt_zoomOpts.visualPositionIndex || null; this.visualSprite_ = opt_zoomOpts.visualSprite || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/mapfiles/ftr/controls/dragzoom_btn.png"; this.visualSize_ = opt_zoomOpts.visualSize || new google.maps.Size(20, 20); this.visualTips_ = opt_zoomOpts.visualTips || {}; this.visualTips_.off = this.visualTips_.off || "Turn on drag zoom mode"; this.visualTips_.on = this.visualTips_.on || "Turn off drag zoom mode"; this.boxDiv_ = document.createElement("div"); // Apply default style values for the zoom box: setVals(this.boxDiv_.style, { border: "4px solid #736AFF" }); // Apply style values specified in boxStyle parameter: setVals(this.boxDiv_.style, opt_zoomOpts.boxStyle); // Apply mandatory style values: setVals(this.boxDiv_.style, { position: "absolute", display: "none" }); setOpacity(this.boxDiv_); this.map_.getDiv().appendChild(this.boxDiv_); this.boxBorderWidths_ = getBorderWidths(this.boxDiv_); this.listeners_ = [ google.maps.event.addDomListener(document, "keydown", function (e) { me.onKeyDown_(e); }), google.maps.event.addDomListener(document, "keyup", function (e) { me.onKeyUp_(e); }), google.maps.event.addDomListener(this.veilDiv_[0], "mousedown", function (e) { me.onMouseDown_(e); }), google.maps.event.addDomListener(this.veilDiv_[1], "mousedown", function (e) { me.onMouseDown_(e); }), google.maps.event.addDomListener(this.veilDiv_[2], "mousedown", function (e) { me.onMouseDown_(e); }), google.maps.event.addDomListener(this.veilDiv_[3], "mousedown", function (e) { me.onMouseDown_(e); }), google.maps.event.addDomListener(document, "mousedown", function (e) { me.onMouseDownDocument_(e); }), google.maps.event.addDomListener(document, "mousemove", function (e) { me.onMouseMove_(e); }), google.maps.event.addDomListener(document, "mouseup", function (e) { me.onMouseUp_(e); }), google.maps.event.addDomListener(window, "scroll", getScrollValue) ]; this.hotKeyDown_ = false; this.mouseDown_ = false; this.dragging_ = false; this.startPt_ = null; this.endPt_ = null; this.mapWidth_ = null; this.mapHeight_ = null; this.mousePosn_ = null; this.mapPosn_ = null; if (this.visualEnabled_) { this.buttonDiv_ = this.initControl_(this.visualPositionOffset_); if (this.visualPositionIndex_ !== null) { this.buttonDiv_.index = this.visualPositionIndex_; } this.map_.controls[this.visualPosition_].push(this.buttonDiv_); this.controlIndex_ = this.map_.controls[this.visualPosition_].length - 1; } }; /** * Initializes the visual control and returns its DOM element. * @param {Size} offset The offset of the control from its normal position. * @return {Node} The DOM element containing the visual control. */ DragZoom.prototype.initControl_ = function (offset) { var control; var image; var me = this; control = document.createElement("div"); control.className = this.visualClass_; control.style.position = "relative"; control.style.overflow = "hidden"; control.style.height = this.visualSize_.height + "px"; control.style.width = this.visualSize_.width + "px"; control.title = this.visualTips_.off; image = document.createElement("img"); image.src = this.visualSprite_; image.style.position = "absolute"; image.style.left = -(this.visualSize_.width * 2) + "px"; image.style.top = 0 + "px"; control.appendChild(image); control.onclick = function (e) { me.hotKeyDown_ = !me.hotKeyDown_; if (me.hotKeyDown_) { me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 0) + "px"; me.buttonDiv_.title = me.visualTips_.on; me.activatedByControl_ = true; google.maps.event.trigger(me, "activate"); } else { me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 2) + "px"; me.buttonDiv_.title = me.visualTips_.off; google.maps.event.trigger(me, "deactivate"); } me.onMouseMove_(e); // Updates the veil }; control.onmouseover = function () { me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 1) + "px"; }; control.onmouseout = function () { if (me.hotKeyDown_) { me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 0) + "px"; me.buttonDiv_.title = me.visualTips_.on; } else { me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 2) + "px"; me.buttonDiv_.title = me.visualTips_.off; } }; control.ondragstart = function () { return false; }; setVals(control.style, { cursor: "pointer", marginTop: offset.height + "px", marginLeft: offset.width + "px" }); return control; }; /** * Returns <code>true</code> if the hot key is being pressed when an event occurs. * @param {Event} e The keyboard event. * @return {boolean} Flag indicating whether the hot key is down. */ DragZoom.prototype.isHotKeyDown_ = function (e) { var isHot; e = e || window.event; isHot = (e.shiftKey && this.key_ === "shift") || (e.altKey && this.key_ === "alt") || (e.ctrlKey && this.key_ === "ctrl"); if (!isHot) { // Need to look at keyCode for Opera because it // doesn't set the shiftKey, altKey, ctrlKey properties // unless a non-modifier event is being reported. // // See http://cross-browser.com/x/examples/shift_mode.php // Also see http://unixpapa.com/js/key.html switch (e.keyCode) { case 16: if (this.key_ === "shift") { isHot = true; } break; case 17: if (this.key_ === "ctrl") { isHot = true; } break; case 18: if (this.key_ === "alt") { isHot = true; } break; } } return isHot; }; /** * Returns <code>true</code> if the mouse is on top of the map div. * The position is captured in onMouseMove_. * @return {boolean} */ DragZoom.prototype.isMouseOnMap_ = function () { var mousePosn = this.mousePosn_; if (mousePosn) { var mapPosn = this.mapPosn_; var mapDiv = this.map_.getDiv(); return mousePosn.left > mapPosn.left && mousePosn.left < (mapPosn.left + mapDiv.offsetWidth) && mousePosn.top > mapPosn.top && mousePosn.top < (mapPosn.top + mapDiv.offsetHeight); } else { // if user never moved mouse return false; } }; /** * Show the veil if the hot key is down and the mouse is over the map, * otherwise hide the veil. */ DragZoom.prototype.setVeilVisibility_ = function () { var i; if (this.map_ && this.hotKeyDown_ && this.isMouseOnMap_()) { var mapDiv = this.map_.getDiv(); this.mapWidth_ = mapDiv.offsetWidth - (this.borderWidths_.left + this.borderWidths_.right); this.mapHeight_ = mapDiv.offsetHeight - (this.borderWidths_.top + this.borderWidths_.bottom); if (this.activatedByControl_) { // Veil covers entire map (except control) var left = parseInt(this.buttonDiv_.style.left, 10) + this.visualPositionOffset_.width; var top = parseInt(this.buttonDiv_.style.top, 10) + this.visualPositionOffset_.height; var width = this.visualSize_.width; var height = this.visualSize_.height; // Left veil rectangle: this.veilDiv_[0].style.top = "0px"; this.veilDiv_[0].style.left = "0px"; this.veilDiv_[0].style.width = left + "px"; this.veilDiv_[0].style.height = this.mapHeight_ + "px"; // Right veil rectangle: this.veilDiv_[1].style.top = "0px"; this.veilDiv_[1].style.left = (left + width) + "px"; this.veilDiv_[1].style.width = (this.mapWidth_ - (left + width)) + "px"; this.veilDiv_[1].style.height = this.mapHeight_ + "px"; // Top veil rectangle: this.veilDiv_[2].style.top = "0px"; this.veilDiv_[2].style.left = left + "px"; this.veilDiv_[2].style.width = width + "px"; this.veilDiv_[2].style.height = top + "px"; // Bottom veil rectangle: this.veilDiv_[3].style.top = (top + height) + "px"; this.veilDiv_[3].style.left = left + "px"; this.veilDiv_[3].style.width = width + "px"; this.veilDiv_[3].style.height = (this.mapHeight_ - (top + height)) + "px"; for (i = 0; i < this.veilDiv_.length; i++) { this.veilDiv_[i].style.display = "block"; } } else { this.veilDiv_[0].style.left = "0px"; this.veilDiv_[0].style.top = "0px"; this.veilDiv_[0].style.width = this.mapWidth_ + "px"; this.veilDiv_[0].style.height = this.mapHeight_ + "px"; for (i = 1; i < this.veilDiv_.length; i++) { this.veilDiv_[i].style.width = "0px"; this.veilDiv_[i].style.height = "0px"; } for (i = 0; i < this.veilDiv_.length; i++) { this.veilDiv_[i].style.display = "block"; } } } else { for (i = 0; i < this.veilDiv_.length; i++) { this.veilDiv_[i].style.display = "none"; } } }; /** * Handle key down. Show the veil if the hot key has been pressed. * @param {Event} e The keyboard event. */ DragZoom.prototype.onKeyDown_ = function (e) { if (this.map_ && !this.hotKeyDown_ && this.isHotKeyDown_(e)) { this.mapPosn_ = getElementPosition(this.map_.getDiv()); this.hotKeyDown_ = true; this.activatedByControl_ = false; this.setVeilVisibility_(); /** * This event is fired when the hot key is pressed. * @name DragZoom#activate * @event */ google.maps.event.trigger(this, "activate"); } }; /** * Get the <code>google.maps.Point</code> of the mouse position. * @param {Event} e The mouse event. * @return {Point} The mouse position. */ DragZoom.prototype.getMousePoint_ = function (e) { var mousePosn = getMousePosition(e); var p = new google.maps.Point(); p.x = mousePosn.left - this.mapPosn_.left - this.borderWidths_.left; p.y = mousePosn.top - this.mapPosn_.top - this.borderWidths_.top; p.x = Math.min(p.x, this.mapWidth_); p.y = Math.min(p.y, this.mapHeight_); p.x = Math.max(p.x, 0); p.y = Math.max(p.y, 0); return p; }; /** * Handle mouse down. * @param {Event} e The mouse event. */ DragZoom.prototype.onMouseDown_ = function (e) { if (this.map_ && this.hotKeyDown_) { this.mapPosn_ = getElementPosition(this.map_.getDiv()); this.dragging_ = true; this.startPt_ = this.endPt_ = this.getMousePoint_(e); this.boxDiv_.style.width = this.boxDiv_.style.height = "0px"; var prj = this.prjov_.getProjection(); var latlng = prj.fromContainerPixelToLatLng(this.startPt_); /** * This event is fired when the drag operation begins. * The parameter passed is the geographic position of the starting point. * @name DragZoom#dragstart * @param {LatLng} latlng The geographic position of the starting point. * @event */ google.maps.event.trigger(this, "dragstart", latlng); } }; /** * Handle mouse down at the document level. * @param {Event} e The mouse event. */ DragZoom.prototype.onMouseDownDocument_ = function (e) { this.mouseDown_ = true; }; /** * Handle mouse move. * @param {Event} e The mouse event. */ DragZoom.prototype.onMouseMove_ = function (e) { this.mousePosn_ = getMousePosition(e); if (this.dragging_) { this.endPt_ = this.getMousePoint_(e); var left = Math.min(this.startPt_.x, this.endPt_.x); var top = Math.min(this.startPt_.y, this.endPt_.y); var width = Math.abs(this.startPt_.x - this.endPt_.x); var height = Math.abs(this.startPt_.y - this.endPt_.y); // For benefit of MSIE 7/8 ensure following values are not negative: var boxWidth = Math.max(0, width - (this.boxBorderWidths_.left + this.boxBorderWidths_.right)); var boxHeight = Math.max(0, height - (this.boxBorderWidths_.top + this.boxBorderWidths_.bottom)); // Left veil rectangle: this.veilDiv_[0].style.top = "0px"; this.veilDiv_[0].style.left = "0px"; this.veilDiv_[0].style.width = left + "px"; this.veilDiv_[0].style.height = this.mapHeight_ + "px"; // Right veil rectangle: this.veilDiv_[1].style.top = "0px"; this.veilDiv_[1].style.left = (left + width) + "px"; this.veilDiv_[1].style.width = (this.mapWidth_ - (left + width)) + "px"; this.veilDiv_[1].style.height = this.mapHeight_ + "px"; // Top veil rectangle: this.veilDiv_[2].style.top = "0px"; this.veilDiv_[2].style.left = left + "px"; this.veilDiv_[2].style.width = width + "px"; this.veilDiv_[2].style.height = top + "px"; // Bottom veil rectangle: this.veilDiv_[3].style.top = (top + height) + "px"; this.veilDiv_[3].style.left = left + "px"; this.veilDiv_[3].style.width = width + "px"; this.veilDiv_[3].style.height = (this.mapHeight_ - (top + height)) + "px"; // Selection rectangle: this.boxDiv_.style.top = top + "px"; this.boxDiv_.style.left = left + "px"; this.boxDiv_.style.width = boxWidth + "px"; this.boxDiv_.style.height = boxHeight + "px"; this.boxDiv_.style.display = "block"; /** * This event is fired repeatedly while the user drags a box across the area of interest. * The southwest and northeast point are passed as parameters of type <code>google.maps.Point</code> * (for performance reasons), relative to the map container. Also passed is the projection object * so that the event listener, if necessary, can convert the pixel positions to geographic * coordinates using <code>google.maps.MapCanvasProjection.fromContainerPixelToLatLng</code>. * @name DragZoom#drag * @param {Point} southwestPixel The southwest point of the selection area. * @param {Point} northeastPixel The northeast point of the selection area. * @param {MapCanvasProjection} prj The projection object. * @event */ google.maps.event.trigger(this, "drag", new google.maps.Point(left, top + height), new google.maps.Point(left + width, top), this.prjov_.getProjection()); } else if (!this.mouseDown_) { this.mapPosn_ = getElementPosition(this.map_.getDiv()); this.setVeilVisibility_(); } }; /** * Handle mouse up. * @param {Event} e The mouse event. */ DragZoom.prototype.onMouseUp_ = function (e) { var z; var me = this; this.mouseDown_ = false; if (this.dragging_) { if ((this.getMousePoint_(e).x === this.startPt_.x) && (this.getMousePoint_(e).y === this.startPt_.y)) { this.onKeyUp_(e); // Cancel event return; } var left = Math.min(this.startPt_.x, this.endPt_.x); var top = Math.min(this.startPt_.y, this.endPt_.y); var width = Math.abs(this.startPt_.x - this.endPt_.x); var height = Math.abs(this.startPt_.y - this.endPt_.y); // Google Maps API bug: setCenter() doesn't work as expected if the map has a // border on the left or top. The code here includes a workaround for this problem. var kGoogleCenteringBug = true; if (kGoogleCenteringBug) { left += this.borderWidths_.left; top += this.borderWidths_.top; } var prj = this.prjov_.getProjection(); var sw = prj.fromContainerPixelToLatLng(new google.maps.Point(left, top + height)); var ne = prj.fromContainerPixelToLatLng(new google.maps.Point(left + width, top)); var bnds = new google.maps.LatLngBounds(sw, ne); if (this.noZoom_) { this.boxDiv_.style.display = "none"; } else { // Sometimes fitBounds causes a zoom OUT, so restore original zoom level if this happens. z = this.map_.getZoom(); this.map_.fitBounds(bnds); if (this.map_.getZoom() < z) { this.map_.setZoom(z); } // Redraw box after zoom: var swPt = prj.fromLatLngToContainerPixel(sw); var nePt = prj.fromLatLngToContainerPixel(ne); if (kGoogleCenteringBug) { swPt.x -= this.borderWidths_.left; swPt.y -= this.borderWidths_.top; nePt.x -= this.borderWidths_.left; nePt.y -= this.borderWidths_.top; } this.boxDiv_.style.left = swPt.x + "px"; this.boxDiv_.style.top = nePt.y + "px"; this.boxDiv_.style.width = (Math.abs(nePt.x - swPt.x) - (this.boxBorderWidths_.left + this.boxBorderWidths_.right)) + "px"; this.boxDiv_.style.height = (Math.abs(nePt.y - swPt.y) - (this.boxBorderWidths_.top + this.boxBorderWidths_.bottom)) + "px"; // Hide box asynchronously after 1 second: setTimeout(function () { me.boxDiv_.style.display = "none"; }, 1000); } this.dragging_ = false; this.onMouseMove_(e); // Updates the veil /** * This event is fired when the drag operation ends. * The parameter passed is the geographic bounds of the selected area. * Note that this event is <i>not</i> fired if the hot key is released before the drag operation ends. * @name DragZoom#dragend * @param {LatLngBounds} bnds The geographic bounds of the selected area. * @event */ google.maps.event.trigger(this, "dragend", bnds); // if the hot key isn't down, the drag zoom must have been activated by turning // on the visual control. In this case, finish up by simulating a key up event. if (!this.isHotKeyDown_(e)) { this.onKeyUp_(e); } } }; /** * Handle key up. * @param {Event} e The keyboard event. */ DragZoom.prototype.onKeyUp_ = function (e) { var i; var left, top, width, height, prj, sw, ne; var bnds = null; if (this.map_ && this.hotKeyDown_) { this.hotKeyDown_ = false; if (this.dragging_) { this.boxDiv_.style.display = "none"; this.dragging_ = false; // Calculate the bounds when drag zoom was cancelled left = Math.min(this.startPt_.x, this.endPt_.x); top = Math.min(this.startPt_.y, this.endPt_.y); width = Math.abs(this.startPt_.x - this.endPt_.x); height = Math.abs(this.startPt_.y - this.endPt_.y); prj = this.prjov_.getProjection(); sw = prj.fromContainerPixelToLatLng(new google.maps.Point(left, top + height)); ne = prj.fromContainerPixelToLatLng(new google.maps.Point(left + width, top)); bnds = new google.maps.LatLngBounds(sw, ne); } for (i = 0; i < this.veilDiv_.length; i++) { this.veilDiv_[i].style.display = "none"; } if (this.visualEnabled_) { this.buttonDiv_.firstChild.style.left = -(this.visualSize_.width * 2) + "px"; this.buttonDiv_.title = this.visualTips_.off; this.buttonDiv_.style.display = ""; } /** * This event is fired when the hot key is released. * The parameter passed is the geographic bounds of the selected area immediately * before the hot key was released. * @name DragZoom#deactivate * @param {LatLngBounds} bnds The geographic bounds of the selected area immediately * before the hot key was released. * @event */ google.maps.event.trigger(this, "deactivate", bnds); } }; /** * @name google.maps.Map * @class These are new methods added to the Google Maps JavaScript API V3's * <a href="http://code.google.com/apis/maps/documentation/javascript/reference.html#Map">Map</a> * class. */ /** * Enables drag zoom. The user can zoom to an area of interest by holding down the hot key * <code>(shift | ctrl | alt )</code> while dragging a box around the area or by turning * on the visual control then dragging a box around the area. * @param {KeyDragZoomOptions} opt_zoomOpts The optional parameters. */ google.maps.Map.prototype.enableKeyDragZoom = function (opt_zoomOpts) { this.dragZoom_ = new DragZoom(this, opt_zoomOpts); }; /** * Disables drag zoom. */ google.maps.Map.prototype.disableKeyDragZoom = function () { var i; var d = this.dragZoom_; if (d) { for (i = 0; i < d.listeners_.length; ++i) { google.maps.event.removeListener(d.listeners_[i]); } this.getDiv().removeChild(d.boxDiv_); for (i = 0; i < d.veilDiv_.length; i++) { this.getDiv().removeChild(d.veilDiv_[i]); } if (d.visualEnabled_) { // Remove the custom control: this.controls[d.visualPosition_].removeAt(d.controlIndex_); } d.prjov_.setMap(null); this.dragZoom_ = null; } }; /** * Returns <code>true</code> if the drag zoom feature has been enabled. * @return {boolean} */ google.maps.Map.prototype.keyDragZoomEnabled = function () { return this.dragZoom_ !== null; }; /** * Returns the DragZoom object which is created when <code>google.maps.Map.enableKeyDragZoom</code> is called. * With this object you can use <code>google.maps.event.addListener</code> to attach event listeners * for the "activate", "deactivate", "dragstart", "drag", and "dragend" events. * @return {DragZoom} */ google.maps.Map.prototype.getDragZoomObject = function () { return this.dragZoom_; }; })(); /** * google-maps-utility-library-v3-markerwithlabel * * @version: 1.1.10 * @author: Gary Little (inspired by code from Marc Ridey of Google). * @contributors: Nicholas McCready * @date: Fri May 13 2016 16:29:58 GMT-0400 (EDT) * @license: Apache License 2.0 */ /** * MarkerWithLabel allows you to define markers with associated labels. As you would expect, * if the marker is draggable, so too will be the label. In addition, a marker with a label * responds to all mouse events in the same manner as a regular marker. It also fires mouse * events and "property changed" events just as a regular marker would. Version 1.1 adds * support for the raiseOnDrag feature introduced in API V3.3. * <p> * If you drag a marker by its label, you can cancel the drag and return the marker to its * original position by pressing the <code>Esc</code> key. This doesn't work if you drag the marker * itself because this feature is not (yet) supported in the <code>google.maps.Marker</code> class. */ /*jslint browser:true */ /*global document,google */ /** * @param {Function} childCtor Child class. * @param {Function} parentCtor Parent class. * @private */ function inherits(childCtor, parentCtor) { /* @constructor */ function tempCtor() {} tempCtor.prototype = parentCtor.prototype; childCtor.superClass_ = parentCtor.prototype; childCtor.prototype = new tempCtor(); /* @override */ childCtor.prototype.constructor = childCtor; } /** * This constructor creates a label and associates it with a marker. * It is for the private use of the MarkerWithLabel class. * @constructor * @param {Marker} marker The marker with which the label is to be associated. * @param {string} crossURL The URL of the cross image =. * @param {string} handCursor The URL of the hand cursor. * @private */ function MarkerLabel_(marker, crossURL, handCursorURL) { this.marker_ = marker; this.handCursorURL_ = marker.handCursorURL; this.labelDiv_ = document.createElement("div"); this.labelDiv_.style.cssText = "position: absolute; overflow: hidden;"; // Set up the DIV for handling mouse events in the label. This DIV forms a transparent veil // in the "overlayMouseTarget" pane, a veil that covers just the label. This is done so that // events can be captured even if the label is in the shadow of a google.maps.InfoWindow. // Code is included here to ensure the veil is always exactly the same size as the label. this.eventDiv_ = document.createElement("div"); this.eventDiv_.style.cssText = this.labelDiv_.style.cssText; // This is needed for proper behavior on MSIE: this.eventDiv_.setAttribute("onselectstart", "return false;"); this.eventDiv_.setAttribute("ondragstart", "return false;"); // Get the DIV for the "X" to be displayed when the marker is raised. this.crossDiv_ = MarkerLabel_.getSharedCross(crossURL); } inherits(MarkerLabel_, google.maps.OverlayView); /** * Returns the DIV for the cross used when dragging a marker when the * raiseOnDrag parameter set to true. One cross is shared with all markers. * @param {string} crossURL The URL of the cross image =. * @private */ MarkerLabel_.getSharedCross = function (crossURL) { var div; if (typeof MarkerLabel_.getSharedCross.crossDiv === "undefined") { div = document.createElement("img"); div.style.cssText = "position: absolute; z-index: 1000002; display: none;"; // Hopefully Google never changes the standard "X" attributes: div.style.marginLeft = "-8px"; div.style.marginTop = "-9px"; div.src = crossURL; MarkerLabel_.getSharedCross.crossDiv = div; } return MarkerLabel_.getSharedCross.crossDiv; }; /** * Adds the DIV representing the label to the DOM. This method is called * automatically when the marker's <code>setMap</code> method is called. * @private */ MarkerLabel_.prototype.onAdd = function () { var me = this; var cMouseIsDown = false; var cDraggingLabel = false; var cSavedZIndex; var cLatOffset, cLngOffset; var cIgnoreClick; var cRaiseEnabled; var cStartPosition; var cStartCenter; // Constants: var cRaiseOffset = 20; var cDraggingCursor = "url(" + this.handCursorURL_ + ")"; // Stops all processing of an event. // var cAbortEvent = function (e) { if (e.preventDefault) { e.preventDefault(); } e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } }; var cStopBounce = function () { me.marker_.setAnimation(null); }; this.getPanes().overlayImage.appendChild(this.labelDiv_); this.getPanes().overlayMouseTarget.appendChild(this.eventDiv_); // One cross is shared with all markers, so only add it once: if (typeof MarkerLabel_.getSharedCross.processed === "undefined") { this.getPanes().overlayImage.appendChild(this.crossDiv_); MarkerLabel_.getSharedCross.processed = true; } this.listeners_ = [ google.maps.event.addDomListener(this.eventDiv_, "mouseover", function (e) { if (me.marker_.getDraggable() || me.marker_.getClickable()) { this.style.cursor = "pointer"; google.maps.event.trigger(me.marker_, "mouseover", e); } }), google.maps.event.addDomListener(this.eventDiv_, "mouseout", function (e) { if ((me.marker_.getDraggable() || me.marker_.getClickable()) && !cDraggingLabel) { this.style.cursor = me.marker_.getCursor(); google.maps.event.trigger(me.marker_, "mouseout", e); } }), google.maps.event.addDomListener(this.eventDiv_, "mousedown", function (e) { cDraggingLabel = false; if (me.marker_.getDraggable()) { cMouseIsDown = true; this.style.cursor = cDraggingCursor; } if (me.marker_.getDraggable() || me.marker_.getClickable()) { google.maps.event.trigger(me.marker_, "mousedown", e); cAbortEvent(e); // Prevent map pan when starting a drag on a label } }), google.maps.event.addDomListener(document, "mouseup", function (mEvent) { var position; if (cMouseIsDown) { cMouseIsDown = false; me.eventDiv_.style.cursor = "pointer"; google.maps.event.trigger(me.marker_, "mouseup", mEvent); } if (cDraggingLabel) { if (cRaiseEnabled) { // Lower the marker & label position = me.getProjection().fromLatLngToDivPixel(me.marker_.getPosition()); position.y += cRaiseOffset; me.marker_.setPosition(me.getProjection().fromDivPixelToLatLng(position)); // This is not the same bouncing style as when the marker portion is dragged, // but it will have to do: try { // Will fail if running Google Maps API earlier than V3.3 me.marker_.setAnimation(google.maps.Animation.BOUNCE); setTimeout(cStopBounce, 1406); } catch (e) {} } me.crossDiv_.style.display = "none"; me.marker_.setZIndex(cSavedZIndex); cIgnoreClick = true; // Set flag to ignore the click event reported after a label drag cDraggingLabel = false; mEvent.latLng = me.marker_.getPosition(); google.maps.event.trigger(me.marker_, "dragend", mEvent); } }), google.maps.event.addListener(me.marker_.getMap(), "mousemove", function (mEvent) { var position; if (cMouseIsDown) { if (cDraggingLabel) { // Change the reported location from the mouse position to the marker position: mEvent.latLng = new google.maps.LatLng(mEvent.latLng.lat() - cLatOffset, mEvent.latLng.lng() - cLngOffset); position = me.getProjection().fromLatLngToDivPixel(mEvent.latLng); if (cRaiseEnabled) { me.crossDiv_.style.left = position.x + "px"; me.crossDiv_.style.top = position.y + "px"; me.crossDiv_.style.display = ""; position.y -= cRaiseOffset; } me.marker_.setPosition(me.getProjection().fromDivPixelToLatLng(position)); if (cRaiseEnabled) { // Don't raise the veil; this hack needed to make MSIE act properly me.eventDiv_.style.top = (position.y + cRaiseOffset) + "px"; } google.maps.event.trigger(me.marker_, "drag", mEvent); } else { // Calculate offsets from the click point to the marker position: cLatOffset = mEvent.latLng.lat() - me.marker_.getPosition().lat(); cLngOffset = mEvent.latLng.lng() - me.marker_.getPosition().lng(); cSavedZIndex = me.marker_.getZIndex(); cStartPosition = me.marker_.getPosition(); cStartCenter = me.marker_.getMap().getCenter(); cRaiseEnabled = me.marker_.get("raiseOnDrag"); cDraggingLabel = true; me.marker_.setZIndex(1000000); // Moves the marker & label to the foreground during a drag mEvent.latLng = me.marker_.getPosition(); google.maps.event.trigger(me.marker_, "dragstart", mEvent); } } }), google.maps.event.addDomListener(document, "keydown", function (e) { if (cDraggingLabel) { if (e.keyCode === 27) { // Esc key cRaiseEnabled = false; me.marker_.setPosition(cStartPosition); me.marker_.getMap().setCenter(cStartCenter); google.maps.event.trigger(document, "mouseup", e); } } }), google.maps.event.addDomListener(this.eventDiv_, "click", function (e) { if (me.marker_.getDraggable() || me.marker_.getClickable()) { if (cIgnoreClick) { // Ignore the click reported when a label drag ends cIgnoreClick = false; } else { google.maps.event.trigger(me.marker_, "click", e); cAbortEvent(e); // Prevent click from being passed on to map } } }), google.maps.event.addDomListener(this.eventDiv_, "dblclick", function (e) { if (me.marker_.getDraggable() || me.marker_.getClickable()) { google.maps.event.trigger(me.marker_, "dblclick", e); cAbortEvent(e); // Prevent map zoom when double-clicking on a label } }), google.maps.event.addListener(this.marker_, "dragstart", function (mEvent) { if (!cDraggingLabel) { cRaiseEnabled = this.get("raiseOnDrag"); } }), google.maps.event.addListener(this.marker_, "drag", function (mEvent) { if (!cDraggingLabel) { if (cRaiseEnabled) { me.setPosition(cRaiseOffset); // During a drag, the marker's z-index is temporarily set to 1000000 to // ensure it appears above all other markers. Also set the label's z-index // to 1000000 (plus or minus 1 depending on whether the label is supposed // to be above or below the marker). me.labelDiv_.style.zIndex = 1000000 + (this.get("labelInBackground") ? -1 : +1); } } }), google.maps.event.addListener(this.marker_, "dragend", function (mEvent) { if (!cDraggingLabel) { if (cRaiseEnabled) { me.setPosition(0); // Also restores z-index of label } } }), google.maps.event.addListener(this.marker_, "position_changed", function () { me.setPosition(); }), google.maps.event.addListener(this.marker_, "zindex_changed", function () { me.setZIndex(); }), google.maps.event.addListener(this.marker_, "visible_changed", function () { me.setVisible(); }), google.maps.event.addListener(this.marker_, "labelvisible_changed", function () { me.setVisible(); }), google.maps.event.addListener(this.marker_, "title_changed", function () { me.setTitle(); }), google.maps.event.addListener(this.marker_, "labelcontent_changed", function () { me.setContent(); }), google.maps.event.addListener(this.marker_, "labelanchor_changed", function () { me.setAnchor(); }), google.maps.event.addListener(this.marker_, "labelclass_changed", function () { me.setStyles(); }), google.maps.event.addListener(this.marker_, "labelstyle_changed", function () { me.setStyles(); }) ]; }; /** * Removes the DIV for the label from the DOM. It also removes all event handlers. * This method is called automatically when the marker's <code>setMap(null)</code> * method is called. * @private */ MarkerLabel_.prototype.onRemove = function () { var i; this.labelDiv_.parentNode.removeChild(this.labelDiv_); this.eventDiv_.parentNode.removeChild(this.eventDiv_); // Remove event listeners: for (i = 0; i < this.listeners_.length; i++) { google.maps.event.removeListener(this.listeners_[i]); } }; /** * Draws the label on the map. * @private */ MarkerLabel_.prototype.draw = function () { this.setContent(); this.setTitle(); this.setStyles(); }; /** * Sets the content of the label. * The content can be plain text or an HTML DOM node. * @private */ MarkerLabel_.prototype.setContent = function () { var content = this.marker_.get("labelContent"); if (typeof content.nodeType === "undefined") { this.labelDiv_.innerHTML = content; this.eventDiv_.innerHTML = this.labelDiv_.innerHTML; } else { this.labelDiv_.innerHTML = ""; // Remove current content this.labelDiv_.appendChild(content); content = content.cloneNode(true); this.eventDiv_.innerHTML = ""; // Remove current content this.eventDiv_.appendChild(content); } }; /** * Sets the content of the tool tip for the label. It is * always set to be the same as for the marker itself. * @private */ MarkerLabel_.prototype.setTitle = function () { this.eventDiv_.title = this.marker_.getTitle() || ""; }; /** * Sets the style of the label by setting the style sheet and applying * other specific styles requested. * @private */ MarkerLabel_.prototype.setStyles = function () { var i, labelStyle; // Apply style values from the style sheet defined in the labelClass parameter: this.labelDiv_.className = this.marker_.get("labelClass"); this.eventDiv_.className = this.labelDiv_.className; // Clear existing inline style values: this.labelDiv_.style.cssText = ""; this.eventDiv_.style.cssText = ""; // Apply style values defined in the labelStyle parameter: labelStyle = this.marker_.get("labelStyle"); for (i in labelStyle) { if (labelStyle.hasOwnProperty(i)) { this.labelDiv_.style[i] = labelStyle[i]; this.eventDiv_.style[i] = labelStyle[i]; } } this.setMandatoryStyles(); }; /** * Sets the mandatory styles to the DIV representing the label as well as to the * associated event DIV. This includes setting the DIV position, z-index, and visibility. * @private */ MarkerLabel_.prototype.setMandatoryStyles = function () { this.labelDiv_.style.position = "absolute"; this.labelDiv_.style.overflow = "hidden"; // Make sure the opacity setting causes the desired effect on MSIE: if (typeof this.labelDiv_.style.opacity !== "undefined" && this.labelDiv_.style.opacity !== "") { this.labelDiv_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(opacity=" + (this.labelDiv_.style.opacity * 100) + ")\""; this.labelDiv_.style.filter = "alpha(opacity=" + (this.labelDiv_.style.opacity * 100) + ")"; } this.eventDiv_.style.position = this.labelDiv_.style.position; this.eventDiv_.style.overflow = this.labelDiv_.style.overflow; this.eventDiv_.style.opacity = 0.01; // Don't use 0; DIV won't be clickable on MSIE this.eventDiv_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(opacity=1)\""; this.eventDiv_.style.filter = "alpha(opacity=1)"; // For MSIE this.setAnchor(); this.setPosition(); // This also updates z-index, if necessary. this.setVisible(); }; /** * Sets the anchor point of the label. * @private */ MarkerLabel_.prototype.setAnchor = function () { var anchor = this.marker_.get("labelAnchor"); this.labelDiv_.style.marginLeft = -anchor.x + "px"; this.labelDiv_.style.marginTop = -anchor.y + "px"; this.eventDiv_.style.marginLeft = -anchor.x + "px"; this.eventDiv_.style.marginTop = -anchor.y + "px"; }; /** * Sets the position of the label. The z-index is also updated, if necessary. * @private */ MarkerLabel_.prototype.setPosition = function (yOffset) { var position = this.getProjection().fromLatLngToDivPixel(this.marker_.getPosition()); if (typeof yOffset === "undefined") { yOffset = 0; } this.labelDiv_.style.left = Math.round(position.x) + "px"; this.labelDiv_.style.top = Math.round(position.y - yOffset) + "px"; this.eventDiv_.style.left = this.labelDiv_.style.left; this.eventDiv_.style.top = this.labelDiv_.style.top; this.setZIndex(); }; /** * Sets the z-index of the label. If the marker's z-index property has not been defined, the z-index * of the label is set to the vertical coordinate of the label. This is in keeping with the default * stacking order for Google Maps: markers to the south are in front of markers to the north. * @private */ MarkerLabel_.prototype.setZIndex = function () { var zAdjust = (this.marker_.get("labelInBackground") ? -1 : +1); if (typeof this.marker_.getZIndex() === "undefined") { this.labelDiv_.style.zIndex = parseInt(this.labelDiv_.style.top, 10) + zAdjust; this.eventDiv_.style.zIndex = this.labelDiv_.style.zIndex; } else { this.labelDiv_.style.zIndex = this.marker_.getZIndex() + zAdjust; this.eventDiv_.style.zIndex = this.labelDiv_.style.zIndex; } }; /** * Sets the visibility of the label. The label is visible only if the marker itself is * visible (i.e., its visible property is true) and the labelVisible property is true. * @private */ MarkerLabel_.prototype.setVisible = function () { if (this.marker_.get("labelVisible")) { this.labelDiv_.style.display = this.marker_.getVisible() ? "block" : "none"; } else { this.labelDiv_.style.display = "none"; } this.eventDiv_.style.display = this.labelDiv_.style.display; }; /** * @name MarkerWithLabelOptions * @class This class represents the optional parameter passed to the {@link MarkerWithLabel} constructor. * The properties available are the same as for <code>google.maps.Marker</code> with the addition * of the properties listed below. To change any of these additional properties after the labeled * marker has been created, call <code>google.maps.Marker.set(propertyName, propertyValue)</code>. * <p> * When any of these properties changes, a property changed event is fired. The names of these * events are derived from the name of the property and are of the form <code>propertyname_changed</code>. * For example, if the content of the label changes, a <code>labelcontent_changed</code> event * is fired. * <p> * @property {string|Node} [labelContent] The content of the label (plain text or an HTML DOM node). * @property {Point} [labelAnchor] By default, a label is drawn with its anchor point at (0,0) so * that its top left corner is positioned at the anchor point of the associated marker. Use this * property to change the anchor point of the label. For example, to center a 50px-wide label * beneath a marker, specify a <code>labelAnchor</code> of <code>google.maps.Point(25, 0)</code>. * (Note: x-values increase to the right and y-values increase to the top.) * @property {string} [labelClass] The name of the CSS class defining the styles for the label. * Note that style values for <code>position</code>, <code>overflow</code>, <code>top</code>, * <code>left</code>, <code>zIndex</code>, <code>display</code>, <code>marginLeft</code>, and * <code>marginTop</code> are ignored; these styles are for internal use only. * @property {Object} [labelStyle] An object literal whose properties define specific CSS * style values to be applied to the label. Style values defined here override those that may * be defined in the <code>labelClass</code> style sheet. If this property is changed after the * label has been created, all previously set styles (except those defined in the style sheet) * are removed from the label before the new style values are applied. * Note that style values for <code>position</code>, <code>overflow</code>, <code>top</code>, * <code>left</code>, <code>zIndex</code>, <code>display</code>, <code>marginLeft</code>, and * <code>marginTop</code> are ignored; these styles are for internal use only. * @property {boolean} [labelInBackground] A flag indicating whether a label that overlaps its * associated marker should appear in the background (i.e., in a plane below the marker). * The default is <code>false</code>, which causes the label to appear in the foreground. * @property {boolean} [labelVisible] A flag indicating whether the label is to be visible. * The default is <code>true</code>. Note that even if <code>labelVisible</code> is * <code>true</code>, the label will <i>not</i> be visible unless the associated marker is also * visible (i.e., unless the marker's <code>visible</code> property is <code>true</code>). * @property {boolean} [raiseOnDrag] A flag indicating whether the label and marker are to be * raised when the marker is dragged. The default is <code>true</code>. If a draggable marker is * being created and a version of Google Maps API earlier than V3.3 is being used, this property * must be set to <code>false</code>. * @property {boolean} [optimized] A flag indicating whether rendering is to be optimized for the * marker. <b>Important: The optimized rendering technique is not supported by MarkerWithLabel, * so the value of this parameter is always forced to <code>false</code>. * @property {string} [crossImage="http://maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png"] * The URL of the cross image to be displayed while dragging a marker. * @property {string} [handCursor="http://maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur"] * The URL of the cursor to be displayed while dragging a marker. */ /** * Creates a MarkerWithLabel with the options specified in {@link MarkerWithLabelOptions}. * @constructor * @param {MarkerWithLabelOptions} [opt_options] The optional parameters. */ function MarkerWithLabel(opt_options) { opt_options = opt_options || {}; opt_options.labelContent = opt_options.labelContent || ""; opt_options.labelAnchor = opt_options.labelAnchor || new google.maps.Point(0, 0); opt_options.labelClass = opt_options.labelClass || "markerLabels"; opt_options.labelStyle = opt_options.labelStyle || {}; opt_options.labelInBackground = opt_options.labelInBackground || false; if (typeof opt_options.labelVisible === "undefined") { opt_options.labelVisible = true; } if (typeof opt_options.raiseOnDrag === "undefined") { opt_options.raiseOnDrag = true; } if (typeof opt_options.clickable === "undefined") { opt_options.clickable = true; } if (typeof opt_options.draggable === "undefined") { opt_options.draggable = false; } if (typeof opt_options.optimized === "undefined") { opt_options.optimized = false; } opt_options.crossImage = opt_options.crossImage || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png"; opt_options.handCursor = opt_options.handCursor || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur"; opt_options.optimized = false; // Optimized rendering is not supported this.label = new MarkerLabel_(this, opt_options.crossImage, opt_options.handCursor); // Bind the label to the marker // Call the parent constructor. It calls Marker.setValues to initialize, so all // the new parameters are conveniently saved and can be accessed with get/set. // Marker.set triggers a property changed event (called "propertyname_changed") // that the marker label listens for in order to react to state changes. google.maps.Marker.apply(this, arguments); } inherits(MarkerWithLabel, google.maps.Marker); /** * Overrides the standard Marker setMap function. * @param {Map} theMap The map to which the marker is to be added. * @private */ MarkerWithLabel.prototype.setMap = function (theMap) { // Call the inherited function... google.maps.Marker.prototype.setMap.apply(this, arguments); // ... then deal with the label: this.label.setMap(theMap); }; // ==ClosureCompiler== // @compilation_level ADVANCED_OPTIMIZATIONS // @externs_url http://closure-compiler.googlecode.com/svn/trunk/contrib/externs/maps/google_maps_api_v3.js // @output_wrapper (function() {%output%})(); // ==/ClosureCompiler== /** * @license * Copyright 2013 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * A RichMarker that allows any HTML/DOM to be added to a map and be draggable. * * @param {Object.<string, *>=} opt_options Optional properties to set. * @extends {google.maps.OverlayView} * @constructor */ function RichMarker(opt_options) { var options = opt_options || {}; /** * @type {boolean} * @private */ this.ready_ = false; /** * @type {boolean} * @private */ this.dragging_ = false; if (opt_options['visible'] == undefined) { opt_options['visible'] = true; } if (opt_options['shadow'] == undefined) { opt_options['shadow'] = '7px -3px 5px rgba(88,88,88,0.7)'; } if (opt_options['anchor'] == undefined) { opt_options['anchor'] = RichMarkerPosition['BOTTOM']; } this.setValues(options); } RichMarker.prototype = new google.maps.OverlayView(); window['RichMarker'] = RichMarker; /** * Returns the current visibility state of the marker. * * @return {boolean} The visiblity of the marker. */ RichMarker.prototype.getVisible = function() { return /** @type {boolean} */ (this.get('visible')); }; RichMarker.prototype['getVisible'] = RichMarker.prototype.getVisible; /** * Sets the visiblility state of the marker. * * @param {boolean} visible The visiblilty of the marker. */ RichMarker.prototype.setVisible = function(visible) { this.set('visible', visible); }; RichMarker.prototype['setVisible'] = RichMarker.prototype.setVisible; /** * The visible changed event. */ RichMarker.prototype.visible_changed = function() { if (this.ready_) { this.markerWrapper_.style['display'] = this.getVisible() ? '' : 'none'; this.draw(); } }; RichMarker.prototype['visible_changed'] = RichMarker.prototype.visible_changed; /** * Sets the marker to be flat. * * @param {boolean} flat If the marker is to be flat or not. */ RichMarker.prototype.setFlat = function(flat) { this.set('flat', !!flat); }; RichMarker.prototype['setFlat'] = RichMarker.prototype.setFlat; /** * If the makrer is flat or not. * * @return {boolean} True the marker is flat. */ RichMarker.prototype.getFlat = function() { return /** @type {boolean} */ (this.get('flat')); }; RichMarker.prototype['getFlat'] = RichMarker.prototype.getFlat; /** * Get the width of the marker. * * @return {Number} The width of the marker. */ RichMarker.prototype.getWidth = function() { return /** @type {Number} */ (this.get('width')); }; RichMarker.prototype['getWidth'] = RichMarker.prototype.getWidth; /** * Get the height of the marker. * * @return {Number} The height of the marker. */ RichMarker.prototype.getHeight = function() { return /** @type {Number} */ (this.get('height')); }; RichMarker.prototype['getHeight'] = RichMarker.prototype.getHeight; /** * Sets the marker's box shadow. * * @param {string} shadow The box shadow to set. */ RichMarker.prototype.setShadow = function(shadow) { this.set('shadow', shadow); this.flat_changed(); }; RichMarker.prototype['setShadow'] = RichMarker.prototype.setShadow; /** * Gets the marker's box shadow. * * @return {string} The box shadow. */ RichMarker.prototype.getShadow = function() { return /** @type {string} */ (this.get('shadow')); }; RichMarker.prototype['getShadow'] = RichMarker.prototype.getShadow; /** * Flat changed event. */ RichMarker.prototype.flat_changed = function() { if (!this.ready_) { return; } this.markerWrapper_.style['boxShadow'] = this.markerWrapper_.style['webkitBoxShadow'] = this.markerWrapper_.style['MozBoxShadow'] = this.getFlat() ? '' : this.getShadow(); }; RichMarker.prototype['flat_changed'] = RichMarker.prototype.flat_changed; /** * Sets the zIndex of the marker. * * @param {Number} index The index to set. */ RichMarker.prototype.setZIndex = function(index) { this.set('zIndex', index); }; RichMarker.prototype['setZIndex'] = RichMarker.prototype.setZIndex; /** * Gets the zIndex of the marker. * * @return {Number} The zIndex of the marker. */ RichMarker.prototype.getZIndex = function() { return /** @type {Number} */ (this.get('zIndex')); }; RichMarker.prototype['getZIndex'] = RichMarker.prototype.getZIndex; /** * zIndex changed event. */ RichMarker.prototype.zIndex_changed = function() { if (this.getZIndex() && this.ready_) { this.markerWrapper_.style.zIndex = this.getZIndex(); } }; RichMarker.prototype['zIndex_changed'] = RichMarker.prototype.zIndex_changed; /** * Whether the marker is draggable or not. * * @return {boolean} True if the marker is draggable. */ RichMarker.prototype.getDraggable = function() { return /** @type {boolean} */ (this.get('draggable')); }; RichMarker.prototype['getDraggable'] = RichMarker.prototype.getDraggable; /** * Sets the marker to be draggable or not. * * @param {boolean} draggable If the marker is draggable or not. */ RichMarker.prototype.setDraggable = function(draggable) { this.set('draggable', !!draggable); }; RichMarker.prototype['setDraggable'] = RichMarker.prototype.setDraggable; /** * Draggable property changed callback. */ RichMarker.prototype.draggable_changed = function() { if (this.ready_) { if (this.getDraggable()) { this.addDragging_(this.markerWrapper_); } else { this.removeDragListeners_(); } } }; RichMarker.prototype['draggable_changed'] = RichMarker.prototype.draggable_changed; /** * Gets the postiton of the marker. * * @return {google.maps.LatLng} The position of the marker. */ RichMarker.prototype.getPosition = function() { return /** @type {google.maps.LatLng} */ (this.get('position')); }; RichMarker.prototype['getPosition'] = RichMarker.prototype.getPosition; /** * Sets the position of the marker. * * @param {google.maps.LatLng} position The position to set. */ RichMarker.prototype.setPosition = function(position) { this.set('position', position); }; RichMarker.prototype['setPosition'] = RichMarker.prototype.setPosition; /** * Position changed event. */ RichMarker.prototype.position_changed = function() { this.draw(); }; RichMarker.prototype['position_changed'] = RichMarker.prototype.position_changed; /** * Gets the anchor. * * @return {google.maps.Size} The position of the anchor. */ RichMarker.prototype.getAnchor = function() { return /** @type {google.maps.Size} */ (this.get('anchor')); }; RichMarker.prototype['getAnchor'] = RichMarker.prototype.getAnchor; /** * Sets the anchor. * * @param {RichMarkerPosition|google.maps.Size} anchor The anchor to set. */ RichMarker.prototype.setAnchor = function(anchor) { this.set('anchor', anchor); }; RichMarker.prototype['setAnchor'] = RichMarker.prototype.setAnchor; /** * Anchor changed event. */ RichMarker.prototype.anchor_changed = function() { this.draw(); }; RichMarker.prototype['anchor_changed'] = RichMarker.prototype.anchor_changed; /** * Converts a HTML string to a document fragment. * * @param {string} htmlString The HTML string to convert. * @return {Node} A HTML document fragment. * @private */ RichMarker.prototype.htmlToDocumentFragment_ = function(htmlString) { var tempDiv = document.createElement('DIV'); tempDiv.innerHTML = htmlString; if (tempDiv.childNodes.length == 1) { return /** @type {!Node} */ (tempDiv.removeChild(tempDiv.firstChild)); } else { var fragment = document.createDocumentFragment(); while (tempDiv.firstChild) { fragment.appendChild(tempDiv.firstChild); } return fragment; } }; /** * Removes all children from the node. * * @param {Node} node The node to remove all children from. * @private */ RichMarker.prototype.removeChildren_ = function(node) { if (!node) { return; } var child; while (child = node.firstChild) { node.removeChild(child); } }; /** * Sets the content of the marker. * * @param {string|Node} content The content to set. */ RichMarker.prototype.setContent = function(content) { this.set('content', content); }; RichMarker.prototype['setContent'] = RichMarker.prototype.setContent; /** * Get the content of the marker. * * @return {string|Node} The marker content. */ RichMarker.prototype.getContent = function() { return /** @type {Node|string} */ (this.get('content')); }; RichMarker.prototype['getContent'] = RichMarker.prototype.getContent; /** * Sets the marker content and adds loading events to images */ RichMarker.prototype.content_changed = function() { if (!this.markerContent_) { // Marker content area doesnt exist. return; } this.removeChildren_(this.markerContent_); var content = this.getContent(); if (content) { if (typeof content == 'string') { content = content.replace(/^\s*([\S\s]*)\b\s*$/, '$1'); content = this.htmlToDocumentFragment_(content); } this.markerContent_.appendChild(content); var that = this; var images = this.markerContent_.getElementsByTagName('IMG'); for (var i = 0, image; image = images[i]; i++) { // By default, a browser lets a image be dragged outside of the browser, // so by calling preventDefault we stop this behaviour and allow the image // to be dragged around the map and now out of the browser and onto the // desktop. google.maps.event.addDomListener(image, 'mousedown', function(e) { if (that.getDraggable()) { if (e.preventDefault) { e.preventDefault(); } e.returnValue = false; } }); // Because we don't know the size of an image till it loads, add a // listener to the image load so the marker can resize and reposition // itself to be the correct height. google.maps.event.addDomListener(image, 'load', function() { that.draw(); }); } google.maps.event.trigger(this, 'domready'); } if (this.ready_) { this.draw(); } }; RichMarker.prototype['content_changed'] = RichMarker.prototype.content_changed; /** * Sets the cursor. * * @param {string} whichCursor What cursor to show. * @private */ RichMarker.prototype.setCursor_ = function(whichCursor) { if (!this.ready_) { return; } var cursor = ''; if (navigator.userAgent.indexOf('Gecko/') !== -1) { // Moz has some nice cursors :) if (whichCursor == 'dragging') { cursor = '-moz-grabbing'; } if (whichCursor == 'dragready') { cursor = '-moz-grab'; } if (whichCursor == 'draggable') { cursor = 'pointer'; } } else { if (whichCursor == 'dragging' || whichCursor == 'dragready') { cursor = 'move'; } if (whichCursor == 'draggable') { cursor = 'pointer'; } } if (this.markerWrapper_.style.cursor != cursor) { this.markerWrapper_.style.cursor = cursor; } }; /** * Start dragging. * * @param {Event} e The event. */ RichMarker.prototype.startDrag = function(e) { if (!this.getDraggable()) { return; } if (!this.dragging_) { this.dragging_ = true; var map = this.getMap(); this.mapDraggable_ = map.get('draggable'); map.set('draggable', false); // Store the current mouse position this.mouseX_ = e.clientX; this.mouseY_ = e.clientY; this.setCursor_('dragready'); // Stop the text from being selectable while being dragged this.markerWrapper_.style['MozUserSelect'] = 'none'; this.markerWrapper_.style['KhtmlUserSelect'] = 'none'; this.markerWrapper_.style['WebkitUserSelect'] = 'none'; this.markerWrapper_['unselectable'] = 'on'; this.markerWrapper_['onselectstart'] = function() { return false; }; this.addDraggingListeners_(); google.maps.event.trigger(this, 'dragstart'); } }; /** * Stop dragging. */ RichMarker.prototype.stopDrag = function() { if (!this.getDraggable()) { return; } if (this.dragging_) { this.dragging_ = false; this.getMap().set('draggable', this.mapDraggable_); this.mouseX_ = this.mouseY_ = this.mapDraggable_ = null; // Allow the text to be selectable again this.markerWrapper_.style['MozUserSelect'] = ''; this.markerWrapper_.style['KhtmlUserSelect'] = ''; this.markerWrapper_.style['WebkitUserSelect'] = ''; this.markerWrapper_['unselectable'] = 'off'; this.markerWrapper_['onselectstart'] = function() {}; this.removeDraggingListeners_(); this.setCursor_('draggable'); google.maps.event.trigger(this, 'dragend'); this.draw(); } }; /** * Handles the drag event. * * @param {Event} e The event. */ RichMarker.prototype.drag = function(e) { if (!this.getDraggable() || !this.dragging_) { // This object isn't draggable or we have stopped dragging this.stopDrag(); return; } var dx = this.mouseX_ - e.clientX; var dy = this.mouseY_ - e.clientY; this.mouseX_ = e.clientX; this.mouseY_ = e.clientY; var left = parseInt(this.markerWrapper_.style['left'], 10) - dx; var top = parseInt(this.markerWrapper_.style['top'], 10) - dy; this.markerWrapper_.style['left'] = left + 'px'; this.markerWrapper_.style['top'] = top + 'px'; var offset = this.getOffset_(); // Set the position property and adjust for the anchor offset var point = new google.maps.Point(left - offset.width, top - offset.height); var projection = this.getProjection(); this.setPosition(projection.fromDivPixelToLatLng(point)); this.setCursor_('dragging'); google.maps.event.trigger(this, 'drag'); }; /** * Removes the drag listeners associated with the marker. * * @private */ RichMarker.prototype.removeDragListeners_ = function() { if (this.draggableListener_) { google.maps.event.removeListener(this.draggableListener_); delete this.draggableListener_; } this.setCursor_(''); }; /** * Add dragability events to the marker. * * @param {Node} node The node to apply dragging to. * @private */ RichMarker.prototype.addDragging_ = function(node) { if (!node) { return; } var that = this; this.draggableListener_ = google.maps.event.addDomListener(node, 'mousedown', function(e) { that.startDrag(e); }); this.setCursor_('draggable'); }; /** * Add dragging listeners. * * @private */ RichMarker.prototype.addDraggingListeners_ = function() { var that = this; if (this.markerWrapper_.setCapture) { this.markerWrapper_.setCapture(true); this.draggingListeners_ = [ google.maps.event.addDomListener(this.markerWrapper_, 'mousemove', function(e) { that.drag(e); }, true), google.maps.event.addDomListener(this.markerWrapper_, 'mouseup', function() { that.stopDrag(); that.markerWrapper_.releaseCapture(); }, true) ]; } else { this.draggingListeners_ = [ google.maps.event.addDomListener(window, 'mousemove', function(e) { that.drag(e); }, true), google.maps.event.addDomListener(window, 'mouseup', function() { that.stopDrag(); }, true) ]; } }; /** * Remove dragging listeners. * * @private */ RichMarker.prototype.removeDraggingListeners_ = function() { if (this.draggingListeners_) { for (var i = 0, listener; listener = this.draggingListeners_[i]; i++) { google.maps.event.removeListener(listener); } this.draggingListeners_.length = 0; } }; /** * Get the anchor offset. * * @return {google.maps.Size} The size offset. * @private */ RichMarker.prototype.getOffset_ = function() { var anchor = this.getAnchor(); if (typeof anchor == 'object') { return /** @type {google.maps.Size} */ (anchor); } var offset = new google.maps.Size(0, 0); if (!this.markerContent_) { return offset; } var width = this.markerContent_.offsetWidth; var height = this.markerContent_.offsetHeight; switch (anchor) { case RichMarkerPosition['TOP_LEFT']: break; case RichMarkerPosition['TOP']: offset.width = -width / 2; break; case RichMarkerPosition['TOP_RIGHT']: offset.width = -width; break; case RichMarkerPosition['LEFT']: offset.height = -height / 2; break; case RichMarkerPosition['MIDDLE']: offset.width = -width / 2; offset.height = -height / 2; break; case RichMarkerPosition['RIGHT']: offset.width = -width; offset.height = -height / 2; break; case RichMarkerPosition['BOTTOM_LEFT']: offset.height = -height; break; case RichMarkerPosition['BOTTOM']: offset.width = -width / 2; offset.height = -height; break; case RichMarkerPosition['BOTTOM_RIGHT']: offset.width = -width; offset.height = -height; break; } return offset; }; /** * Adding the marker to a map. * Implementing the interface. */ RichMarker.prototype.onAdd = function() { if (!this.markerWrapper_) { this.markerWrapper_ = document.createElement('DIV'); this.markerWrapper_.style['position'] = 'absolute'; } if (this.getZIndex()) { this.markerWrapper_.style['zIndex'] = this.getZIndex(); } this.markerWrapper_.style['display'] = this.getVisible() ? '' : 'none'; if (!this.markerContent_) { this.markerContent_ = document.createElement('DIV'); this.markerWrapper_.appendChild(this.markerContent_); var that = this; google.maps.event.addDomListener(this.markerContent_, 'click', function(e) { google.maps.event.trigger(that, 'click'); }); google.maps.event.addDomListener(this.markerContent_, 'mouseover', function(e) { google.maps.event.trigger(that, 'mouseover'); }); google.maps.event.addDomListener(this.markerContent_, 'mouseout', function(e) { google.maps.event.trigger(that, 'mouseout'); }); } this.ready_ = true; this.content_changed(); this.flat_changed(); this.draggable_changed(); var panes = this.getPanes(); if (panes) { panes.overlayMouseTarget.appendChild(this.markerWrapper_); } google.maps.event.trigger(this, 'ready'); }; RichMarker.prototype['onAdd'] = RichMarker.prototype.onAdd; /** * Impelementing the interface. */ RichMarker.prototype.draw = function() { if (!this.ready_ || this.dragging_) { return; } var projection = this.getProjection(); if (!projection) { // The map projection is not ready yet so do nothing return; } var latLng = /** @type {google.maps.LatLng} */ (this.get('position')); var pos = projection.fromLatLngToDivPixel(latLng); var offset = this.getOffset_(); this.markerWrapper_.style['top'] = (pos.y + offset.height) + 'px'; this.markerWrapper_.style['left'] = (pos.x + offset.width) + 'px'; var height = this.markerContent_.offsetHeight; var width = this.markerContent_.offsetWidth; if (width != this.get('width')) { this.set('width', width); } if (height != this.get('height')) { this.set('height', height); } }; RichMarker.prototype['draw'] = RichMarker.prototype.draw; /** * Removing a marker from the map. * Implementing the interface. */ RichMarker.prototype.onRemove = function() { if (this.markerWrapper_ && this.markerWrapper_.parentNode) { this.markerWrapper_.parentNode.removeChild(this.markerWrapper_); } this.removeDragListeners_(); }; RichMarker.prototype['onRemove'] = RichMarker.prototype.onRemove; /** * RichMarker Anchor positions * @enum {number} */ var RichMarkerPosition = { 'TOP_LEFT': 1, 'TOP': 2, 'TOP_RIGHT': 3, 'LEFT': 4, 'MIDDLE': 5, 'RIGHT': 6, 'BOTTOM_LEFT': 7, 'BOTTOM': 8, 'BOTTOM_RIGHT': 9 }; window['RichMarkerPosition'] = RichMarkerPosition; //TODO: export / passthese on in the service instead of window window.InfoBox = InfoBox; window.Cluster = Cluster; window.ClusterIcon = ClusterIcon; window.MarkerClusterer = MarkerClusterer; window.MarkerLabel_ = MarkerLabel_; window.MarkerWithLabel = MarkerWithLabel; window.RichMarker = RichMarker; }(); //END REPLACE }) }; }); ;/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { /* istanbul ignore next */ angular.module('uiGmapgoogle-maps.wrapped') .service('uiGmapDataStructures', function() { return { Graph: __webpack_require__(1).Graph, Queue: __webpack_require__(1).Queue }; }); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { (function() { module.exports = { Graph: __webpack_require__(2), Heap: __webpack_require__(3), LinkedList: __webpack_require__(4), Map: __webpack_require__(5), Queue: __webpack_require__(6), RedBlackTree: __webpack_require__(7), Trie: __webpack_require__(8) }; }).call(this); /***/ }, /* 2 */ /***/ function(module, exports) { /* Graph implemented as a modified incidence list. O(1) for every typical operation except `removeNode()` at O(E) where E is the number of edges. ## Overview example: ```js var graph = new Graph; graph.addNode('A'); // => a node object. For more info, log the output or check // the documentation for addNode graph.addNode('B'); graph.addNode('C'); graph.addEdge('A', 'C'); // => an edge object graph.addEdge('A', 'B'); graph.getEdge('B', 'A'); // => undefined. Directed edge! graph.getEdge('A', 'B'); // => the edge object previously added graph.getEdge('A', 'B').weight = 2 // weight is the only built-in handy property // of an edge object. Feel free to attach // other properties graph.getInEdgesOf('B'); // => array of edge objects, in this case only one; // connecting A to B graph.getOutEdgesOf('A'); // => array of edge objects, one to B and one to C graph.getAllEdgesOf('A'); // => all the in and out edges. Edge directed toward // the node itself are only counted once forEachNode(function(nodeObject) { console.log(node); }); forEachEdge(function(edgeObject) { console.log(edgeObject); }); graph.removeNode('C'); // => 'C'. The edge between A and C also removed graph.removeEdge('A', 'B'); // => the edge object removed ``` ## Properties: - nodeSize: total number of nodes. - edgeSize: total number of edges. */ (function() { var Graph, __hasProp = {}.hasOwnProperty; Graph = (function() { function Graph() { this._nodes = {}; this.nodeSize = 0; this.edgeSize = 0; } Graph.prototype.addNode = function(id) { /* The `id` is a unique identifier for the node, and should **not** change after it's added. It will be used for adding, retrieving and deleting related edges too. **Note** that, internally, the ids are kept in an object. JavaScript's object hashes the id `'2'` and `2` to the same key, so please stick to a simple id data type such as number or string. _Returns:_ the node object. Feel free to attach additional custom properties on it for graph algorithms' needs. **Undefined if node id already exists**, as to avoid accidental overrides. */ if (!this._nodes[id]) { this.nodeSize++; return this._nodes[id] = { _outEdges: {}, _inEdges: {} }; } }; Graph.prototype.getNode = function(id) { /* _Returns:_ the node object. Feel free to attach additional custom properties on it for graph algorithms' needs. */ return this._nodes[id]; }; Graph.prototype.removeNode = function(id) { /* _Returns:_ the node object removed, or undefined if it didn't exist in the first place. */ var inEdgeId, nodeToRemove, outEdgeId, _ref, _ref1; nodeToRemove = this._nodes[id]; if (!nodeToRemove) { return; } else { _ref = nodeToRemove._outEdges; for (outEdgeId in _ref) { if (!__hasProp.call(_ref, outEdgeId)) continue; this.removeEdge(id, outEdgeId); } _ref1 = nodeToRemove._inEdges; for (inEdgeId in _ref1) { if (!__hasProp.call(_ref1, inEdgeId)) continue; this.removeEdge(inEdgeId, id); } this.nodeSize--; delete this._nodes[id]; } return nodeToRemove; }; Graph.prototype.addEdge = function(fromId, toId, weight) { var edgeToAdd, fromNode, toNode; if (weight == null) { weight = 1; } /* `fromId` and `toId` are the node id specified when it was created using `addNode()`. `weight` is optional and defaults to 1. Ignoring it effectively makes this an unweighted graph. Under the hood, `weight` is just a normal property of the edge object. _Returns:_ the edge object created. Feel free to attach additional custom properties on it for graph algorithms' needs. **Or undefined** if the nodes of id `fromId` or `toId` aren't found, or if an edge already exists between the two nodes. */ if (this.getEdge(fromId, toId)) { return; } fromNode = this._nodes[fromId]; toNode = this._nodes[toId]; if (!fromNode || !toNode) { return; } edgeToAdd = { weight: weight }; fromNode._outEdges[toId] = edgeToAdd; toNode._inEdges[fromId] = edgeToAdd; this.edgeSize++; return edgeToAdd; }; Graph.prototype.getEdge = function(fromId, toId) { /* _Returns:_ the edge object, or undefined if the nodes of id `fromId` or `toId` aren't found. */ var fromNode, toNode; fromNode = this._nodes[fromId]; toNode = this._nodes[toId]; if (!fromNode || !toNode) { } else { return fromNode._outEdges[toId]; } }; Graph.prototype.removeEdge = function(fromId, toId) { /* _Returns:_ the edge object removed, or undefined of edge wasn't found. */ var edgeToDelete, fromNode, toNode; fromNode = this._nodes[fromId]; toNode = this._nodes[toId]; edgeToDelete = this.getEdge(fromId, toId); if (!edgeToDelete) { return; } delete fromNode._outEdges[toId]; delete toNode._inEdges[fromId]; this.edgeSize--; return edgeToDelete; }; Graph.prototype.getInEdgesOf = function(nodeId) { /* _Returns:_ an array of edge objects that are directed toward the node, or empty array if no such edge or node exists. */ var fromId, inEdges, toNode, _ref; toNode = this._nodes[nodeId]; inEdges = []; _ref = toNode != null ? toNode._inEdges : void 0; for (fromId in _ref) { if (!__hasProp.call(_ref, fromId)) continue; inEdges.push(this.getEdge(fromId, nodeId)); } return inEdges; }; Graph.prototype.getOutEdgesOf = function(nodeId) { /* _Returns:_ an array of edge objects that go out of the node, or empty array if no such edge or node exists. */ var fromNode, outEdges, toId, _ref; fromNode = this._nodes[nodeId]; outEdges = []; _ref = fromNode != null ? fromNode._outEdges : void 0; for (toId in _ref) { if (!__hasProp.call(_ref, toId)) continue; outEdges.push(this.getEdge(nodeId, toId)); } return outEdges; }; Graph.prototype.getAllEdgesOf = function(nodeId) { /* **Note:** not the same as concatenating `getInEdgesOf()` and `getOutEdgesOf()`. Some nodes might have an edge pointing toward itself. This method solves that duplication. _Returns:_ an array of edge objects linked to the node, no matter if they're outgoing or coming. Duplicate edge created by self-pointing nodes are removed. Only one copy stays. Empty array if node has no edge. */ var i, inEdges, outEdges, selfEdge, _i, _ref, _ref1; inEdges = this.getInEdgesOf(nodeId); outEdges = this.getOutEdgesOf(nodeId); if (inEdges.length === 0) { return outEdges; } selfEdge = this.getEdge(nodeId, nodeId); for (i = _i = 0, _ref = inEdges.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { if (inEdges[i] === selfEdge) { _ref1 = [inEdges[inEdges.length - 1], inEdges[i]], inEdges[i] = _ref1[0], inEdges[inEdges.length - 1] = _ref1[1]; inEdges.pop(); break; } } return inEdges.concat(outEdges); }; Graph.prototype.forEachNode = function(operation) { /* Traverse through the graph in an arbitrary manner, visiting each node once. Pass a function of the form `fn(nodeObject, nodeId)`. _Returns:_ undefined. */ var nodeId, nodeObject, _ref; _ref = this._nodes; for (nodeId in _ref) { if (!__hasProp.call(_ref, nodeId)) continue; nodeObject = _ref[nodeId]; operation(nodeObject, nodeId); } }; Graph.prototype.forEachEdge = function(operation) { /* Traverse through the graph in an arbitrary manner, visiting each edge once. Pass a function of the form `fn(edgeObject)`. _Returns:_ undefined. */ var edgeObject, nodeId, nodeObject, toId, _ref, _ref1; _ref = this._nodes; for (nodeId in _ref) { if (!__hasProp.call(_ref, nodeId)) continue; nodeObject = _ref[nodeId]; _ref1 = nodeObject._outEdges; for (toId in _ref1) { if (!__hasProp.call(_ref1, toId)) continue; edgeObject = _ref1[toId]; operation(edgeObject); } } }; return Graph; })(); module.exports = Graph; }).call(this); /***/ }, /* 3 */ /***/ function(module, exports) { /* Minimum heap, i.e. smallest node at root. **Note:** does not accept null or undefined. This is by design. Those values cause comparison problems and might report false negative during extraction. ## Overview example: ```js var heap = new Heap([5, 6, 3, 4]); heap.add(10); // => 10 heap.removeMin(); // => 3 heap.peekMin(); // => 4 ``` ## Properties: - size: total number of items. */ (function() { var Heap, _leftChild, _parent, _rightChild; Heap = (function() { function Heap(dataToHeapify) { var i, item, _i, _j, _len, _ref; if (dataToHeapify == null) { dataToHeapify = []; } /* Pass an optional array to be heapified. Takes only O(n) time. */ this._data = [void 0]; for (_i = 0, _len = dataToHeapify.length; _i < _len; _i++) { item = dataToHeapify[_i]; if (item != null) { this._data.push(item); } } if (this._data.length > 1) { for (i = _j = 2, _ref = this._data.length; 2 <= _ref ? _j < _ref : _j > _ref; i = 2 <= _ref ? ++_j : --_j) { this._upHeap(i); } } this.size = this._data.length - 1; } Heap.prototype.add = function(value) { /* **Remember:** rejects null and undefined for mentioned reasons. _Returns:_ the value added. */ if (value == null) { return; } this._data.push(value); this._upHeap(this._data.length - 1); this.size++; return value; }; Heap.prototype.removeMin = function() { /* _Returns:_ the smallest item (the root). */ var min; if (this._data.length === 1) { return; } this.size--; if (this._data.length === 2) { return this._data.pop(); } min = this._data[1]; this._data[1] = this._data.pop(); this._downHeap(); return min; }; Heap.prototype.peekMin = function() { /* Check the smallest item without removing it. _Returns:_ the smallest item (the root). */ return this._data[1]; }; Heap.prototype._upHeap = function(index) { var valueHolder, _ref; valueHolder = this._data[index]; while (this._data[index] < this._data[_parent(index)] && index > 1) { _ref = [this._data[_parent(index)], this._data[index]], this._data[index] = _ref[0], this._data[_parent(index)] = _ref[1]; index = _parent(index); } }; Heap.prototype._downHeap = function() { var currentIndex, smallerChildIndex, _ref; currentIndex = 1; while (_leftChild(currentIndex < this._data.length)) { smallerChildIndex = _leftChild(currentIndex); if (smallerChildIndex < this._data.length - 1) { if (this._data[_rightChild(currentIndex)] < this._data[smallerChildIndex]) { smallerChildIndex = _rightChild(currentIndex); } } if (this._data[smallerChildIndex] < this._data[currentIndex]) { _ref = [this._data[currentIndex], this._data[smallerChildIndex]], this._data[smallerChildIndex] = _ref[0], this._data[currentIndex] = _ref[1]; currentIndex = smallerChildIndex; } else { break; } } }; return Heap; })(); _parent = function(index) { return index >> 1; }; _leftChild = function(index) { return index << 1; }; _rightChild = function(index) { return (index << 1) + 1; }; module.exports = Heap; }).call(this); /***/ }, /* 4 */ /***/ function(module, exports) { /* Doubly Linked. ## Overview example: ```js var list = new LinkedList([5, 4, 9]); list.add(12); // => 12 list.head.next.value; // => 4 list.tail.value; // => 12 list.at(-1); // => 12 list.removeAt(2); // => 9 list.remove(4); // => 4 list.indexOf(5); // => 0 list.add(5, 1); // => 5. Second 5 at position 1. list.indexOf(5, 1); // => 1 ``` ## Properties: - head: first item. - tail: last item. - size: total number of items. - item.value: value passed to the item when calling `add()`. - item.prev: previous item. - item.next: next item. */ (function() { var LinkedList; LinkedList = (function() { function LinkedList(valuesToAdd) { var value, _i, _len; if (valuesToAdd == null) { valuesToAdd = []; } /* Can pass an array of elements to link together during `new LinkedList()` initiation. */ this.head = { prev: void 0, value: void 0, next: void 0 }; this.tail = { prev: void 0, value: void 0, next: void 0 }; this.size = 0; for (_i = 0, _len = valuesToAdd.length; _i < _len; _i++) { value = valuesToAdd[_i]; this.add(value); } } LinkedList.prototype.at = function(position) { /* Get the item at `position` (optional). Accepts negative index: ```js myList.at(-1); // Returns the last element. ``` However, passing a negative index that surpasses the boundary will return undefined: ```js myList = new LinkedList([2, 6, 8, 3]) myList.at(-5); // Undefined. myList.at(-4); // 2. ``` _Returns:_ item gotten, or undefined if not found. */ var currentNode, i, _i, _j, _ref; if (!((-this.size <= position && position < this.size))) { return; } position = this._adjust(position); if (position * 2 < this.size) { currentNode = this.head; for (i = _i = 1; _i <= position; i = _i += 1) { currentNode = currentNode.next; } } else { currentNode = this.tail; for (i = _j = 1, _ref = this.size - position - 1; _j <= _ref; i = _j += 1) { currentNode = currentNode.prev; } } return currentNode; }; LinkedList.prototype.add = function(value, position) { var currentNode, nodeToAdd, _ref, _ref1, _ref2; if (position == null) { position = this.size; } /* Add a new item at `position` (optional). Defaults to adding at the end. `position`, just like in `at()`, can be negative (within the negative boundary). Position specifies the place the value's going to be, and the old node will be pushed higher. `add(-2)` on list of size 7 is the same as `add(5)`. _Returns:_ item added. */ if (!((-this.size <= position && position <= this.size))) { return; } nodeToAdd = { value: value }; position = this._adjust(position); if (this.size === 0) { this.head = nodeToAdd; } else { if (position === 0) { _ref = [nodeToAdd, this.head, nodeToAdd], this.head.prev = _ref[0], nodeToAdd.next = _ref[1], this.head = _ref[2]; } else { currentNode = this.at(position - 1); _ref1 = [currentNode.next, nodeToAdd, nodeToAdd, currentNode], nodeToAdd.next = _ref1[0], (_ref2 = currentNode.next) != null ? _ref2.prev = _ref1[1] : void 0, currentNode.next = _ref1[2], nodeToAdd.prev = _ref1[3]; } } if (position === this.size) { this.tail = nodeToAdd; } this.size++; return value; }; LinkedList.prototype.removeAt = function(position) { var currentNode, valueToReturn, _ref; if (position == null) { position = this.size - 1; } /* Remove an item at index `position` (optional). Defaults to the last item. Index can be negative (within the boundary). _Returns:_ item removed. */ if (!((-this.size <= position && position < this.size))) { return; } if (this.size === 0) { return; } position = this._adjust(position); if (this.size === 1) { valueToReturn = this.head.value; this.head.value = this.tail.value = void 0; } else { if (position === 0) { valueToReturn = this.head.value; this.head = this.head.next; this.head.prev = void 0; } else { currentNode = this.at(position); valueToReturn = currentNode.value; currentNode.prev.next = currentNode.next; if ((_ref = currentNode.next) != null) { _ref.prev = currentNode.prev; } if (position === this.size - 1) { this.tail = currentNode.prev; } } } this.size--; return valueToReturn; }; LinkedList.prototype.remove = function(value) { /* Remove the item using its value instead of position. **Will remove the fist occurrence of `value`.** _Returns:_ the value, or undefined if value's not found. */ var currentNode; if (value == null) { return; } currentNode = this.head; while (currentNode && currentNode.value !== value) { currentNode = currentNode.next; } if (!currentNode) { return; } if (this.size === 1) { this.head.value = this.tail.value = void 0; } else if (currentNode === this.head) { this.head = this.head.next; this.head.prev = void 0; } else if (currentNode === this.tail) { this.tail = this.tail.prev; this.tail.next = void 0; } else { currentNode.prev.next = currentNode.next; currentNode.next.prev = currentNode.prev; } this.size--; return value; }; LinkedList.prototype.indexOf = function(value, startingPosition) { var currentNode, position; if (startingPosition == null) { startingPosition = 0; } /* Find the index of an item, similarly to `array.indexOf()`. Defaults to start searching from the beginning, by can start at another position by passing `startingPosition`. This parameter can also be negative; but unlike the other methods of this class, `startingPosition` (optional) can be as small as desired; a value of -999 for a list of size 5 will start searching normally, at the beginning. **Note:** searches forwardly, **not** backwardly, i.e: ```js var myList = new LinkedList([2, 3, 1, 4, 3, 5]) myList.indexOf(3, -3); // Returns 4, not 1 ``` _Returns:_ index of item found, or -1 if not found. */ if (((this.head.value == null) && !this.head.next) || startingPosition >= this.size) { return -1; } startingPosition = Math.max(0, this._adjust(startingPosition)); currentNode = this.at(startingPosition); position = startingPosition; while (currentNode) { if (currentNode.value === value) { break; } currentNode = currentNode.next; position++; } if (position === this.size) { return -1; } else { return position; } }; LinkedList.prototype._adjust = function(position) { if (position < 0) { return this.size + position; } else { return position; } }; return LinkedList; })(); module.exports = LinkedList; }).call(this); /***/ }, /* 5 */ /***/ function(module, exports) { /* Kind of a stopgap measure for the upcoming [JavaScript Map](http://wiki.ecmascript.org/doku.php?id=harmony:simple_maps_and_sets) **Note:** due to JavaScript's limitations, hashing something other than Boolean, Number, String, Undefined, Null, RegExp, Function requires a hack that inserts a hidden unique property into the object. This means `set`, `get`, `has` and `delete` must employ the same object, and not a mere identical copy as in the case of, say, a string. ## Overview example: ```js var map = new Map({'alice': 'wonderland', 20: 'ok'}); map.set('20', 5); // => 5 map.get('20'); // => 5 map.has('alice'); // => true map.delete(20) // => true var arr = [1, 2]; map.add(arr, 'goody'); // => 'goody' map.has(arr); // => true map.has([1, 2]); // => false. Needs to compare by reference map.forEach(function(key, value) { console.log(key, value); }); ``` ## Properties: - size: The total number of `(key, value)` pairs. */ (function() { var Map, SPECIAL_TYPE_KEY_PREFIX, _extractDataType, _isSpecialType, __hasProp = {}.hasOwnProperty; SPECIAL_TYPE_KEY_PREFIX = '_mapId_'; Map = (function() { Map._mapIdTracker = 0; Map._newMapId = function() { return this._mapIdTracker++; }; function Map(objectToMap) { /* Pass an optional object whose (key, value) pair will be hashed. **Careful** not to pass something like {5: 'hi', '5': 'hello'}, since JavaScript's native object behavior will crush the first 5 property before it gets to constructor. */ var key, value; this._content = {}; this._itemId = 0; this._id = Map._newMapId(); this.size = 0; for (key in objectToMap) { if (!__hasProp.call(objectToMap, key)) continue; value = objectToMap[key]; this.set(key, value); } } Map.prototype.hash = function(key, makeHash) { var propertyForMap, type; if (makeHash == null) { makeHash = false; } /* The hash function for hashing keys is public. Feel free to replace it with your own. The `makeHash` parameter is optional and accepts a boolean (defaults to `false`) indicating whether or not to produce a new hash (for the first use, naturally). _Returns:_ the hash. */ type = _extractDataType(key); if (_isSpecialType(key)) { propertyForMap = SPECIAL_TYPE_KEY_PREFIX + this._id; if (makeHash && !key[propertyForMap]) { key[propertyForMap] = this._itemId++; } return propertyForMap + '_' + key[propertyForMap]; } else { return type + '_' + key; } }; Map.prototype.set = function(key, value) { /* _Returns:_ value. */ if (!this.has(key)) { this.size++; } this._content[this.hash(key, true)] = [value, key]; return value; }; Map.prototype.get = function(key) { /* _Returns:_ value corresponding to the key, or undefined if not found. */ var _ref; return (_ref = this._content[this.hash(key)]) != null ? _ref[0] : void 0; }; Map.prototype.has = function(key) { /* Check whether a value exists for the key. _Returns:_ true or false. */ return this.hash(key) in this._content; }; Map.prototype["delete"] = function(key) { /* Remove the (key, value) pair. _Returns:_ **true or false**. Unlike most of this library, this method doesn't return the deleted value. This is so that it conforms to the future JavaScript `map.delete()`'s behavior. */ var hashedKey; hashedKey = this.hash(key); if (hashedKey in this._content) { delete this._content[hashedKey]; if (_isSpecialType(key)) { delete key[SPECIAL_TYPE_KEY_PREFIX + this._id]; } this.size--; return true; } return false; }; Map.prototype.forEach = function(operation) { /* Traverse through the map. Pass a function of the form `fn(key, value)`. _Returns:_ undefined. */ var key, value, _ref; _ref = this._content; for (key in _ref) { if (!__hasProp.call(_ref, key)) continue; value = _ref[key]; operation(value[1], value[0]); } }; return Map; })(); _isSpecialType = function(key) { var simpleHashableTypes, simpleType, type, _i, _len; simpleHashableTypes = ['Boolean', 'Number', 'String', 'Undefined', 'Null', 'RegExp', 'Function']; type = _extractDataType(key); for (_i = 0, _len = simpleHashableTypes.length; _i < _len; _i++) { simpleType = simpleHashableTypes[_i]; if (type === simpleType) { return false; } } return true; }; _extractDataType = function(type) { return Object.prototype.toString.apply(type).match(/\[object (.+)\]/)[1]; }; module.exports = Map; }).call(this); /***/ }, /* 6 */ /***/ function(module, exports) { /* Amortized O(1) dequeue! ## Overview example: ```js var queue = new Queue([1, 6, 4]); queue.enqueue(10); // => 10 queue.dequeue(); // => 1 queue.dequeue(); // => 6 queue.dequeue(); // => 4 queue.peek(); // => 10 queue.dequeue(); // => 10 queue.peek(); // => undefined ``` ## Properties: - size: The total number of items. */ (function() { var Queue; Queue = (function() { function Queue(initialArray) { if (initialArray == null) { initialArray = []; } /* Pass an optional array to be transformed into a queue. The item at index 0 is the first to be dequeued. */ this._content = initialArray; this._dequeueIndex = 0; this.size = this._content.length; } Queue.prototype.enqueue = function(item) { /* _Returns:_ the item. */ this.size++; this._content.push(item); return item; }; Queue.prototype.dequeue = function() { /* _Returns:_ the dequeued item. */ var itemToDequeue; if (this.size === 0) { return; } this.size--; itemToDequeue = this._content[this._dequeueIndex]; this._dequeueIndex++; if (this._dequeueIndex * 2 > this._content.length) { this._content = this._content.slice(this._dequeueIndex); this._dequeueIndex = 0; } return itemToDequeue; }; Queue.prototype.peek = function() { /* Check the next item to be dequeued, without removing it. _Returns:_ the item. */ return this._content[this._dequeueIndex]; }; return Queue; })(); module.exports = Queue; }).call(this); /***/ }, /* 7 */ /***/ function(module, exports) { /* Credit to Wikipedia's article on [Red-black tree](http://en.wikipedia.org/wiki/Red–black_tree) **Note:** doesn't handle duplicate entries, undefined and null. This is by design. ## Overview example: ```js var rbt = new RedBlackTree([7, 5, 1, 8]); rbt.add(2); // => 2 rbt.add(10); // => 10 rbt.has(5); // => true rbt.peekMin(); // => 1 rbt.peekMax(); // => 10 rbt.removeMin(); // => 1 rbt.removeMax(); // => 10 rbt.remove(8); // => 8 ``` ## Properties: - size: The total number of items. */ (function() { var BLACK, NODE_FOUND, NODE_TOO_BIG, NODE_TOO_SMALL, RED, RedBlackTree, STOP_SEARCHING, _findNode, _grandParentOf, _isLeft, _leftOrRight, _peekMaxNode, _peekMinNode, _siblingOf, _uncleOf; NODE_FOUND = 0; NODE_TOO_BIG = 1; NODE_TOO_SMALL = 2; STOP_SEARCHING = 3; RED = 1; BLACK = 2; RedBlackTree = (function() { function RedBlackTree(valuesToAdd) { var value, _i, _len; if (valuesToAdd == null) { valuesToAdd = []; } /* Pass an optional array to be turned into binary tree. **Note:** does not accept duplicate, undefined and null. */ this._root; this.size = 0; for (_i = 0, _len = valuesToAdd.length; _i < _len; _i++) { value = valuesToAdd[_i]; if (value != null) { this.add(value); } } } RedBlackTree.prototype.add = function(value) { /* Again, make sure to not pass a value already in the tree, or undefined, or null. _Returns:_ value added. */ var currentNode, foundNode, nodeToInsert, _ref; if (value == null) { return; } this.size++; nodeToInsert = { value: value, _color: RED }; if (!this._root) { this._root = nodeToInsert; } else { foundNode = _findNode(this._root, function(node) { if (value === node.value) { return NODE_FOUND; } else { if (value < node.value) { if (node._left) { return NODE_TOO_BIG; } else { nodeToInsert._parent = node; node._left = nodeToInsert; return STOP_SEARCHING; } } else { if (node._right) { return NODE_TOO_SMALL; } else { nodeToInsert._parent = node; node._right = nodeToInsert; return STOP_SEARCHING; } } } }); if (foundNode != null) { return; } } currentNode = nodeToInsert; while (true) { if (currentNode === this._root) { currentNode._color = BLACK; break; } if (currentNode._parent._color === BLACK) { break; } if (((_ref = _uncleOf(currentNode)) != null ? _ref._color : void 0) === RED) { currentNode._parent._color = BLACK; _uncleOf(currentNode)._color = BLACK; _grandParentOf(currentNode)._color = RED; currentNode = _grandParentOf(currentNode); continue; } if (!_isLeft(currentNode) && _isLeft(currentNode._parent)) { this._rotateLeft(currentNode._parent); currentNode = currentNode._left; } else if (_isLeft(currentNode) && !_isLeft(currentNode._parent)) { this._rotateRight(currentNode._parent); currentNode = currentNode._right; } currentNode._parent._color = BLACK; _grandParentOf(currentNode)._color = RED; if (_isLeft(currentNode)) { this._rotateRight(_grandParentOf(currentNode)); } else { this._rotateLeft(_grandParentOf(currentNode)); } break; } return value; }; RedBlackTree.prototype.has = function(value) { /* _Returns:_ true or false. */ var foundNode; foundNode = _findNode(this._root, function(node) { if (value === node.value) { return NODE_FOUND; } else if (value < node.value) { return NODE_TOO_BIG; } else { return NODE_TOO_SMALL; } }); if (foundNode) { return true; } else { return false; } }; RedBlackTree.prototype.peekMin = function() { /* Check the minimum value without removing it. _Returns:_ the minimum value. */ var _ref; return (_ref = _peekMinNode(this._root)) != null ? _ref.value : void 0; }; RedBlackTree.prototype.peekMax = function() { /* Check the maximum value without removing it. _Returns:_ the maximum value. */ var _ref; return (_ref = _peekMaxNode(this._root)) != null ? _ref.value : void 0; }; RedBlackTree.prototype.remove = function(value) { /* _Returns:_ the value removed, or undefined if the value's not found. */ var foundNode; foundNode = _findNode(this._root, function(node) { if (value === node.value) { return NODE_FOUND; } else if (value < node.value) { return NODE_TOO_BIG; } else { return NODE_TOO_SMALL; } }); if (!foundNode) { return; } this._removeNode(this._root, foundNode); this.size--; return value; }; RedBlackTree.prototype.removeMin = function() { /* _Returns:_ smallest item removed, or undefined if tree's empty. */ var nodeToRemove, valueToReturn; nodeToRemove = _peekMinNode(this._root); if (!nodeToRemove) { return; } valueToReturn = nodeToRemove.value; this._removeNode(this._root, nodeToRemove); return valueToReturn; }; RedBlackTree.prototype.removeMax = function() { /* _Returns:_ biggest item removed, or undefined if tree's empty. */ var nodeToRemove, valueToReturn; nodeToRemove = _peekMaxNode(this._root); if (!nodeToRemove) { return; } valueToReturn = nodeToRemove.value; this._removeNode(this._root, nodeToRemove); return valueToReturn; }; RedBlackTree.prototype._removeNode = function(root, node) { var sibling, successor, _ref, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7; if (node._left && node._right) { successor = _peekMinNode(node._right); node.value = successor.value; node = successor; } successor = node._left || node._right; if (!successor) { successor = { color: BLACK, _right: void 0, _left: void 0, isLeaf: true }; } successor._parent = node._parent; if ((_ref = node._parent) != null) { _ref[_leftOrRight(node)] = successor; } if (node._color === BLACK) { if (successor._color === RED) { successor._color = BLACK; if (!successor._parent) { this._root = successor; } } else { while (true) { if (!successor._parent) { if (!successor.isLeaf) { this._root = successor; } else { this._root = void 0; } break; } sibling = _siblingOf(successor); if ((sibling != null ? sibling._color : void 0) === RED) { successor._parent._color = RED; sibling._color = BLACK; if (_isLeft(successor)) { this._rotateLeft(successor._parent); } else { this._rotateRight(successor._parent); } } sibling = _siblingOf(successor); if (successor._parent._color === BLACK && (!sibling || (sibling._color === BLACK && (!sibling._left || sibling._left._color === BLACK) && (!sibling._right || sibling._right._color === BLACK)))) { if (sibling != null) { sibling._color = RED; } if (successor.isLeaf) { successor._parent[_leftOrRight(successor)] = void 0; } successor = successor._parent; continue; } if (successor._parent._color === RED && (!sibling || (sibling._color === BLACK && (!sibling._left || ((_ref1 = sibling._left) != null ? _ref1._color : void 0) === BLACK) && (!sibling._right || ((_ref2 = sibling._right) != null ? _ref2._color : void 0) === BLACK)))) { if (sibling != null) { sibling._color = RED; } successor._parent._color = BLACK; break; } if ((sibling != null ? sibling._color : void 0) === BLACK) { if (_isLeft(successor) && (!sibling._right || sibling._right._color === BLACK) && ((_ref3 = sibling._left) != null ? _ref3._color : void 0) === RED) { sibling._color = RED; if ((_ref4 = sibling._left) != null) { _ref4._color = BLACK; } this._rotateRight(sibling); } else if (!_isLeft(successor) && (!sibling._left || sibling._left._color === BLACK) && ((_ref5 = sibling._right) != null ? _ref5._color : void 0) === RED) { sibling._color = RED; if ((_ref6 = sibling._right) != null) { _ref6._color = BLACK; } this._rotateLeft(sibling); } break; } sibling = _siblingOf(successor); sibling._color = successor._parent._color; if (_isLeft(successor)) { sibling._right._color = BLACK; this._rotateRight(successor._parent); } else { sibling._left._color = BLACK; this._rotateLeft(successor._parent); } } } } if (successor.isLeaf) { return (_ref7 = successor._parent) != null ? _ref7[_leftOrRight(successor)] = void 0 : void 0; } }; RedBlackTree.prototype._rotateLeft = function(node) { var _ref, _ref1; if ((_ref = node._parent) != null) { _ref[_leftOrRight(node)] = node._right; } node._right._parent = node._parent; node._parent = node._right; node._right = node._right._left; node._parent._left = node; if ((_ref1 = node._right) != null) { _ref1._parent = node; } if (node._parent._parent == null) { return this._root = node._parent; } }; RedBlackTree.prototype._rotateRight = function(node) { var _ref, _ref1; if ((_ref = node._parent) != null) { _ref[_leftOrRight(node)] = node._left; } node._left._parent = node._parent; node._parent = node._left; node._left = node._left._right; node._parent._right = node; if ((_ref1 = node._left) != null) { _ref1._parent = node; } if (node._parent._parent == null) { return this._root = node._parent; } }; return RedBlackTree; })(); _isLeft = function(node) { return node === node._parent._left; }; _leftOrRight = function(node) { if (_isLeft(node)) { return '_left'; } else { return '_right'; } }; _findNode = function(startingNode, comparator) { var comparisonResult, currentNode, foundNode; currentNode = startingNode; foundNode = void 0; while (currentNode) { comparisonResult = comparator(currentNode); if (comparisonResult === NODE_FOUND) { foundNode = currentNode; break; } if (comparisonResult === NODE_TOO_BIG) { currentNode = currentNode._left; } else if (comparisonResult === NODE_TOO_SMALL) { currentNode = currentNode._right; } else if (comparisonResult === STOP_SEARCHING) { break; } } return foundNode; }; _peekMinNode = function(startingNode) { return _findNode(startingNode, function(node) { if (node._left) { return NODE_TOO_BIG; } else { return NODE_FOUND; } }); }; _peekMaxNode = function(startingNode) { return _findNode(startingNode, function(node) { if (node._right) { return NODE_TOO_SMALL; } else { return NODE_FOUND; } }); }; _grandParentOf = function(node) { var _ref; return (_ref = node._parent) != null ? _ref._parent : void 0; }; _uncleOf = function(node) { if (!_grandParentOf(node)) { return; } if (_isLeft(node._parent)) { return _grandParentOf(node)._right; } else { return _grandParentOf(node)._left; } }; _siblingOf = function(node) { if (_isLeft(node)) { return node._parent._right; } else { return node._parent._left; } }; module.exports = RedBlackTree; }).call(this); /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { /* Good for fast insertion/removal/lookup of strings. ## Overview example: ```js var trie = new Trie(['bear', 'beer']); trie.add('hello'); // => 'hello' trie.add('helloha!'); // => 'helloha!' trie.has('bears'); // => false trie.longestPrefixOf('beatrice'); // => 'bea' trie.wordsWithPrefix('hel'); // => ['hello', 'helloha!'] trie.remove('beers'); // => undefined. 'beer' still exists trie.remove('Beer') // => undefined. Case-sensitive trie.remove('beer') // => 'beer'. Removed ``` ## Properties: - size: The total number of words. */ (function() { var Queue, Trie, WORD_END, _hasAtLeastNChildren, __hasProp = {}.hasOwnProperty; Queue = __webpack_require__(6); WORD_END = 'end'; Trie = (function() { function Trie(words) { var word, _i, _len; if (words == null) { words = []; } /* Pass an optional array of strings to be inserted initially. */ this._root = {}; this.size = 0; for (_i = 0, _len = words.length; _i < _len; _i++) { word = words[_i]; this.add(word); } } Trie.prototype.add = function(word) { /* Add a whole string to the trie. _Returns:_ the word added. Will return undefined (without adding the value) if the word passed is null or undefined. */ var currentNode, letter, _i, _len; if (word == null) { return; } this.size++; currentNode = this._root; for (_i = 0, _len = word.length; _i < _len; _i++) { letter = word[_i]; if (currentNode[letter] == null) { currentNode[letter] = {}; } currentNode = currentNode[letter]; } currentNode[WORD_END] = true; return word; }; Trie.prototype.has = function(word) { /* __Returns:_ true or false. */ var currentNode, letter, _i, _len; if (word == null) { return false; } currentNode = this._root; for (_i = 0, _len = word.length; _i < _len; _i++) { letter = word[_i]; if (currentNode[letter] == null) { return false; } currentNode = currentNode[letter]; } if (currentNode[WORD_END]) { return true; } else { return false; } }; Trie.prototype.longestPrefixOf = function(word) { /* Find all words containing the prefix. The word itself counts as a prefix. ```js var trie = new Trie; trie.add('hello'); trie.longestPrefixOf('he'); // 'he' trie.longestPrefixOf('hello'); // 'hello' trie.longestPrefixOf('helloha!'); // 'hello' ``` _Returns:_ the prefix string, or empty string if no prefix found. */ var currentNode, letter, prefix, _i, _len; if (word == null) { return ''; } currentNode = this._root; prefix = ''; for (_i = 0, _len = word.length; _i < _len; _i++) { letter = word[_i]; if (currentNode[letter] == null) { break; } prefix += letter; currentNode = currentNode[letter]; } return prefix; }; Trie.prototype.wordsWithPrefix = function(prefix) { /* Find all words containing the prefix. The word itself counts as a prefix. **Watch out for edge cases.** ```js var trie = new Trie; trie.wordsWithPrefix(''); // []. Check later case below. trie.add(''); trie.wordsWithPrefix(''); // [''] trie.add('he'); trie.add('hello'); trie.add('hell'); trie.add('bear'); trie.add('z'); trie.add('zebra'); trie.wordsWithPrefix('hel'); // ['hell', 'hello'] ``` _Returns:_ an array of strings, or empty array if no word found. */ var accumulatedLetters, currentNode, letter, node, queue, subNode, words, _i, _len, _ref; if (prefix == null) { return []; } (prefix != null) || (prefix = ''); words = []; currentNode = this._root; for (_i = 0, _len = prefix.length; _i < _len; _i++) { letter = prefix[_i]; currentNode = currentNode[letter]; if (currentNode == null) { return []; } } queue = new Queue(); queue.enqueue([currentNode, '']); while (queue.size !== 0) { _ref = queue.dequeue(), node = _ref[0], accumulatedLetters = _ref[1]; if (node[WORD_END]) { words.push(prefix + accumulatedLetters); } for (letter in node) { if (!__hasProp.call(node, letter)) continue; subNode = node[letter]; queue.enqueue([subNode, accumulatedLetters + letter]); } } return words; }; Trie.prototype.remove = function(word) { /* _Returns:_ the string removed, or undefined if the word in its whole doesn't exist. **Note:** this means removing `beers` when only `beer` exists will return undefined and conserve `beer`. */ var currentNode, i, letter, prefix, _i, _j, _len, _ref; if (word == null) { return; } currentNode = this._root; prefix = []; for (_i = 0, _len = word.length; _i < _len; _i++) { letter = word[_i]; if (currentNode[letter] == null) { return; } currentNode = currentNode[letter]; prefix.push([letter, currentNode]); } if (!currentNode[WORD_END]) { return; } this.size--; delete currentNode[WORD_END]; if (_hasAtLeastNChildren(currentNode, 1)) { return word; } for (i = _j = _ref = prefix.length - 1; _ref <= 1 ? _j <= 1 : _j >= 1; i = _ref <= 1 ? ++_j : --_j) { if (!_hasAtLeastNChildren(prefix[i][1], 1)) { delete prefix[i - 1][1][prefix[i][0]]; } else { break; } } if (!_hasAtLeastNChildren(this._root[prefix[0][0]], 1)) { delete this._root[prefix[0][0]]; } return word; }; return Trie; })(); _hasAtLeastNChildren = function(node, n) { var child, childCount; if (n === 0) { return true; } childCount = 0; for (child in node) { if (!__hasProp.call(node, child)) continue; childCount++; if (childCount >= n) { return true; } } return false; }; module.exports = Trie; }).call(this); /***/ } /******/ ]);;angular.module('uiGmapgoogle-maps.wrapped') .service('uiGmapMarkerSpiderfier', [ 'uiGmapGoogleMapApi', function(GoogleMapApi) { var self = this; /* istanbul ignore next */ +function(){ /** @preserve OverlappingMarkerSpiderfier https://github.com/jawj/OverlappingMarkerSpiderfier Copyright (c) 2011 - 2013 George MacKerron Released under the MIT licence: http://opensource.org/licenses/mit-license Note: The Google Maps API v3 must be included *before* this code */ var hasProp = {}.hasOwnProperty, slice = [].slice; this['OverlappingMarkerSpiderfier'] = (function() { var ge, gm, j, lcH, lcU, len, mt, p, ref, twoPi, x; p = _Class.prototype; ref = [_Class, p]; for (j = 0, len = ref.length; j < len; j++) { x = ref[j]; x['VERSION'] = '0.3.3'; } gm = void 0; ge = void 0; mt = void 0; twoPi = Math.PI * 2; p['keepSpiderfied'] = false; p['markersWontHide'] = false; p['markersWontMove'] = false; p['nearbyDistance'] = 20; p['circleSpiralSwitchover'] = 9; p['circleFootSeparation'] = 23; p['circleStartAngle'] = twoPi / 12; p['spiralFootSeparation'] = 26; p['spiralLengthStart'] = 11; p['spiralLengthFactor'] = 4; p['spiderfiedZIndex'] = 1000; p['usualLegZIndex'] = 10; p['highlightedLegZIndex'] = 20; p['event'] = 'click'; p['minZoomLevel'] = false; p['legWeight'] = 1.5; p['legColors'] = { 'usual': {}, 'highlighted': {} }; lcU = p['legColors']['usual']; lcH = p['legColors']['highlighted']; _Class['initializeGoogleMaps'] = function(google) { gm = google.maps; ge = gm.event; mt = gm.MapTypeId; lcU[mt.HYBRID] = lcU[mt.SATELLITE] = '#fff'; lcH[mt.HYBRID] = lcH[mt.SATELLITE] = '#f00'; lcU[mt.TERRAIN] = lcU[mt.ROADMAP] = '#444'; lcH[mt.TERRAIN] = lcH[mt.ROADMAP] = '#f00'; this.ProjHelper = function(map) { return this.setMap(map); }; this.ProjHelper.prototype = new gm.OverlayView(); return this.ProjHelper.prototype['draw'] = function() {}; }; function _Class(map1, opts) { var e, k, l, len1, ref1, v; this.map = map1; if (opts == null) { opts = {}; } for (k in opts) { if (!hasProp.call(opts, k)) continue; v = opts[k]; this[k] = v; } this.projHelper = new this.constructor.ProjHelper(this.map); this.initMarkerArrays(); this.listeners = {}; ref1 = ['click', 'zoom_changed', 'maptypeid_changed']; for (l = 0, len1 = ref1.length; l < len1; l++) { e = ref1[l]; ge.addListener(this.map, e, (function(_this) { return function() { return _this['unspiderfy'](); }; })(this)); } } p.initMarkerArrays = function() { this.markers = []; return this.markerListenerRefs = []; }; p['addMarker'] = function(marker) { var listenerRefs; if (marker['_oms'] != null) { return this; } marker['_oms'] = true; listenerRefs = [ ge.addListener(marker, this['event'], (function(_this) { return function(event) { return _this.spiderListener(marker, event); }; })(this)) ]; if (!this['markersWontHide']) { listenerRefs.push(ge.addListener(marker, 'visible_changed', (function(_this) { return function() { return _this.markerChangeListener(marker, false); }; })(this))); } if (!this['markersWontMove']) { listenerRefs.push(ge.addListener(marker, 'position_changed', (function(_this) { return function() { return _this.markerChangeListener(marker, true); }; })(this))); } this.markerListenerRefs.push(listenerRefs); this.markers.push(marker); return this; }; p.markerChangeListener = function(marker, positionChanged) { if ((marker['_omsData'] != null) && (positionChanged || !marker.getVisible()) && !((this.spiderfying != null) || (this.unspiderfying != null))) { return this['unspiderfy'](positionChanged ? marker : null); } }; p['getMarkers'] = function() { return this.markers.slice(0); }; p['removeMarker'] = function(marker) { var i, l, len1, listenerRef, listenerRefs; if (marker['_omsData'] != null) { this['unspiderfy'](); } i = this.arrIndexOf(this.markers, marker); if (i < 0) { return this; } listenerRefs = this.markerListenerRefs.splice(i, 1)[0]; for (l = 0, len1 = listenerRefs.length; l < len1; l++) { listenerRef = listenerRefs[l]; ge.removeListener(listenerRef); } delete marker['_oms']; this.markers.splice(i, 1); return this; }; p['clearMarkers'] = function() { var i, l, len1, len2, listenerRef, listenerRefs, marker, n, ref1; this['unspiderfy'](); ref1 = this.markers; for (i = l = 0, len1 = ref1.length; l < len1; i = ++l) { marker = ref1[i]; listenerRefs = this.markerListenerRefs[i]; for (n = 0, len2 = listenerRefs.length; n < len2; n++) { listenerRef = listenerRefs[n]; ge.removeListener(listenerRef); } delete marker['_oms']; } this.initMarkerArrays(); return this; }; p['addListener'] = function(event, func) { var base; ((base = this.listeners)[event] != null ? base[event] : base[event] = []).push(func); return this; }; p['removeListener'] = function(event, func) { var i; i = this.arrIndexOf(this.listeners[event], func); if (!(i < 0)) { this.listeners[event].splice(i, 1); } return this; }; p['clearListeners'] = function(event) { this.listeners[event] = []; return this; }; p.trigger = function() { var args, event, func, l, len1, ref1, ref2, results; event = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : []; ref2 = (ref1 = this.listeners[event]) != null ? ref1 : []; results = []; for (l = 0, len1 = ref2.length; l < len1; l++) { func = ref2[l]; results.push(func.apply(null, args)); } return results; }; p.generatePtsCircle = function(count, centerPt) { var angle, angleStep, circumference, i, l, legLength, ref1, results; circumference = this['circleFootSeparation'] * (2 + count); legLength = circumference / twoPi; angleStep = twoPi / count; results = []; for (i = l = 0, ref1 = count; 0 <= ref1 ? l < ref1 : l > ref1; i = 0 <= ref1 ? ++l : --l) { angle = this['circleStartAngle'] + i * angleStep; results.push(new gm.Point(centerPt.x + legLength * Math.cos(angle), centerPt.y + legLength * Math.sin(angle))); } return results; }; p.generatePtsSpiral = function(count, centerPt) { var angle, i, l, legLength, pt, ref1, results; legLength = this['spiralLengthStart']; angle = 0; results = []; for (i = l = 0, ref1 = count; 0 <= ref1 ? l < ref1 : l > ref1; i = 0 <= ref1 ? ++l : --l) { angle += this['spiralFootSeparation'] / legLength + i * 0.0005; pt = new gm.Point(centerPt.x + legLength * Math.cos(angle), centerPt.y + legLength * Math.sin(angle)); legLength += twoPi * this['spiralLengthFactor'] / angle; results.push(pt); } return results; }; p.spiderListener = function(marker, event) { var $this, clear, l, len1, m, mPt, markerPt, markerSpiderfied, nDist, nearbyMarkerData, nonNearbyMarkers, pxSq, ref1; markerSpiderfied = marker['_omsData'] != null; if (!(markerSpiderfied && this['keepSpiderfied'])) { if (this['event'] === 'mouseover') { $this = this; clear = function() { return $this['unspiderfy'](); }; window.clearTimeout(p.timeout); p.timeout = setTimeout(clear, 3000); } else { this['unspiderfy'](); } } if (markerSpiderfied || this.map.getStreetView().getVisible() || this.map.getMapTypeId() === 'GoogleEarthAPI') { return this.trigger('click', marker, event); } else { nearbyMarkerData = []; nonNearbyMarkers = []; nDist = this['nearbyDistance']; pxSq = nDist * nDist; markerPt = this.llToPt(marker.position); ref1 = this.markers; for (l = 0, len1 = ref1.length; l < len1; l++) { m = ref1[l]; if (!((m.map != null) && m.getVisible())) { continue; } mPt = this.llToPt(m.position); if (this.ptDistanceSq(mPt, markerPt) < pxSq) { nearbyMarkerData.push({ marker: m, markerPt: mPt }); } else { nonNearbyMarkers.push(m); } } if (nearbyMarkerData.length === 1) { return this.trigger('click', marker, event); } else { return this.spiderfy(nearbyMarkerData, nonNearbyMarkers); } } }; p['markersNearMarker'] = function(marker, firstOnly) { var l, len1, m, mPt, markerPt, markers, nDist, pxSq, ref1, ref2, ref3; if (firstOnly == null) { firstOnly = false; } if (this.projHelper.getProjection() == null) { throw "Must wait for 'idle' event on map before calling markersNearMarker"; } nDist = this['nearbyDistance']; pxSq = nDist * nDist; markerPt = this.llToPt(marker.position); markers = []; ref1 = this.markers; for (l = 0, len1 = ref1.length; l < len1; l++) { m = ref1[l]; if (m === marker || (m.map == null) || !m.getVisible()) { continue; } mPt = this.llToPt((ref2 = (ref3 = m['_omsData']) != null ? ref3.usualPosition : void 0) != null ? ref2 : m.position); if (this.ptDistanceSq(mPt, markerPt) < pxSq) { markers.push(m); if (firstOnly) { break; } } } return markers; }; p['markersNearAnyOtherMarker'] = function() { var i, i1, i2, l, len1, len2, len3, m, m1, m1Data, m2, m2Data, mData, n, nDist, pxSq, q, ref1, ref2, ref3, results; if (this.projHelper.getProjection() == null) { throw "Must wait for 'idle' event on map before calling markersNearAnyOtherMarker"; } nDist = this['nearbyDistance']; pxSq = nDist * nDist; mData = (function() { var l, len1, ref1, ref2, ref3, results; ref1 = this.markers; results = []; for (l = 0, len1 = ref1.length; l < len1; l++) { m = ref1[l]; results.push({ pt: this.llToPt((ref2 = (ref3 = m['_omsData']) != null ? ref3.usualPosition : void 0) != null ? ref2 : m.position), willSpiderfy: false }); } return results; }).call(this); ref1 = this.markers; for (i1 = l = 0, len1 = ref1.length; l < len1; i1 = ++l) { m1 = ref1[i1]; if (!((m1.map != null) && m1.getVisible())) { continue; } m1Data = mData[i1]; if (m1Data.willSpiderfy) { continue; } ref2 = this.markers; for (i2 = n = 0, len2 = ref2.length; n < len2; i2 = ++n) { m2 = ref2[i2]; if (i2 === i1) { continue; } if (!((m2.map != null) && m2.getVisible())) { continue; } m2Data = mData[i2]; if (i2 < i1 && !m2Data.willSpiderfy) { continue; } if (this.ptDistanceSq(m1Data.pt, m2Data.pt) < pxSq) { m1Data.willSpiderfy = m2Data.willSpiderfy = true; break; } } } ref3 = this.markers; results = []; for (i = q = 0, len3 = ref3.length; q < len3; i = ++q) { m = ref3[i]; if (mData[i].willSpiderfy) { results.push(m); } } return results; }; p.makeHighlightListenerFuncs = function(marker) { return { highlight: (function(_this) { return function() { return marker['_omsData'].leg.setOptions({ strokeColor: _this['legColors']['highlighted'][_this.map.mapTypeId], zIndex: _this['highlightedLegZIndex'] }); }; })(this), unhighlight: (function(_this) { return function() { return marker['_omsData'].leg.setOptions({ strokeColor: _this['legColors']['usual'][_this.map.mapTypeId], zIndex: _this['usualLegZIndex'] }); }; })(this) }; }; p.spiderfy = function(markerData, nonNearbyMarkers) { var bodyPt, footLl, footPt, footPts, highlightListenerFuncs, leg, marker, md, nearestMarkerDatum, numFeet, spiderfiedMarkers; if (this['minZoomLevel'] && this.map.getZoom() < this['minZoomLevel']) { return false; } this.spiderfying = true; numFeet = markerData.length; bodyPt = this.ptAverage((function() { var l, len1, results; results = []; for (l = 0, len1 = markerData.length; l < len1; l++) { md = markerData[l]; results.push(md.markerPt); } return results; })()); footPts = numFeet >= this['circleSpiralSwitchover'] ? this.generatePtsSpiral(numFeet, bodyPt).reverse() : this.generatePtsCircle(numFeet, bodyPt); spiderfiedMarkers = (function() { var l, len1, results; results = []; for (l = 0, len1 = footPts.length; l < len1; l++) { footPt = footPts[l]; footLl = this.ptToLl(footPt); nearestMarkerDatum = this.minExtract(markerData, (function(_this) { return function(md) { return _this.ptDistanceSq(md.markerPt, footPt); }; })(this)); marker = nearestMarkerDatum.marker; leg = new gm.Polyline({ map: this.map, path: [marker.position, footLl], strokeColor: this['legColors']['usual'][this.map.mapTypeId], strokeWeight: this['legWeight'], zIndex: this['usualLegZIndex'] }); marker['_omsData'] = { usualPosition: marker.position, leg: leg }; if (this['legColors']['highlighted'][this.map.mapTypeId] !== this['legColors']['usual'][this.map.mapTypeId]) { highlightListenerFuncs = this.makeHighlightListenerFuncs(marker); marker['_omsData'].hightlightListeners = { highlight: ge.addListener(marker, 'mouseover', highlightListenerFuncs.highlight), unhighlight: ge.addListener(marker, 'mouseout', highlightListenerFuncs.unhighlight) }; } marker.setPosition(footLl); marker.setZIndex(Math.round(this['spiderfiedZIndex'] + footPt.y)); results.push(marker); } return results; }).call(this); delete this.spiderfying; this.spiderfied = true; return this.trigger('spiderfy', spiderfiedMarkers, nonNearbyMarkers); }; p['unspiderfy'] = function(markerNotToMove) { var l, len1, listeners, marker, nonNearbyMarkers, ref1, unspiderfiedMarkers; if (markerNotToMove == null) { markerNotToMove = null; } if (this.spiderfied == null) { return this; } this.unspiderfying = true; unspiderfiedMarkers = []; nonNearbyMarkers = []; ref1 = this.markers; for (l = 0, len1 = ref1.length; l < len1; l++) { marker = ref1[l]; if (marker['_omsData'] != null) { marker['_omsData'].leg.setMap(null); if (marker !== markerNotToMove) { marker.setPosition(marker['_omsData'].usualPosition); } marker.setZIndex(null); listeners = marker['_omsData'].hightlightListeners; if (listeners != null) { ge.removeListener(listeners.highlight); ge.removeListener(listeners.unhighlight); } delete marker['_omsData']; unspiderfiedMarkers.push(marker); } else { nonNearbyMarkers.push(marker); } } delete this.unspiderfying; delete this.spiderfied; this.trigger('unspiderfy', unspiderfiedMarkers, nonNearbyMarkers); return this; }; p.ptDistanceSq = function(pt1, pt2) { var dx, dy; dx = pt1.x - pt2.x; dy = pt1.y - pt2.y; return dx * dx + dy * dy; }; p.ptAverage = function(pts) { var l, len1, numPts, pt, sumX, sumY; sumX = sumY = 0; for (l = 0, len1 = pts.length; l < len1; l++) { pt = pts[l]; sumX += pt.x; sumY += pt.y; } numPts = pts.length; return new gm.Point(sumX / numPts, sumY / numPts); }; p.llToPt = function(ll) { return this.projHelper.getProjection().fromLatLngToDivPixel(ll); }; p.ptToLl = function(pt) { return this.projHelper.getProjection().fromDivPixelToLatLng(pt); }; p.minExtract = function(set, func) { var bestIndex, bestVal, index, item, l, len1, val; for (index = l = 0, len1 = set.length; l < len1; index = ++l) { item = set[index]; val = func(item); if ((typeof bestIndex === "undefined" || bestIndex === null) || val < bestVal) { bestVal = val; bestIndex = index; } } return set.splice(bestIndex, 1)[0]; }; p.arrIndexOf = function(arr, obj) { var i, l, len1, o; if (arr.indexOf != null) { return arr.indexOf(obj); } for (i = l = 0, len1 = arr.length; l < len1; i = ++l) { o = arr[i]; if (o === obj) { return i; } } return -1; }; return _Class; })(); }.apply(self); GoogleMapApi.then(function(){ self.OverlappingMarkerSpiderfier.initializeGoogleMaps(window.google); }); return this.OverlappingMarkerSpiderfier; }]); ;/** * Performance overrides on MarkerClusterer custom to Angular Google Maps * * Created by Petr Bruna ccg1415 and Nick McCready on 7/13/14. */ angular.module('uiGmapgoogle-maps.extensions') .service('uiGmapExtendMarkerClusterer',['uiGmapLodash', 'uiGmapPropMap', function (uiGmapLodash, PropMap) { return { init: _.once(function () { (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; }; window.NgMapCluster = (function (_super) { __extends(NgMapCluster, _super); function NgMapCluster(opts) { NgMapCluster.__super__.constructor.call(this, opts); this.markers_ = new PropMap(); } /** * Adds a marker to the cluster. * * @param {google.maps.Marker} marker The marker to be added. * @return {boolean} True if the marker was added. * @ignore */ NgMapCluster.prototype.addMarker = function (marker) { var i; var mCount; var mz; if (this.isMarkerAlreadyAdded_(marker)) { var oldMarker = this.markers_.get(marker.key); if (oldMarker.getPosition().lat() == marker.getPosition().lat() && oldMarker.getPosition().lon() == marker.getPosition().lon()) //if nothing has changed return false; } if (!this.center_) { this.center_ = marker.getPosition(); this.calculateBounds_(); } else { if (this.averageCenter_) { var l = this.markers_.length + 1; var lat = (this.center_.lat() * (l - 1) + marker.getPosition().lat()) / l; var lng = (this.center_.lng() * (l - 1) + marker.getPosition().lng()) / l; this.center_ = new google.maps.LatLng(lat, lng); this.calculateBounds_(); } } marker.isAdded = true; this.markers_.push(marker); mCount = this.markers_.length; mz = this.markerClusterer_.getMaxZoom(); if (mz !== null && this.map_.getZoom() > mz) { // Zoomed in past max zoom, so show the marker. if (marker.getMap() !== this.map_) { marker.setMap(this.map_); } } else if (mCount < this.minClusterSize_) { // Min cluster size not reached so show the marker. if (marker.getMap() !== this.map_) { marker.setMap(this.map_); } } else if (mCount === this.minClusterSize_) { // Hide the markers that were showing. this.markers_.each(function (m) { m.setMap(null); }); } else { marker.setMap(null); } //this.updateIcon_(); return true; }; /** * Determines if a marker has already been added to the cluster. * * @param {google.maps.Marker} marker The marker to check. * @return {boolean} True if the marker has already been added. */ NgMapCluster.prototype.isMarkerAlreadyAdded_ = function (marker) { return uiGmapLodash.isNullOrUndefined(this.markers_.get(marker.key)); }; /** * Returns the bounds of the cluster. * * @return {google.maps.LatLngBounds} the cluster bounds. * @ignore */ NgMapCluster.prototype.getBounds = function () { var i; var bounds = new google.maps.LatLngBounds(this.center_, this.center_); this.getMarkers().each(function(m){ bounds.extend(m.getPosition()); }); return bounds; }; /** * Removes the cluster from the map. * * @ignore */ NgMapCluster.prototype.remove = function () { this.clusterIcon_.setMap(null); this.markers_ = new PropMap(); delete this.markers_; }; return NgMapCluster; })(Cluster); window.NgMapMarkerClusterer = (function (_super) { __extends(NgMapMarkerClusterer, _super); function NgMapMarkerClusterer(map, opt_markers, opt_options) { NgMapMarkerClusterer.__super__.constructor.call(this, map, opt_markers, opt_options); this.markers_ = new PropMap(); } /** * Removes all clusters and markers from the map and also removes all markers * managed by the clusterer. */ NgMapMarkerClusterer.prototype.clearMarkers = function () { this.resetViewport_(true); this.markers_ = new PropMap(); }; /** * Removes a marker and returns true if removed, false if not. * * @param {google.maps.Marker} marker The marker to remove * @return {boolean} Whether the marker was removed or not */ NgMapMarkerClusterer.prototype.removeMarker_ = function (marker) { if (!this.markers_.get(marker.key)) { return false; } marker.setMap(null); this.markers_.remove(marker.key); // Remove the marker from the list of managed markers return true; }; /** * Creates the clusters. This is done in batches to avoid timeout errors * in some browsers when there is a huge number of markers. * * @param {number} iFirst The index of the first marker in the batch of * markers to be added to clusters. */ NgMapMarkerClusterer.prototype.createClusters_ = function (iFirst) { var i, marker; var mapBounds; var cMarkerClusterer = this; if (!this.ready_) { return; } // Cancel previous batch processing if we're working on the first batch: if (iFirst === 0) { /** * This event is fired when the <code>MarkerClusterer</code> begins * clustering markers. * @name MarkerClusterer#clusteringbegin * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered. * @event */ google.maps.event.trigger(this, 'clusteringbegin', this); if (typeof this.timerRefStatic !== 'undefined') { clearTimeout(this.timerRefStatic); delete this.timerRefStatic; } } // Get our current map view bounds. // Create a new bounds object so we don't affect the map. // // See Comments 9 & 11 on Issue 3651 relating to this workaround for a Google Maps bug: if (this.getMap().getZoom() > 3) { mapBounds = new google.maps.LatLngBounds(this.getMap().getBounds().getSouthWest(), this.getMap().getBounds().getNorthEast()); } else { mapBounds = new google.maps.LatLngBounds(new google.maps.LatLng(85.02070771743472, -178.48388434375), new google.maps.LatLng(-85.08136444384544, 178.00048865625)); } var bounds = this.getExtendedBounds(mapBounds); var iLast = Math.min(iFirst + this.batchSize_, this.markers_.length); var _ms = this.markers_.values(); for (i = iFirst; i < iLast; i++) { marker = _ms[i]; if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) { if (!this.ignoreHidden_ || (this.ignoreHidden_ && marker.getVisible())) { this.addToClosestCluster_(marker); } } } if (iLast < this.markers_.length) { this.timerRefStatic = setTimeout(function () { cMarkerClusterer.createClusters_(iLast); }, 0); } else { // custom addition by ui-gmap // update icon for all clusters for (i = 0; i < this.clusters_.length; i++) { this.clusters_[i].updateIcon_(); } delete this.timerRefStatic; /** * This event is fired when the <code>MarkerClusterer</code> stops * clustering markers. * @name MarkerClusterer#clusteringend * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered. * @event */ google.maps.event.trigger(this, 'clusteringend', this); } }; /** * Adds a marker to a cluster, or creates a new cluster. * * @param {google.maps.Marker} marker The marker to add. */ NgMapMarkerClusterer.prototype.addToClosestCluster_ = function (marker) { var i, d, cluster, center; var distance = 40000; // Some large number var clusterToAddTo = null; for (i = 0; i < this.clusters_.length; i++) { cluster = this.clusters_[i]; center = cluster.getCenter(); if (center) { d = this.distanceBetweenPoints_(center, marker.getPosition()); if (d < distance) { distance = d; clusterToAddTo = cluster; } } } if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) { clusterToAddTo.addMarker(marker); } else { cluster = new NgMapCluster(this); cluster.addMarker(marker); this.clusters_.push(cluster); } }; /** * Redraws all the clusters. */ NgMapMarkerClusterer.prototype.redraw_ = function () { this.createClusters_(0); }; /** * Removes all clusters from the map. The markers are also removed from the map * if <code>opt_hide</code> is set to <code>true</code>. * * @param {boolean} [opt_hide] Set to <code>true</code> to also remove the markers * from the map. */ NgMapMarkerClusterer.prototype.resetViewport_ = function (opt_hide) { var i, marker; // Remove all the clusters for (i = 0; i < this.clusters_.length; i++) { this.clusters_[i].remove(); } this.clusters_ = []; // Reset the markers to not be added and to be removed from the map. this.markers_.each(function (marker) { marker.isAdded = false; if (opt_hide) { marker.setMap(null); } }); }; /** * Extends an object's prototype by another's. * * @param {Object} obj1 The object to be extended. * @param {Object} obj2 The object to extend with. * @return {Object} The new extended object. * @ignore */ NgMapMarkerClusterer.prototype.extend = function (obj1, obj2) { return (function (object) { var property; for (property in object.prototype) { if (property !== 'constructor') this.prototype[property] = object.prototype[property]; } return this; }).apply(obj1, [obj2]); }; //////////////////////////////////////////////////////////////////////////////// /* Other overrides relevant to MarkerClusterPlus */ //////////////////////////////////////////////////////////////////////////////// /** * Positions and shows the icon. */ ClusterIcon.prototype.show = function () { if (this.div_) { var img = ""; // NOTE: values must be specified in px units var bp = this.backgroundPosition_.split(" "); var spriteH = parseInt(bp[0].trim(), 10); var spriteV = parseInt(bp[1].trim(), 10); var pos = this.getPosFromLatLng_(this.center_); this.div_.style.cssText = this.createCss(pos); img = "<img src='" + this.url_ + "' style='position: absolute; top: " + spriteV + "px; left: " + spriteH + "px; "; if (!this.cluster_.getMarkerClusterer().enableRetinaIcons_) { img += "clip: rect(" + (-1 * spriteV) + "px, " + ((-1 * spriteH) + this.width_) + "px, " + ((-1 * spriteV) + this.height_) + "px, " + (-1 * spriteH) + "px);"; } // ADDED FOR RETINA SUPPORT else { img += "width: " + this.width_ + "px;" + "height: " + this.height_ + "px;"; } // END ADD img += "'>"; this.div_.innerHTML = img + "<div style='" + "position: absolute;" + "top: " + this.anchorText_[0] + "px;" + "left: " + this.anchorText_[1] + "px;" + "color: " + this.textColor_ + ";" + "font-size: " + this.textSize_ + "px;" + "font-family: " + this.fontFamily_ + ";" + "font-weight: " + this.fontWeight_ + ";" + "font-style: " + this.fontStyle_ + ";" + "text-decoration: " + this.textDecoration_ + ";" + "text-align: center;" + "width: " + this.width_ + "px;" + "line-height:" + this.height_ + "px;" + "'>" + this.sums_.text + "</div>"; if (typeof this.sums_.title === "undefined" || this.sums_.title === "") { this.div_.title = this.cluster_.getMarkerClusterer().getTitle(); } else { this.div_.title = this.sums_.title; } this.div_.style.display = ""; } this.visible_ = true; }; //END OTHER OVERRIDES //////////////////////////////////////////////////////////////////////////////// return NgMapMarkerClusterer; })(MarkerClusterer); }).call(this); }) }; }]); }( window, angular, _)); //# sourceMappingURL=angular-google-maps_dev_mapped.js.map
src/Parser/Monk/Mistweaver/CombatLogParser.js
hasseboulen/WoWAnalyzer
import React from 'react'; import CoreCombatLogParser from 'Parser/Core/CombatLogParser'; import Tab from 'Main/Tab'; import Mana from 'Main/Mana'; import MonkSpreadsheet from 'Main/MonkSpreadsheet'; import LowHealthHealing from 'Parser/Core/Modules/LowHealthHealing'; import HealingDone from 'Parser/Core/Modules/HealingDone'; import GlobalCooldown from './Modules/Core/GlobalCooldown'; import Channeling from './Modules/Core/Channeling'; // Features import Abilities from './Modules/Features/Abilities'; import CooldownThroughputTracker from './Modules/Features/CooldownThroughputTracker'; import AlwaysBeCasting from './Modules/Features/AlwaysBeCasting'; import EssenceFontMastery from './Modules/Features/EssenceFontMastery'; import Checklist from './Modules/Features/Checklist'; import StatValues from './Modules/Features/StatValues'; // Traits import MistsOfSheilun from './Modules/Traits/MistsOfSheilun'; import CelestialBreath from './Modules/Traits/CelestialBreath'; import WhispersOfShaohao from './Modules/Traits/WhispersOfShaohao'; import CoalescingMists from './Modules/Traits/CoalescingMists'; import SoothingRemedies from './Modules/Traits/SoothingRemedies'; import EssenceOfTheMist from './Modules/Traits/EssenceOfTheMist'; import WayOfTheMistweaver from './Modules/Traits/WayOfTheMistweaver'; import InfusionOfLife from './Modules/Traits/InfusionOfLife'; import ProtectionOfShaohao from './Modules/Traits/ProtectionOfShaohao'; import ExtendedHealing from './Modules/Traits/ExtendedHealing'; import RelicTraits from './Modules/Traits/RelicTraits'; // Spells import UpliftingTrance from './Modules/Spells/UpliftingTrance'; import ThunderFocusTea from './Modules/Spells/ThunderFocusTea'; import SheilunsGift from './Modules/Spells/SheilunsGift'; import RenewingMist from './Modules/Spells/RenewingMist'; import EssenceFont from './Modules/Spells/EssenceFont'; import EnvelopingMists from './Modules/Spells/EnvelopingMists'; import SoothingMist from './Modules/Spells/SoothingMist'; // Talents import ChiJi from './Modules/Talents/ChiJi'; import ChiBurst from './Modules/Talents/ChiBurst'; import ManaTea from './Modules/Talents/ManaTea'; import RefreshingJadeWind from './Modules/Talents/RefreshingJadeWind'; import Lifecycles from './Modules/Talents/Lifecycles'; import SpiritOfTheCrane from './Modules/Talents/SpiritOfTheCrane'; // Items import DrapeOfShame from './Modules/Items/DrapeOfShame'; import Eithas from './Modules/Items/Eithas'; import T20_4set from './Modules/Items/T20_4set'; import T20_2set from './Modules/Items/T20_2set'; import ShelterOfRin from './Modules/Items/ShelterOfRin'; import DoorwayToNowhere from './Modules/Items/DoorwayToNowhere'; import PetrichorLagniappe from './Modules/Items/PetrichorLagniappe'; import OvydsWinterWrap from './Modules/Items/OvydsWinterWrap'; import T21_2set from './Modules/Items/T21_2set'; import T21_4set from './Modules/Items/T21_4set'; import { ABILITIES_AFFECTED_BY_HEALING_INCREASES } from './Constants'; class CombatLogParser extends CoreCombatLogParser { static abilitiesAffectedByHealingIncreases = ABILITIES_AFFECTED_BY_HEALING_INCREASES; static specModules = { // Core lowHealthHealing: LowHealthHealing, healingDone: [HealingDone, { showStatistic: true }], channeling: Channeling, globalCooldown: GlobalCooldown, // Features alwaysBeCasting: AlwaysBeCasting, abilities: Abilities, cooldownThroughputTracker: CooldownThroughputTracker, essenceFontMastery: EssenceFontMastery, checklist: Checklist, statValues: StatValues, // Traits mistsOfSheilun: MistsOfSheilun, celestialBreath: CelestialBreath, whispersOfShaohao: WhispersOfShaohao, coalescingMists: CoalescingMists, soothingRemedies: SoothingRemedies, essenceOfTheMist: EssenceOfTheMist, wayOfTheMistweaver: WayOfTheMistweaver, infusionOfLife: InfusionOfLife, protectionOfShaohao: ProtectionOfShaohao, extendedHealing: ExtendedHealing, relicTraits: RelicTraits, // Spells essenceFont: EssenceFont, renewingMist: RenewingMist, sheilunsGift: SheilunsGift, thunderFocusTea: ThunderFocusTea, upliftingTrance: UpliftingTrance, envelopingMists: EnvelopingMists, soothingMist: SoothingMist, // Talents chiBurst: ChiBurst, chiJi: ChiJi, manaTea: ManaTea, refreshingJadeWind: RefreshingJadeWind, lifecycles: Lifecycles, spiritOfTheCrane: SpiritOfTheCrane, // Legendaries / Items: drapeOfShame: DrapeOfShame, eithas: Eithas, t20_4set: T20_4set, t20_2set: T20_2set, shelterOfRin: ShelterOfRin, doorwayToNowhere: DoorwayToNowhere, petrichorLagniappe: PetrichorLagniappe, ovydsWinterWrap: OvydsWinterWrap, t21_2set: T21_2set, t21_4set: T21_4set, }; generateResults() { const results = super.generateResults(); results.tabs = [ ...results.tabs, { title: 'Mana', url: 'mana', render: () => ( <Tab title="Mana" style={{ padding: '15px 22px' }}> <Mana parser={this} /> </Tab> ), }, { title: 'Player Log Data', url: 'player-log-data', render: () => ( <Tab title="Player Log Data" style={{ padding: '15px 22px 15px 15px' }}> <MonkSpreadsheet parser={this} /> </Tab> ), }, ]; return results; } } export default CombatLogParser;
app/components/LoadingIndicator/index.js
BartoszBazanski/react-100-pushup-challenge
import React from 'react'; import Circle from './Circle'; import Wrapper from './Wrapper'; const LoadingIndicator = () => ( <Wrapper> <Circle /> <Circle rotate={30} delay={-1.1} /> <Circle rotate={60} delay={-1} /> <Circle rotate={90} delay={-0.9} /> <Circle rotate={120} delay={-0.8} /> <Circle rotate={150} delay={-0.7} /> <Circle rotate={180} delay={-0.6} /> <Circle rotate={210} delay={-0.5} /> <Circle rotate={240} delay={-0.4} /> <Circle rotate={270} delay={-0.3} /> <Circle rotate={300} delay={-0.2} /> <Circle rotate={330} delay={-0.1} /> </Wrapper> ); export default LoadingIndicator;
ajax/libs/instantsearch.js/0.8.0/instantsearch.min.js
jonobr1/cdnjs
/*! instantsearch.js 0.8.0 | © Algolia Inc. and other contributors; Licensed MIT | github.com/algolia/instantsearch.js */ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.instantsearch=t():e.instantsearch=t()}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return e[r].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){"use strict";e.exports=n(1)},function(e,t,n){"use strict";n(2);var r=n(3),o=n(4),i=r(o),a=n(72);i.widgets={hierarchicalMenu:n(216),hits:n(382),hitsPerPageSelector:n(385),indexSelector:n(387),menu:n(388),refinementList:n(390),pagination:n(392),priceRanges:n(399),searchBox:n(404),rangeSlider:n(406),stats:n(414),toggle:n(417)},i.version=n(214),i.createQueryString=a.url.getQueryStringFromState,e.exports=i},function(){"use strict";Object.freeze||(Object.freeze=function(e){if(Object(e)!==e)throw new TypeError("Object.freeze can only be called on Objects.");return e})},function(e){"use strict";function t(e){var t=function(){for(var t=arguments.length,r=Array(t),o=0;t>o;o++)r[o]=arguments[o];return new(n.apply(e,[null].concat(r)))};return t.__proto__=e,t.prototype=e.prototype,t}var n=Function.prototype.bind;e.exports=t},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function i(){return"#"}function a(e,t){if(!t.getConfiguration)return e;var n=t.getConfiguration(e);return f({},e,n,function(e,t){return Array.isArray(e)?h(e,t):void 0})}var s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),u=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;return void 0===u?void 0:u.call(a)}var c=Object.getPrototypeOf(o);if(null===c)return void 0;e=c,t=i,n=a,r=!0,s=c=void 0}},c=n(5),l=n(72),p=n(17),f=n(53),h=n(211),d=n(63).EventEmitter,v=n(213),m=function(e){function t(e){var n=e.appId,o=void 0===n?null:n,i=e.apiKey,a=void 0===i?null:i,s=e.indexName,l=void 0===s?null:s,p=e.numberLocale,f=void 0===p?"en-EN":p,h=e.searchParameters,d=void 0===h?{}:h,v=e.urlSync,m=void 0===v?null:v;if(r(this,t),u(Object.getPrototypeOf(t.prototype),"constructor",this).call(this),null===o||null===a||null===l){var g="\nUsage: instantsearch({\n appId: 'my_application_id',\n apiKey: 'my_search_api_key',\n indexName: 'my_index_name'\n});";throw new Error(g)}var y=c(o,a);this.client=y,this.helper=null,this.indexName=l,this.searchParameters=d||{},this.widgets=[],this.templatesConfig={helpers:{formatNumber:function(e,t){return Number(t(e)).toLocaleString(f)}},compileOptions:{}},this.urlSync=m}return o(t,e),s(t,[{key:"addWidget",value:function(e){this.widgets.push(e)}},{key:"start",value:function(){if(!this.widgets)throw new Error("No widgets were added to instantsearch.js");if(this.urlSync){var e=v(this.urlSync);this._createURL=e.createURL.bind(e),this.widgets.push(e)}else this._createURL=i;this.searchParameters=this.widgets.reduce(a,this.searchParameters);var t=l(this.client,this.searchParameters.index||this.indexName,this.searchParameters);this.helper=t,this._init(t.state,t),t.on("result",this._render.bind(this,t)),t.search()}},{key:"createURL",value:function(e){if(!this._createURL)throw new Error("You need to call start() before calling createURL()");return this._createURL(this.helper.state.setQueryParameters(e))}},{key:"_render",value:function(e,t,n){p(this.widgets,function(r){r.render&&r.render({templatesConfig:this.templatesConfig,results:t,state:n,helper:e,createURL:this._createURL})},this),this.emit("render")}},{key:"_init",value:function(e,t){p(this.widgets,function(n){n.init&&n.init(e,t,this.templatesConfig)},this)}}]),t}(d);e.exports=m},function(e,t,n){"use strict";function r(e,t,i){var a=n(69),s=n(70);return i=a(i||{}),void 0===i.protocol&&(i.protocol=s()),i._ua=i._ua||r.ua,new o(e,t,i)}function o(){s.apply(this,arguments)}e.exports=r;var i=n(6),a=window.Promise||n(7).Promise,s=n(12),u=n(16),c=n(64),l=n(68);r.version=n(71),r.ua="Algolia for vanilla JavaScript "+r.version,window.__algolia={debug:n(13),algoliasearch:r};var p={hasXMLHttpRequest:"XMLHttpRequest"in window,hasXDomainRequest:"XDomainRequest"in window,cors:"withCredentials"in new XMLHttpRequest,timeout:"timeout"in new XMLHttpRequest};i(o,s),o.prototype._request=function(e,t){return new a(function(n,r){function o(){if(!l){p.timeout||clearTimeout(s);var e;try{e={body:JSON.parse(h.responseText),responseText:h.responseText,statusCode:h.status,headers:h.getAllResponseHeaders&&h.getAllResponseHeaders()||{}}}catch(t){e=new u.UnparsableJSON({more:h.responseText})}e instanceof u.UnparsableJSON?r(e):n(e)}}function i(e){l||(p.timeout||clearTimeout(s),r(new u.Network({more:e})))}function a(){p.timeout||(l=!0,h.abort()),r(new u.RequestTimeout)}if(!p.cors&&!p.hasXDomainRequest)return void r(new u.Network("CORS not supported"));e=c(e,t.headers);var s,l,f=t.body,h=p.cors?new XMLHttpRequest:new XDomainRequest;h instanceof XMLHttpRequest?h.open(t.method,e,!0):h.open(t.method,e),p.cors&&(f&&("POST"===t.method?h.setRequestHeader("content-type","application/x-www-form-urlencoded"):h.setRequestHeader("content-type","application/json")),h.setRequestHeader("accept","application/json")),h.onprogress=function(){},h.onload=o,h.onerror=i,p.timeout?(h.timeout=t.timeout,h.ontimeout=a):s=setTimeout(a,t.timeout),h.send(f)})},o.prototype._request.fallback=function(e,t){return e=c(e,t.headers),new a(function(n,r){l(e,t,function(e,t){return e?void r(e):void n(t)})})},o.prototype._promise={reject:function(e){return a.reject(e)},resolve:function(e){return a.resolve(e)},delay:function(e){return new a(function(t){setTimeout(t,e)})}}},function(e){e.exports="function"==typeof Object.create?function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:function(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}},function(e,t,n){var r;(function(e,o,i){(function(){"use strict";function a(e){return"function"==typeof e||"object"==typeof e&&null!==e}function s(e){return"function"==typeof e}function u(e){return"object"==typeof e&&null!==e}function c(e){Y=e}function l(e){J=e}function p(){return function(){e.nextTick(m)}}function f(){return function(){Q(m)}}function h(){var e=0,t=new ee(m),n=document.createTextNode("");return t.observe(n,{characterData:!0}),function(){n.data=e=++e%2}}function d(){var e=new MessageChannel;return e.port1.onmessage=m,function(){e.port2.postMessage(0)}}function v(){return function(){setTimeout(m,1)}}function m(){for(var e=0;$>e;e+=2){var t=re[e],n=re[e+1];t(n),re[e]=void 0,re[e+1]=void 0}$=0}function g(){try{var e=n(10);return Q=e.runOnLoop||e.runOnContext,f()}catch(t){return v()}}function y(){}function b(){return new TypeError("You cannot resolve a promise with itself")}function w(){return new TypeError("A promises callback cannot return that same promise.")}function x(e){try{return e.then}catch(t){return se.error=t,se}}function _(e,t,n,r){try{e.call(t,n,r)}catch(o){return o}}function P(e,t,n){J(function(e){var r=!1,o=_(n,t,function(n){r||(r=!0,t!==n?R(e,n):O(e,n))},function(t){r||(r=!0,S(e,t))},"Settle: "+(e._label||" unknown promise"));!r&&o&&(r=!0,S(e,o))},e)}function C(e,t){t._state===ie?O(e,t._result):t._state===ae?S(e,t._result):N(t,void 0,function(t){R(e,t)},function(t){S(e,t)})}function E(e,t){if(t.constructor===e.constructor)C(e,t);else{var n=x(t);n===se?S(e,se.error):void 0===n?O(e,t):s(n)?P(e,t,n):O(e,t)}}function R(e,t){e===t?S(e,b()):a(t)?E(e,t):O(e,t)}function T(e){e._onerror&&e._onerror(e._result),j(e)}function O(e,t){e._state===oe&&(e._result=t,e._state=ie,0!==e._subscribers.length&&J(j,e))}function S(e,t){e._state===oe&&(e._state=ae,e._result=t,J(T,e))}function N(e,t,n,r){var o=e._subscribers,i=o.length;e._onerror=null,o[i]=t,o[i+ie]=n,o[i+ae]=r,0===i&&e._state&&J(j,e)}function j(e){var t=e._subscribers,n=e._state;if(0!==t.length){for(var r,o,i=e._result,a=0;a<t.length;a+=3)r=t[a],o=t[a+n],r?D(n,r,o,i):o(i);e._subscribers.length=0}}function k(){this.error=null}function I(e,t){try{return e(t)}catch(n){return ue.error=n,ue}}function D(e,t,n,r){var o,i,a,u,c=s(n);if(c){if(o=I(n,r),o===ue?(u=!0,i=o.error,o=null):a=!0,t===o)return void S(t,w())}else o=r,a=!0;t._state!==oe||(c&&a?R(t,o):u?S(t,i):e===ie?O(t,o):e===ae&&S(t,o))}function A(e,t){try{t(function(t){R(e,t)},function(t){S(e,t)})}catch(n){S(e,n)}}function M(e,t){var n=this;n._instanceConstructor=e,n.promise=new e(y),n._validateInput(t)?(n._input=t,n.length=t.length,n._remaining=t.length,n._init(),0===n.length?O(n.promise,n._result):(n.length=n.length||0,n._enumerate(),0===n._remaining&&O(n.promise,n._result))):S(n.promise,n._validationError())}function F(e){return new ce(this,e).promise}function U(e){function t(e){R(o,e)}function n(e){S(o,e)}var r=this,o=new r(y);if(!G(e))return S(o,new TypeError("You must pass an array to race.")),o;for(var i=e.length,a=0;o._state===oe&&i>a;a++)N(r.resolve(e[a]),void 0,t,n);return o}function L(e){var t=this;if(e&&"object"==typeof e&&e.constructor===t)return e;var n=new t(y);return R(n,e),n}function B(e){var t=this,n=new t(y);return S(n,e),n}function q(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function H(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function V(e){this._id=de++,this._state=void 0,this._result=void 0,this._subscribers=[],y!==e&&(s(e)||q(),this instanceof V||H(),A(this,e))}function W(){var e;if("undefined"!=typeof o)e=o;else if("undefined"!=typeof self)e=self;else try{e=Function("return this")()}catch(t){throw new Error("polyfill failed because global object is unavailable in this environment")}var n=e.Promise;(!n||"[object Promise]"!==Object.prototype.toString.call(n.resolve())||n.cast)&&(e.Promise=ve)}var K;K=Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)};var Q,Y,z,G=K,$=0,J=({}.toString,function(e,t){re[$]=e,re[$+1]=t,$+=2,2===$&&(Y?Y(m):z())}),X="undefined"!=typeof window?window:void 0,Z=X||{},ee=Z.MutationObserver||Z.WebKitMutationObserver,te="undefined"!=typeof e&&"[object process]"==={}.toString.call(e),ne="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,re=new Array(1e3);z=te?p():ee?h():ne?d():void 0===X?g():v();var oe=void 0,ie=1,ae=2,se=new k,ue=new k;M.prototype._validateInput=function(e){return G(e)},M.prototype._validationError=function(){return new Error("Array Methods must be provided an Array")},M.prototype._init=function(){this._result=new Array(this.length)};var ce=M;M.prototype._enumerate=function(){for(var e=this,t=e.length,n=e.promise,r=e._input,o=0;n._state===oe&&t>o;o++)e._eachEntry(r[o],o)},M.prototype._eachEntry=function(e,t){var n=this,r=n._instanceConstructor;u(e)?e.constructor===r&&e._state!==oe?(e._onerror=null,n._settledAt(e._state,t,e._result)):n._willSettleAt(r.resolve(e),t):(n._remaining--,n._result[t]=e)},M.prototype._settledAt=function(e,t,n){var r=this,o=r.promise;o._state===oe&&(r._remaining--,e===ae?S(o,n):r._result[t]=n),0===r._remaining&&O(o,r._result)},M.prototype._willSettleAt=function(e,t){var n=this;N(e,void 0,function(e){n._settledAt(ie,t,e)},function(e){n._settledAt(ae,t,e)})};var le=F,pe=U,fe=L,he=B,de=0,ve=V;V.all=le,V.race=pe,V.resolve=fe,V.reject=he,V._setScheduler=c,V._setAsap=l,V._asap=J,V.prototype={constructor:V,then:function(e,t){var n=this,r=n._state;if(r===ie&&!e||r===ae&&!t)return this;var o=new this.constructor(y),i=n._result;if(r){var a=arguments[r-1];J(function(){D(r,o,a,i)})}else N(n,o,e,t);return o},"catch":function(e){return this.then(null,e)}};var me=W,ge={Promise:ve,polyfill:me};n(11).amd?(r=function(){return ge}.call(t,n,t,i),!(void 0!==r&&(i.exports=r))):"undefined"!=typeof i&&i.exports?i.exports=ge:"undefined"!=typeof this&&(this.ES6Promise=ge),me()}).call(this)}).call(t,n(8),function(){return this}(),n(9)(e))},function(e){function t(){u=!1,i.length?s=i.concat(s):c=-1,s.length&&n()}function n(){if(!u){var e=setTimeout(t);u=!0;for(var n=s.length;n;){for(i=s,s=[];++c<n;)i&&i[c].run();c=-1,n=s.length}i=null,u=!1,clearTimeout(e)}}function r(e,t){this.fun=e,this.array=t}function o(){}var i,a=e.exports={},s=[],u=!1,c=-1;a.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var o=1;o<arguments.length;o++)t[o-1]=arguments[o];s.push(new r(e,t)),1!==s.length||u||setTimeout(n,0)},r.prototype.run=function(){this.fun.apply(null,this.array)},a.title="browser",a.browser=!0,a.env={},a.argv=[],a.version="",a.versions={},a.on=o,a.addListener=o,a.once=o,a.off=o,a.removeListener=o,a.removeAllListeners=o,a.emit=o,a.binding=function(){throw new Error("process.binding is not supported")},a.cwd=function(){return"/"},a.chdir=function(){throw new Error("process.chdir is not supported")},a.umask=function(){return 0}},function(e){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children=[],e.webpackPolyfill=1),e}},function(){},function(e){e.exports=function(){throw new Error("define cannot be used indirect")}},function(e,t,n){"use strict";function r(e,t,r){var a=n(13)("algoliasearch"),s=n(43),u=n(36),c="Usage: algoliasearch(applicationID, apiKey, opts)";if(!e)throw new f.AlgoliaSearchError("Please provide an application ID. "+c);if(!t)throw new f.AlgoliaSearchError("Please provide an API key. "+c);this.applicationID=e,this.apiKey=t;var l=[this.applicationID+"-1.algolianet.com",this.applicationID+"-2.algolianet.com",this.applicationID+"-3.algolianet.com"];this.hosts={read:[],write:[]},this.hostIndex={read:0,write:0},r=r||{};var p=r.protocol||"https:",h=void 0===r.timeout?2e3:r.timeout;if(/:$/.test(p)||(p+=":"),"http:"!==r.protocol&&"https:"!==r.protocol)throw new f.AlgoliaSearchError("protocol must be `http:` or `https:` (was `"+r.protocol+"`)");r.hosts?u(r.hosts)?(this.hosts.read=s(r.hosts),this.hosts.write=s(r.hosts)):(this.hosts.read=s(r.hosts.read),this.hosts.write=s(r.hosts.write)):(this.hosts.read=[this.applicationID+"-dsn.algolia.net"].concat(l),this.hosts.write=[this.applicationID+".algolia.net"].concat(l)),this.hosts.read=o(this.hosts.read,i(p)),this.hosts.write=o(this.hosts.write,i(p)),this.requestTimeout=h,this.extraHeaders=[],this.cache={},this._ua=r._ua,this._useCache=void 0===r._useCache?!0:r._useCache,this._setTimeout=r._setTimeout,a("init done, %j",this)}function o(e,t){for(var n=[],r=0;r<e.length;++r)n.push(t(e[r],r));return n}function i(e){return function(t){return e+"//"+t.toLowerCase()}}function a(){var e="Not implemented in this environment.\nIf you feel this is a mistake, write to [email protected]";throw new f.AlgoliaSearchError(e)}function s(e,t){var n=e.toLowerCase().replace(".","").replace("()","");return"algoliasearch: `"+e+"` was replaced by `"+t+"`. Please see https://github.com/algolia/algoliasearch-client-js/wiki/Deprecated#"+n}function u(e,t){t(e,0)}function c(e,t){function n(){return r||(console.log(t),r=!0),e.apply(this,arguments)}var r=!1;return n}function l(e){if(void 0===Array.prototype.toJSON)return JSON.stringify(e);var t=Array.prototype.toJSON;delete Array.prototype.toJSON;var n=JSON.stringify(e);return Array.prototype.toJSON=t,n}function p(e){return function(t,n,r){if("function"==typeof t&&"object"==typeof n||"object"==typeof r)throw new f.AlgoliaSearchError("index.search usage is index.search(query, params, cb)");0===arguments.length||"function"==typeof t?(r=t,t=""):(1===arguments.length||"function"==typeof n)&&(r=n,n=void 0),"object"==typeof t&&null!==t?(n=t,t=void 0):(void 0===t||null===t)&&(t="");var o="";return void 0!==t&&(o+=e+"="+encodeURIComponent(t)),void 0!==n&&(o=this.as._getSearchParams(n,o)),this._search(o,r)}}e.exports=r,"development"==={NODE_ENV:"production"}.APP_ENV&&n(13).enable("algoliasearch*");var f=n(16);r.prototype={deleteIndex:function(e,t){return this._jsonRequest({method:"DELETE",url:"/1/indexes/"+encodeURIComponent(e),hostType:"write",callback:t})},moveIndex:function(e,t,n){var r={operation:"move",destination:t};return this._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(e)+"/operation",body:r,hostType:"write",callback:n})},copyIndex:function(e,t,n){var r={operation:"copy",destination:t};return this._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(e)+"/operation",body:r,hostType:"write",callback:n})},getLogs:function(e,t,n){return 0===arguments.length||"function"==typeof e?(n=e,e=0,t=10):(1===arguments.length||"function"==typeof t)&&(n=t,t=10),this._jsonRequest({method:"GET",url:"/1/logs?offset="+e+"&length="+t,hostType:"read",callback:n})},listIndexes:function(e,t){var n="";return void 0===e||"function"==typeof e?t=e:n="?page="+e,this._jsonRequest({method:"GET",url:"/1/indexes"+n,hostType:"read",callback:t})},initIndex:function(e){return new this.Index(this,e)},listUserKeys:function(e){return this._jsonRequest({method:"GET",url:"/1/keys",hostType:"read",callback:e})},getUserKeyACL:function(e,t){return this._jsonRequest({method:"GET",url:"/1/keys/"+e,hostType:"read",callback:t})},deleteUserKey:function(e,t){return this._jsonRequest({method:"DELETE",url:"/1/keys/"+e,hostType:"write",callback:t})},addUserKey:function(e,t,n){(1===arguments.length||"function"==typeof t)&&(n=t,t=null);var r={acl:e};return t&&(r.validity=t.validity,r.maxQueriesPerIPPerHour=t.maxQueriesPerIPPerHour,r.maxHitsPerQuery=t.maxHitsPerQuery,r.indexes=t.indexes,r.description=t.description,t.queryParameters&&(r.queryParameters=this._getSearchParams(t.queryParameters,"")),r.referers=t.referers),this._jsonRequest({method:"POST",url:"/1/keys",body:r,hostType:"write",callback:n})},addUserKeyWithValidity:c(function(e,t,n){return this.addUserKey(e,t,n)},s("client.addUserKeyWithValidity()","client.addUserKey()")),updateUserKey:function(e,t,n,r){(2===arguments.length||"function"==typeof n)&&(r=n,n=null);var o={acl:t};return n&&(o.validity=n.validity,o.maxQueriesPerIPPerHour=n.maxQueriesPerIPPerHour,o.maxHitsPerQuery=n.maxHitsPerQuery,o.indexes=n.indexes,o.description=n.description,n.queryParameters&&(o.queryParameters=this._getSearchParams(n.queryParameters,"")),o.referers=n.referers),this._jsonRequest({method:"PUT",url:"/1/keys/"+e,body:o,hostType:"write",callback:r})},setSecurityTags:function(e){if("[object Array]"===Object.prototype.toString.call(e)){for(var t=[],n=0;n<e.length;++n)if("[object Array]"===Object.prototype.toString.call(e[n])){for(var r=[],o=0;o<e[n].length;++o)r.push(e[n][o]);t.push("("+r.join(",")+")")}else t.push(e[n]);e=t.join(",")}this.securityTags=e},setUserToken:function(e){this.userToken=e},startQueriesBatch:c(function(){this._batch=[]},s("client.startQueriesBatch()","client.search()")),addQueryInBatch:c(function(e,t,n){this._batch.push({indexName:e,query:t,params:n})},s("client.addQueryInBatch()","client.search()")),clearCache:function(){this.cache={}},sendQueriesBatch:c(function(e){return this.search(this._batch,e)},s("client.sendQueriesBatch()","client.search()")),setRequestTimeout:function(e){e&&(this.requestTimeout=parseInt(e,10))},search:function(e,t){var n=this,r={requests:o(e,function(e){var t="";return void 0!==e.query&&(t+="query="+encodeURIComponent(e.query)),{indexName:e.indexName,params:n._getSearchParams(e.params,t)}})};return this._jsonRequest({cache:this.cache,method:"POST",url:"/1/indexes/*/queries",body:r,hostType:"read",callback:t})},batch:function(e,t){return this._jsonRequest({method:"POST",url:"/1/indexes/*/batch",body:{requests:e},hostType:"write",callback:t})},destroy:a,enableRateLimitForward:a,disableRateLimitForward:a,useSecuredAPIKey:a,disableSecuredAPIKey:a,generateSecuredApiKey:a,Index:function(e,t){this.indexName=t,this.as=e,this.typeAheadArgs=null,this.typeAheadValueOption=null,this.cache={}},setExtraHeader:function(e,t){this.extraHeaders.push({name:e.toLowerCase(),value:t})},addAlgoliaAgent:function(e){this._ua+=";"+e},_sendQueriesBatch:function(e,t){function n(){for(var t="",n=0;n<e.requests.length;++n){var r="/1/indexes/"+encodeURIComponent(e.requests[n].indexName)+"?"+e.requests[n].params;t+=n+"="+encodeURIComponent(r)+"&"}return t}return this._jsonRequest({cache:this.cache,method:"POST",url:"/1/indexes/*/queries",body:e,hostType:"read",fallback:{method:"GET",url:"/1/indexes/*",body:{params:n()}},callback:t})},_jsonRequest:function(e){function t(n,u){function p(e){var t=e&&e.body&&e.body.message&&e.body.status||e.statusCode||e&&e.body&&200;o("received response: statusCode: %s, computed statusCode: %d, headers: %j",e.statusCode,t,e.headers),{NODE_ENV:"production"}.DEBUG&&-1!=={NODE_ENV:"production"}.DEBUG.indexOf("debugBody")&&o("body: %j",e.body);var n=200===t||201===t,r=!n&&4!==Math.floor(t/100)&&1!==Math.floor(t/100);if(a._useCache&&n&&i&&(i[v]=e.responseText),n)return e.body;if(r)return s+=1,d();var u=new f.AlgoliaSearchError(e.body&&e.body.message);return a._promise.reject(u)}function h(r){return o("error: %s, stack: %s",r.message,r.stack),r instanceof f.AlgoliaSearchError||(r=new f.Unknown(r&&r.message,r)),s+=1,r instanceof f.Unknown||r instanceof f.UnparsableJSON||s>=a.hosts[e.hostType].length&&(c||!e.fallback||!a._request.fallback)?a._promise.reject(r):(a.hostIndex[e.hostType]=++a.hostIndex[e.hostType]%a.hosts[e.hostType].length,r instanceof f.RequestTimeout?d():(a._request.fallback&&!a.useFallback&&(a.useFallback=!0),t(n,u)))}function d(){return a.hostIndex[e.hostType]=++a.hostIndex[e.hostType]%a.hosts[e.hostType].length,u.timeout=a.requestTimeout*(s+1),t(n,u)}var v;if(a._useCache&&(v=e.url),a._useCache&&r&&(v+="_body_"+u.body),a._useCache&&i&&void 0!==i[v])return o("serving response from cache"),a._promise.resolve(JSON.parse(i[v]));if(s>=a.hosts[e.hostType].length||a.useFallback&&!c)return e.fallback&&a._request.fallback&&!c?(o("switching to fallback"),s=0,u.method=e.fallback.method,u.url=e.fallback.url,u.jsonBody=e.fallback.body,u.jsonBody&&(u.body=l(u.jsonBody)),u.timeout=a.requestTimeout*(s+1),a.hostIndex[e.hostType]=0,c=!0,t(a._request.fallback,u)):(o("could not get any response"),a._promise.reject(new f.AlgoliaSearchError("Cannot connect to the AlgoliaSearch API. Send an email to [email protected] to report and resolve the issue. Application id was: "+a.applicationID)));var m=a.hosts[e.hostType][a.hostIndex[e.hostType]]+u.url,g={body:r,jsonBody:e.body,method:u.method,headers:a._computeRequestHeaders(),timeout:u.timeout,debug:o};return o("method: %s, url: %s, headers: %j, timeout: %d",g.method,m,g.headers,g.timeout),n===a._request.fallback&&o("using fallback"),n.call(a,m,g).then(p,h)}var r,o=n(13)("algoliasearch:"+e.url),i=e.cache,a=this,s=0,c=!1;void 0!==e.body&&(r=l(e.body)),o("request start");var p=a.useFallback&&e.fallback,h=p?e.fallback:e,d=t(p?a._request.fallback:a._request,{url:h.url,method:h.method,body:r,jsonBody:e.body,timeout:a.requestTimeout*(s+1)});return e.callback?void d.then(function(t){u(function(){e.callback(null,t)},a._setTimeout||setTimeout)},function(t){u(function(){e.callback(t)},a._setTimeout||setTimeout)}):d},_getSearchParams:function(e,t){if(this._isUndefined(e)||null===e)return t;for(var n in e)null!==n&&void 0!==e[n]&&e.hasOwnProperty(n)&&(t+=""===t?"":"&",t+=n+"="+encodeURIComponent("[object Array]"===Object.prototype.toString.call(e[n])?l(e[n]):e[n]));return t},_isUndefined:function(e){return void 0===e},_computeRequestHeaders:function(){var e=n(17),t={"x-algolia-api-key":this.apiKey,"x-algolia-application-id":this.applicationID,"x-algolia-agent":this._ua};return this.userToken&&(t["x-algolia-usertoken"]=this.userToken),this.securityTags&&(t["x-algolia-tagfilters"]=this.securityTags),this.extraHeaders&&e(this.extraHeaders,function(e){t[e.name]=e.value}),t}},r.prototype.Index.prototype={clearCache:function(){this.cache={}},addObject:function(e,t,n){var r=this;return(1===arguments.length||"function"==typeof t)&&(n=t,t=void 0),this.as._jsonRequest({method:void 0!==t?"PUT":"POST",url:"/1/indexes/"+encodeURIComponent(r.indexName)+(void 0!==t?"/"+encodeURIComponent(t):""),body:e,hostType:"write",callback:n})},addObjects:function(e,t){for(var n=this,r={requests:[]},o=0;o<e.length;++o){var i={action:"addObject",body:e[o]};r.requests.push(i)}return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(n.indexName)+"/batch",body:r,hostType:"write",callback:t})},getObject:function(e,t,n){var r=this;(1===arguments.length||"function"==typeof t)&&(n=t,t=void 0);var o="";if(void 0!==t){o="?attributes=";for(var i=0;i<t.length;++i)0!==i&&(o+=","),o+=t[i]}return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(r.indexName)+"/"+encodeURIComponent(e)+o,hostType:"read",callback:n})},getObjects:function(e,t,n){var r=this;(1===arguments.length||"function"==typeof t)&&(n=t,t=void 0);var i={requests:o(e,function(e){var n={indexName:r.indexName,objectID:e};return t&&(n.attributesToRetrieve=t.join(",")),n})};return this.as._jsonRequest({method:"POST",url:"/1/indexes/*/objects",hostType:"read",body:i,callback:n})},partialUpdateObject:function(e,t){var n=this;return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(n.indexName)+"/"+encodeURIComponent(e.objectID)+"/partial",body:e,hostType:"write",callback:t})},partialUpdateObjects:function(e,t){for(var n=this,r={requests:[]},o=0;o<e.length;++o){var i={action:"partialUpdateObject",objectID:e[o].objectID,body:e[o]};r.requests.push(i)}return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(n.indexName)+"/batch",body:r,hostType:"write",callback:t})},saveObject:function(e,t){var n=this;return this.as._jsonRequest({method:"PUT",url:"/1/indexes/"+encodeURIComponent(n.indexName)+"/"+encodeURIComponent(e.objectID),body:e,hostType:"write",callback:t})},saveObjects:function(e,t){for(var n=this,r={requests:[]},o=0;o<e.length;++o){var i={action:"updateObject",objectID:e[o].objectID,body:e[o]};r.requests.push(i)}return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(n.indexName)+"/batch",body:r,hostType:"write",callback:t})},deleteObject:function(e,t){if("function"==typeof e||"string"!=typeof e&&"number"!=typeof e){var n=new f.AlgoliaSearchError("Cannot delete an object without an objectID");return t=e,"function"==typeof t?t(n):this.as._promise.reject(n)}var r=this;return this.as._jsonRequest({method:"DELETE",url:"/1/indexes/"+encodeURIComponent(r.indexName)+"/"+encodeURIComponent(e),hostType:"write",callback:t})},deleteObjects:function(e,t){var n=this,r={requests:o(e,function(e){return{action:"deleteObject",objectID:e,body:{objectID:e}}})};return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(n.indexName)+"/batch",body:r,hostType:"write",callback:t})},deleteByQuery:function(e,t,r){function i(e){if(0===e.nbHits)return e;var t=o(e.hits,function(e){return e.objectID});return f.deleteObjects(t).then(a).then(s)}function a(e){return f.waitTask(e.taskID)}function s(){return f.deleteByQuery(e,t)}function c(){u(function(){r(null)},h._setTimeout||setTimeout)}function l(e){u(function(){r(e)},h._setTimeout||setTimeout)}var p=n(43),f=this,h=f.as;1===arguments.length||"function"==typeof t?(r=t,t={}):t=p(t),t.attributesToRetrieve="objectID",t.hitsPerPage=1e3,t.distinct=!1,this.clearCache();var d=this.search(e,t).then(i);return r?void d.then(c,l):d},search:p("query"),similarSearch:p("similarQuery"),browse:function(e,t,r){var o,i,a=n(53),s=this;0===arguments.length||1===arguments.length&&"function"==typeof arguments[0]?(o=0,r=arguments[0],e=void 0):"number"==typeof arguments[0]?(o=arguments[0],"number"==typeof arguments[1]?i=arguments[1]:"function"==typeof arguments[1]&&(r=arguments[1],i=void 0),e=void 0,t=void 0):"object"==typeof arguments[0]?("function"==typeof arguments[1]&&(r=arguments[1]),t=arguments[0],e=void 0):"string"==typeof arguments[0]&&"function"==typeof arguments[1]&&(r=arguments[1],t=void 0),t=a({},t||{},{page:o,hitsPerPage:i,query:e});var u=this.as._getSearchParams(t,"");return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(s.indexName)+"/browse?"+u,hostType:"read",callback:r})},browseFrom:function(e,t){return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/browse?cursor="+encodeURIComponent(e),hostType:"read",callback:t})},browseAll:function(e,t){function r(e){if(!s._stopped){var t;t=void 0!==e?"cursor="+encodeURIComponent(e):l,u._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(c.indexName)+"/browse?"+t,hostType:"read",callback:o})}}function o(e,t){return s._stopped?void 0:e?void s._error(e):(s._result(t),void 0===t.cursor?void s._end():void r(t.cursor))}"object"==typeof e&&(t=e,e=void 0);var i=n(53),a=n(62),s=new a,u=this.as,c=this,l=u._getSearchParams(i({},t||{},{query:e}),"");return r(),s},ttAdapter:function(e){var t=this;return function(n,r,o){var i;i="function"==typeof o?o:r,t.search(n,e,function(e,t){return e?void i(e):void i(t.hits)})}},waitTask:function(e,t){function n(){return l._jsonRequest({method:"GET",hostType:"read",url:"/1/indexes/"+encodeURIComponent(c.indexName)+"/task/"+e}).then(function(e){s++;var t=i*s*s;return t>a&&(t=a),"published"!==e.status?l._promise.delay(t).then(n):e})}function r(e){u(function(){t(null,e)},l._setTimeout||setTimeout)}function o(e){u(function(){t(e)},l._setTimeout||setTimeout)}var i=100,a=5e3,s=0,c=this,l=c.as,p=n();return t?void p.then(r,o):p},clearIndex:function(e){var t=this;return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(t.indexName)+"/clear",hostType:"write",callback:e})},getSettings:function(e){var t=this;return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(t.indexName)+"/settings",hostType:"read",callback:e})},setSettings:function(e,t){var n=this;return this.as._jsonRequest({method:"PUT",url:"/1/indexes/"+encodeURIComponent(n.indexName)+"/settings",hostType:"write",body:e,callback:t})},listUserKeys:function(e){var t=this;return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(t.indexName)+"/keys",hostType:"read",callback:e})},getUserKeyACL:function(e,t){var n=this;return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(n.indexName)+"/keys/"+e,hostType:"read",callback:t})},deleteUserKey:function(e,t){var n=this;return this.as._jsonRequest({method:"DELETE",url:"/1/indexes/"+encodeURIComponent(n.indexName)+"/keys/"+e,hostType:"write",callback:t})},addUserKey:function(e,t,n){(1===arguments.length||"function"==typeof t)&&(n=t,t=null);var r={acl:e};return t&&(r.validity=t.validity,r.maxQueriesPerIPPerHour=t.maxQueriesPerIPPerHour,r.maxHitsPerQuery=t.maxHitsPerQuery,r.description=t.description,t.queryParameters&&(r.queryParameters=this.as._getSearchParams(t.queryParameters,"")),r.referers=t.referers),this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/keys",body:r,hostType:"write",callback:n})},addUserKeyWithValidity:c(function(e,t,n){return this.addUserKey(e,t,n)},s("index.addUserKeyWithValidity()","index.addUserKey()")),updateUserKey:function(e,t,n,r){(2===arguments.length||"function"==typeof n)&&(r=n,n=null);var o={acl:t};return n&&(o.validity=n.validity,o.maxQueriesPerIPPerHour=n.maxQueriesPerIPPerHour,o.maxHitsPerQuery=n.maxHitsPerQuery,o.description=n.description,n.queryParameters&&(o.queryParameters=this.as._getSearchParams(n.queryParameters,"")),o.referers=n.referers), this.as._jsonRequest({method:"PUT",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/keys/"+e,body:o,hostType:"write",callback:r})},_search:function(e,t){return this.as._jsonRequest({cache:this.cache,method:"POST",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/query",body:{params:e},hostType:"read",fallback:{method:"GET",url:"/1/indexes/"+encodeURIComponent(this.indexName),body:{params:e}},callback:t})},as:null,indexName:null,typeAheadArgs:null,typeAheadValueOption:null}},function(e,t,n){function r(){return"WebkitAppearance"in document.documentElement.style||window.console&&(console.firebug||console.exception&&console.table)||navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31}function o(){var e=arguments,n=this.useColors;if(e[0]=(n?"%c":"")+this.namespace+(n?" %c":" ")+e[0]+(n?"%c ":" ")+"+"+t.humanize(this.diff),!n)return e;var r="color: "+this.color;e=[e[0],r,"color: inherit"].concat(Array.prototype.slice.call(e,1));var o=0,i=0;return e[0].replace(/%[a-z%]/g,function(e){"%%"!==e&&(o++,"%c"===e&&(i=o))}),e.splice(i,0,r),e}function i(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function a(e){try{null==e?t.storage.removeItem("debug"):t.storage.debug=e}catch(n){}}function s(){var e;try{e=t.storage.debug}catch(n){}return e}function u(){try{return window.localStorage}catch(e){}}t=e.exports=n(14),t.log=i,t.formatArgs=o,t.save=a,t.load=s,t.useColors=r,t.storage="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:u(),t.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],t.formatters.j=function(e){return JSON.stringify(e)},t.enable(s())},function(e,t,n){function r(){return t.colors[l++%t.colors.length]}function o(e){function n(){}function o(){var e=o,n=+new Date,i=n-(c||n);e.diff=i,e.prev=c,e.curr=n,c=n,null==e.useColors&&(e.useColors=t.useColors()),null==e.color&&e.useColors&&(e.color=r());var a=Array.prototype.slice.call(arguments);a[0]=t.coerce(a[0]),"string"!=typeof a[0]&&(a=["%o"].concat(a));var s=0;a[0]=a[0].replace(/%([a-z%])/g,function(n,r){if("%%"===n)return n;s++;var o=t.formatters[r];if("function"==typeof o){var i=a[s];n=o.call(e,i),a.splice(s,1),s--}return n}),"function"==typeof t.formatArgs&&(a=t.formatArgs.apply(e,a));var u=o.log||t.log||console.log.bind(console);u.apply(e,a)}n.enabled=!1,o.enabled=!0;var i=t.enabled(e)?o:n;return i.namespace=e,i}function i(e){t.save(e);for(var n=(e||"").split(/[\s,]+/),r=n.length,o=0;r>o;o++)n[o]&&(e=n[o].replace(/\*/g,".*?"),"-"===e[0]?t.skips.push(new RegExp("^"+e.substr(1)+"$")):t.names.push(new RegExp("^"+e+"$")))}function a(){t.enable("")}function s(e){var n,r;for(n=0,r=t.skips.length;r>n;n++)if(t.skips[n].test(e))return!1;for(n=0,r=t.names.length;r>n;n++)if(t.names[n].test(e))return!0;return!1}function u(e){return e instanceof Error?e.stack||e.message:e}t=e.exports=o,t.coerce=u,t.disable=a,t.enable=i,t.enabled=s,t.humanize=n(15),t.names=[],t.skips=[],t.formatters={};var c,l=0},function(e){function t(e){if(e=""+e,!(e.length>1e4)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]),r=(t[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return n*c;case"days":case"day":case"d":return n*u;case"hours":case"hour":case"hrs":case"hr":case"h":return n*s;case"minutes":case"minute":case"mins":case"min":case"m":return n*a;case"seconds":case"second":case"secs":case"sec":case"s":return n*i;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n}}}}function n(e){return e>=u?Math.round(e/u)+"d":e>=s?Math.round(e/s)+"h":e>=a?Math.round(e/a)+"m":e>=i?Math.round(e/i)+"s":e+"ms"}function r(e){return o(e,u,"day")||o(e,s,"hour")||o(e,a,"minute")||o(e,i,"second")||e+" ms"}function o(e,t,n){return t>e?void 0:1.5*t>e?Math.floor(e/t)+" "+n:Math.ceil(e/t)+" "+n+"s"}var i=1e3,a=60*i,s=60*a,u=24*s,c=365.25*u;e.exports=function(e,o){return o=o||{},"string"==typeof e?t(e):o["long"]?r(e):n(e)}},function(e,t,n){"use strict";function r(e,t){var r=n(17),o=this;"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):o.stack=(new Error).stack||"Cannot get a stacktrace, browser is too old",this.name=this.constructor.name,this.message=e||"Unknown error",t&&r(t,function(e,t){o[t]=e})}function o(e,t){function n(){var n=Array.prototype.slice.call(arguments,0);"string"!=typeof n[0]&&n.unshift(t),r.apply(this,n),this.name="AlgoliaSearch"+e+"Error"}return i(n,r),n}var i=n(6);i(r,Error),e.exports={AlgoliaSearchError:r,UnparsableJSON:o("UnparsableJSON","Could not parse the incoming response as JSON, see err.more for details"),RequestTimeout:o("RequestTimeout","Request timedout before getting a response"),Network:o("Network","Network issue, see err.more for details"),JSONPScriptFail:o("JSONPScriptFail","<script> was loaded but did not call our provided callback"),JSONPScriptError:o("JSONPScriptError","<script> unable to load due to an `error` event on it"),Unknown:o("Unknown","Unknown error occured")}},function(e,t,n){var r=n(18),o=n(19),i=n(40),a=i(r,o);e.exports=a},function(e){function t(e,t){for(var n=-1,r=e.length;++n<r&&t(e[n],n,e)!==!1;);return e}e.exports=t},function(e,t,n){var r=n(20),o=n(39),i=o(r);e.exports=i},function(e,t,n){function r(e,t){return o(e,t,i)}var o=n(21),i=n(25);e.exports=r},function(e,t,n){var r=n(22),o=r();e.exports=o},function(e,t,n){function r(e){return function(t,n,r){for(var i=o(t),a=r(t),s=a.length,u=e?s:-1;e?u--:++u<s;){var c=a[u];if(n(i[c],c,i)===!1)break}return t}}var o=n(23);e.exports=r},function(e,t,n){function r(e){return o(e)?e:Object(e)}var o=n(24);e.exports=r},function(e){function t(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}e.exports=t},function(e,t,n){var r=n(26),o=n(30),i=n(24),a=n(34),s=r(Object,"keys"),u=s?function(e){var t=null==e?void 0:e.constructor;return"function"==typeof t&&t.prototype===e||"function"!=typeof e&&o(e)?a(e):i(e)?s(e):[]}:a;e.exports=u},function(e,t,n){function r(e,t){var n=null==e?void 0:e[t];return o(n)?n:void 0}var o=n(27);e.exports=r},function(e,t,n){function r(e){return null==e?!1:o(e)?l.test(u.call(e)):i(e)&&a.test(e)}var o=n(28),i=n(29),a=/^\[object .+?Constructor\]$/,s=Object.prototype,u=Function.prototype.toString,c=s.hasOwnProperty,l=RegExp("^"+u.call(c).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");e.exports=r},function(e,t,n){function r(e){return o(e)&&s.call(e)==i}var o=n(24),i="[object Function]",a=Object.prototype,s=a.toString;e.exports=r},function(e){function t(e){return!!e&&"object"==typeof e}e.exports=t},function(e,t,n){function r(e){return null!=e&&i(o(e))}var o=n(31),i=n(33);e.exports=r},function(e,t,n){var r=n(32),o=r("length");e.exports=o},function(e){function t(e){return function(t){return null==t?void 0:t[e]}}e.exports=t},function(e){function t(e){return"number"==typeof e&&e>-1&&e%1==0&&n>=e}var n=9007199254740991;e.exports=t},function(e,t,n){function r(e){for(var t=u(e),n=t.length,r=n&&e.length,c=!!r&&s(r)&&(i(e)||o(e)),p=-1,f=[];++p<n;){var h=t[p];(c&&a(h,r)||l.call(e,h))&&f.push(h)}return f}var o=n(35),i=n(36),a=n(37),s=n(33),u=n(38),c=Object.prototype,l=c.hasOwnProperty;e.exports=r},function(e,t,n){function r(e){return i(e)&&o(e)&&s.call(e,"callee")&&!u.call(e,"callee")}var o=n(30),i=n(29),a=Object.prototype,s=a.hasOwnProperty,u=a.propertyIsEnumerable;e.exports=r},function(e,t,n){var r=n(26),o=n(33),i=n(29),a="[object Array]",s=Object.prototype,u=s.toString,c=r(Array,"isArray"),l=c||function(e){return i(e)&&o(e.length)&&u.call(e)==a};e.exports=l},function(e){function t(e,t){return e="number"==typeof e||n.test(e)?+e:-1,t=null==t?r:t,e>-1&&e%1==0&&t>e}var n=/^\d+$/,r=9007199254740991;e.exports=t},function(e,t,n){function r(e){if(null==e)return[];u(e)||(e=Object(e));var t=e.length;t=t&&s(t)&&(i(e)||o(e))&&t||0;for(var n=e.constructor,r=-1,c="function"==typeof n&&n.prototype===e,p=Array(t),f=t>0;++r<t;)p[r]=r+"";for(var h in e)f&&a(h,t)||"constructor"==h&&(c||!l.call(e,h))||p.push(h);return p}var o=n(35),i=n(36),a=n(37),s=n(33),u=n(24),c=Object.prototype,l=c.hasOwnProperty;e.exports=r},function(e,t,n){function r(e,t){return function(n,r){var s=n?o(n):0;if(!i(s))return e(n,r);for(var u=t?s:-1,c=a(n);(t?u--:++u<s)&&r(c[u],u,c)!==!1;);return n}}var o=n(31),i=n(33),a=n(23);e.exports=r},function(e,t,n){function r(e,t){return function(n,r,a){return"function"==typeof r&&void 0===a&&i(n)?e(n,r):t(n,o(r,a,3))}}var o=n(41),i=n(36);e.exports=r},function(e,t,n){function r(e,t,n){if("function"!=typeof e)return o;if(void 0===t)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 3:return function(n,r,o){return e.call(t,n,r,o)};case 4:return function(n,r,o,i){return e.call(t,n,r,o,i)};case 5:return function(n,r,o,i,a){return e.call(t,n,r,o,i,a)}}return function(){return e.apply(t,arguments)}}var o=n(42);e.exports=r},function(e){function t(e){return e}e.exports=t},function(e,t,n){function r(e,t,n,r){return t&&"boolean"!=typeof t&&a(e,t,n)?t=!1:"function"==typeof t&&(r=n,n=t,t=!1),"function"==typeof n?o(e,t,i(n,r,3)):o(e,t)}var o=n(44),i=n(41),a=n(52);e.exports=r},function(e,t,n){function r(e,t,n,d,v,m,g){var b;if(n&&(b=v?n(e,d,v):n(e)),void 0!==b)return b;if(!f(e))return e;var w=p(e);if(w){if(b=u(e),!t)return o(e,b)}else{var _=U.call(e),P=_==y;if(_!=x&&_!=h&&(!P||v))return M[_]?c(e,_,t):v?e:{};if(b=l(P?{}:e),!t)return a(b,e)}m||(m=[]),g||(g=[]);for(var C=m.length;C--;)if(m[C]==e)return g[C];return m.push(e),g.push(b),(w?i:s)(e,function(o,i){b[i]=r(o,t,n,i,e,m,g)}),b}var o=n(45),i=n(18),a=n(46),s=n(20),u=n(48),c=n(49),l=n(51),p=n(36),f=n(24),h="[object Arguments]",d="[object Array]",v="[object Boolean]",m="[object Date]",g="[object Error]",y="[object Function]",b="[object Map]",w="[object Number]",x="[object Object]",_="[object RegExp]",P="[object Set]",C="[object String]",E="[object WeakMap]",R="[object ArrayBuffer]",T="[object Float32Array]",O="[object Float64Array]",S="[object Int8Array]",N="[object Int16Array]",j="[object Int32Array]",k="[object Uint8Array]",I="[object Uint8ClampedArray]",D="[object Uint16Array]",A="[object Uint32Array]",M={};M[h]=M[d]=M[R]=M[v]=M[m]=M[T]=M[O]=M[S]=M[N]=M[j]=M[w]=M[x]=M[_]=M[C]=M[k]=M[I]=M[D]=M[A]=!0,M[g]=M[y]=M[b]=M[P]=M[E]=!1;var F=Object.prototype,U=F.toString;e.exports=r},function(e){function t(e,t){var n=-1,r=e.length;for(t||(t=Array(r));++n<r;)t[n]=e[n];return t}e.exports=t},function(e,t,n){function r(e,t){return null==t?e:o(t,i(t),e)}var o=n(47),i=n(25);e.exports=r},function(e){function t(e,t,n){n||(n={});for(var r=-1,o=t.length;++r<o;){var i=t[r];n[i]=e[i]}return n}e.exports=t},function(e){function t(e){var t=e.length,n=new e.constructor(t);return t&&"string"==typeof e[0]&&r.call(e,"index")&&(n.index=e.index,n.input=e.input),n}var n=Object.prototype,r=n.hasOwnProperty;e.exports=t},function(e,t,n){function r(e,t,n){var r=e.constructor;switch(t){case l:return o(e);case i:case a:return new r(+e);case p:case f:case h:case d:case v:case m:case g:case y:case b:var x=e.buffer;return new r(n?o(x):x,e.byteOffset,e.length);case s:case c:return new r(e);case u:var _=new r(e.source,w.exec(e));_.lastIndex=e.lastIndex}return _}var o=n(50),i="[object Boolean]",a="[object Date]",s="[object Number]",u="[object RegExp]",c="[object String]",l="[object ArrayBuffer]",p="[object Float32Array]",f="[object Float64Array]",h="[object Int8Array]",d="[object Int16Array]",v="[object Int32Array]",m="[object Uint8Array]",g="[object Uint8ClampedArray]",y="[object Uint16Array]",b="[object Uint32Array]",w=/\w*$/;e.exports=r},function(e,t){(function(t){function n(e){var t=new r(e.byteLength),n=new o(t);return n.set(new o(e)),t}var r=t.ArrayBuffer,o=t.Uint8Array;e.exports=n}).call(t,function(){return this}())},function(e){function t(e){var t=e.constructor;return"function"==typeof t&&t instanceof t||(t=Object),new t}e.exports=t},function(e,t,n){function r(e,t,n){if(!a(n))return!1;var r=typeof t;if("number"==r?o(n)&&i(t,n.length):"string"==r&&t in n){var s=n[t];return e===e?e===s:s!==s}return!1}var o=n(30),i=n(37),a=n(24);e.exports=r},function(e,t,n){var r=n(54),o=n(60),i=o(r);e.exports=i},function(e,t,n){function r(e,t,n,f,h){if(!u(e))return e;var d=s(t)&&(a(t)||l(t)),v=d?void 0:p(t);return o(v||t,function(o,a){if(v&&(a=o,o=t[a]),c(o))f||(f=[]),h||(h=[]),i(e,t,a,r,n,f,h);else{var s=e[a],u=n?n(s,o,a,e,t):void 0,l=void 0===u;l&&(u=o),void 0===u&&(!d||a in e)||!l&&(u===u?u===s:s!==s)||(e[a]=u)}}),e}var o=n(18),i=n(55),a=n(36),s=n(30),u=n(24),c=n(29),l=n(58),p=n(25);e.exports=r},function(e,t,n){function r(e,t,n,r,p,f,h){for(var d=f.length,v=t[n];d--;)if(f[d]==v)return void(e[n]=h[d]);var m=e[n],g=p?p(m,v,n,e,t):void 0,y=void 0===g;y&&(g=v,s(v)&&(a(v)||c(v))?g=a(m)?m:s(m)?o(m):[]:u(v)||i(v)?g=i(m)?l(m):u(m)?m:{}:y=!1),f.push(v),h.push(g),y?e[n]=r(g,v,p,f,h):(g===g?g!==m:m===m)&&(e[n]=g)}var o=n(45),i=n(35),a=n(36),s=n(30),u=n(56),c=n(58),l=n(59);e.exports=r},function(e,t,n){function r(e){var t;if(!a(e)||l.call(e)!=s||i(e)||!c.call(e,"constructor")&&(t=e.constructor,"function"==typeof t&&!(t instanceof t)))return!1;var n;return o(e,function(e,t){n=t}),void 0===n||c.call(e,n)}var o=n(57),i=n(35),a=n(29),s="[object Object]",u=Object.prototype,c=u.hasOwnProperty,l=u.toString;e.exports=r},function(e,t,n){function r(e,t){return o(e,t,i)}var o=n(21),i=n(38);e.exports=r},function(e,t,n){function r(e){return i(e)&&o(e.length)&&!!S[j.call(e)]}var o=n(33),i=n(29),a="[object Arguments]",s="[object Array]",u="[object Boolean]",c="[object Date]",l="[object Error]",p="[object Function]",f="[object Map]",h="[object Number]",d="[object Object]",v="[object RegExp]",m="[object Set]",g="[object String]",y="[object WeakMap]",b="[object ArrayBuffer]",w="[object Float32Array]",x="[object Float64Array]",_="[object Int8Array]",P="[object Int16Array]",C="[object Int32Array]",E="[object Uint8Array]",R="[object Uint8ClampedArray]",T="[object Uint16Array]",O="[object Uint32Array]",S={};S[w]=S[x]=S[_]=S[P]=S[C]=S[E]=S[R]=S[T]=S[O]=!0,S[a]=S[s]=S[b]=S[u]=S[c]=S[l]=S[p]=S[f]=S[h]=S[d]=S[v]=S[m]=S[g]=S[y]=!1;var N=Object.prototype,j=N.toString;e.exports=r},function(e,t,n){function r(e){return o(e,i(e))}var o=n(47),i=n(38);e.exports=r},function(e,t,n){function r(e){return a(function(t,n){var r=-1,a=null==t?0:n.length,s=a>2?n[a-2]:void 0,u=a>2?n[2]:void 0,c=a>1?n[a-1]:void 0;for("function"==typeof s?(s=o(s,c,5),a-=2):(s="function"==typeof c?c:void 0,a-=s?1:0),u&&i(n[0],n[1],u)&&(s=3>a?void 0:s,a=1);++r<a;){var l=n[r];l&&e(t,l,s)}return t})}var o=n(41),i=n(52),a=n(61);e.exports=r},function(e){function t(e,t){if("function"!=typeof e)throw new TypeError(n);return t=r(void 0===t?e.length-1:+t||0,0),function(){for(var n=arguments,o=-1,i=r(n.length-t,0),a=Array(i);++o<i;)a[o]=n[t+o];switch(t){case 0:return e.call(this,a);case 1:return e.call(this,n[0],a);case 2:return e.call(this,n[0],n[1],a)}var s=Array(t+1);for(o=-1;++o<t;)s[o]=n[o];return s[t]=a,e.apply(this,s)}}var n="Expected a function",r=Math.max;e.exports=t},function(e,t,n){"use strict";function r(){}e.exports=r;var o=n(6),i=n(63).EventEmitter;o(r,i),r.prototype.stop=function(){this._stopped=!0,this._clean()},r.prototype._end=function(){this.emit("end"),this._clean()},r.prototype._error=function(e){this.emit("error",e),this._clean()},r.prototype._result=function(e){this.emit("result",e)},r.prototype._clean=function(){this.removeAllListeners("stop"),this.removeAllListeners("end"),this.removeAllListeners("error"),this.removeAllListeners("result")}},function(e){function t(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function n(e){return"function"==typeof e}function r(e){return"number"==typeof e}function o(e){return"object"==typeof e&&null!==e}function i(e){return void 0===e}e.exports=t,t.EventEmitter=t,t.prototype._events=void 0,t.prototype._maxListeners=void 0,t.defaultMaxListeners=10,t.prototype.setMaxListeners=function(e){if(!r(e)||0>e||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},t.prototype.emit=function(e){var t,r,a,s,u,c;if(this._events||(this._events={}),"error"===e&&(!this._events.error||o(this._events.error)&&!this._events.error.length)){if(t=arguments[1],t instanceof Error)throw t;throw TypeError('Uncaught, unspecified "error" event.')}if(r=this._events[e],i(r))return!1;if(n(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:s=Array.prototype.slice.call(arguments,1),r.apply(this,s)}else if(o(r))for(s=Array.prototype.slice.call(arguments,1),c=r.slice(),a=c.length,u=0;a>u;u++)c[u].apply(this,s);return!0},t.prototype.addListener=function(e,r){var a;if(!n(r))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",e,n(r.listener)?r.listener:r),this._events[e]?o(this._events[e])?this._events[e].push(r):this._events[e]=[this._events[e],r]:this._events[e]=r,o(this._events[e])&&!this._events[e].warned&&(a=i(this._maxListeners)?t.defaultMaxListeners:this._maxListeners,a&&a>0&&this._events[e].length>a&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace())),this},t.prototype.on=t.prototype.addListener,t.prototype.once=function(e,t){function r(){this.removeListener(e,r),o||(o=!0,t.apply(this,arguments))}if(!n(t))throw TypeError("listener must be a function");var o=!1;return r.listener=t,this.on(e,r),this},t.prototype.removeListener=function(e,t){var r,i,a,s;if(!n(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(r=this._events[e],a=r.length,i=-1,r===t||n(r.listener)&&r.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(o(r)){for(s=a;s-->0;)if(r[s]===t||r[s].listener&&r[s].listener===t){i=s;break}if(0>i)return this;1===r.length?(r.length=0,delete this._events[e]):r.splice(i,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},t.prototype.removeAllListeners=function(e){var t,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(r=this._events[e],n(r))this.removeListener(e,r);else if(r)for(;r.length;)this.removeListener(e,r[r.length-1]);return delete this._events[e],this},t.prototype.listeners=function(e){var t;return t=this._events&&this._events[e]?n(this._events[e])?[this._events[e]]:this._events[e].slice():[]},t.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(n(t))return 1;if(t)return t.length}return 0},t.listenerCount=function(e,t){return e.listenerCount(t)}},function(e,t,n){"use strict";function r(e,t){return e+=/\?/.test(e)?"&":"?",e+o.encode(t)}e.exports=r;var o=n(65)},function(e,t,n){"use strict";t.decode=t.parse=n(66),t.encode=t.stringify=n(67)},function(e){"use strict";function t(e,t){return Object.prototype.hasOwnProperty.call(e,t)}e.exports=function(e,r,o,i){r=r||"&",o=o||"=";var a={};if("string"!=typeof e||0===e.length)return a;var s=/\+/g;e=e.split(r);var u=1e3;i&&"number"==typeof i.maxKeys&&(u=i.maxKeys);var c=e.length;u>0&&c>u&&(c=u);for(var l=0;c>l;++l){var p,f,h,d,v=e[l].replace(s,"%20"),m=v.indexOf(o);m>=0?(p=v.substr(0,m),f=v.substr(m+1)):(p=v,f=""),h=decodeURIComponent(p),d=decodeURIComponent(f),t(a,h)?n(a[h])?a[h].push(d):a[h]=[a[h],d]:a[h]=d}return a};var n=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},function(e){"use strict";function t(e,t){if(e.map)return e.map(t);for(var n=[],r=0;r<e.length;r++)n.push(t(e[r],r));return n}var n=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};e.exports=function(e,i,a,s){return i=i||"&",a=a||"=",null===e&&(e=void 0),"object"==typeof e?t(o(e),function(o){var s=encodeURIComponent(n(o))+a;return r(e[o])?t(e[o],function(e){return s+encodeURIComponent(n(e))}).join(i):s+encodeURIComponent(n(e[o]))}).join(i):s?encodeURIComponent(n(s))+a+encodeURIComponent(n(e)):""};var r=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},o=Object.keys||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t}},function(e,t,n){"use strict";function r(e,t,n){function r(){t.debug("JSONP: success"),v||p||(v=!0,l||(t.debug("JSONP: Fail. Script loaded but did not call the callback"),s(),n(new o.JSONPScriptFail)))}function a(){("loaded"===this.readyState||"complete"===this.readyState)&&r()}function s(){clearTimeout(m),h.onload=null,h.onreadystatechange=null,h.onerror=null,f.removeChild(h);try{delete window[d],delete window[d+"_loaded"]}catch(e){window[d]=null,window[d+"_loaded"]=null}}function u(){t.debug("JSONP: Script timeout"),p=!0,s(),n(new o.RequestTimeout)}function c(){t.debug("JSONP: Script error"),v||p||(s(),n(new o.JSONPScriptError))}if("GET"!==t.method)return void n(new Error("Method "+t.method+" "+e+" is not supported by JSONP."));t.debug("JSONP: start");var l=!1,p=!1;i+=1;var f=document.getElementsByTagName("head")[0],h=document.createElement("script"),d="algoliaJSONP_"+i,v=!1;window[d]=function(e){try{delete window[d]}catch(t){window[d]=void 0}p||(l=!0,s(),n(null,{body:e}))},e+="&callback="+d,t.jsonBody&&t.jsonBody.params&&(e+="&"+t.jsonBody.params);var m=setTimeout(u,t.timeout);h.onreadystatechange=a,h.onload=r,h.onerror=c,h.async=!0,h.defer=!0,h.src=e,f.appendChild(h)}e.exports=r;var o=n(16),i=0},function(e,t,n){function r(e,t,n){return"function"==typeof t?o(e,!0,i(t,n,3)):o(e,!0)}var o=n(44),i=n(41);e.exports=r},function(e){"use strict";function t(){var e=window.document.location.protocol;return"http:"!==e&&"https:"!==e&&(e="http:"),e}e.exports=t},function(e){"use strict";e.exports="3.9.0"},function(e,t,n){"use strict";function r(e,t,n){return new o(e,t,n)}var o=n(73),i=n(74),a=n(141);r.version=n(210),r.AlgoliaSearchHelper=o,r.SearchParameters=i,r.SearchResults=a,r.url=n(200),e.exports=r},function(e,t,n){"use strict";function r(e,t,n){this.client=e;var r=n||{};r.index=t,this.state=o.make(r),this.lastResults=null,this._queryId=0,this._lastQueryIdReceived=-1}var o=n(74),i=n(141),a=n(195),s=n(196),u=n(63),c=n(17),l=n(108),p=n(199),f=n(124),h=n(188),d=n(200);s.inherits(r,u.EventEmitter),r.prototype.search=function(){return this._search(),this},r.prototype.searchOnce=function(e,t){var n=this.state.setQueryParameters(e),r=a._getQueries(n.index,n);return t?this.client.search(r,function(e,r){t(e,new i(n,r),n)}):this.client.search(r).then(function(e){return{content:new i(n,e),state:n}})},r.prototype.setQuery=function(e){return this.state=this.state.setQuery(e),this._change(),this},r.prototype.clearRefinements=function(e){return this.state=this.state.clearRefinements(e),this._change(),this},r.prototype.clearTags=function(){return this.state=this.state.clearTags(),this._change(),this},r.prototype.addDisjunctiveFacetRefinement=function(e,t){return this.state=this.state.addDisjunctiveFacetRefinement(e,t),this._change(),this},r.prototype.addDisjunctiveRefine=function(){return this.addDisjunctiveFacetRefinement.apply(this,arguments)},r.prototype.addNumericRefinement=function(e,t,n){return this.state=this.state.addNumericRefinement(e,t,n),this._change(),this},r.prototype.addFacetRefinement=function(e,t){return this.state=this.state.addFacetRefinement(e,t),this._change(),this},r.prototype.addRefine=function(){return this.addFacetRefinement.apply(this,arguments)},r.prototype.addFacetExclusion=function(e,t){return this.state=this.state.addExcludeRefinement(e,t),this._change(),this},r.prototype.addExclude=function(){return this.addFacetExclusion.apply(this,arguments)},r.prototype.addTag=function(e){return this.state=this.state.addTagRefinement(e),this._change(),this},r.prototype.removeNumericRefinement=function(e,t,n){return this.state=this.state.removeNumericRefinement(e,t,n),this._change(),this},r.prototype.removeDisjunctiveFacetRefinement=function(e,t){return this.state=this.state.removeDisjunctiveFacetRefinement(e,t),this._change(),this},r.prototype.removeDisjunctiveRefine=function(){return this.removeDisjunctiveFacetRefinement.apply(this,arguments)},r.prototype.removeFacetRefinement=function(e,t){return this.state=this.state.removeFacetRefinement(e,t),this._change(),this},r.prototype.removeRefine=function(){return this.removeFacetRefinement.apply(this,arguments)},r.prototype.removeFacetExclusion=function(e,t){return this.state=this.state.removeExcludeRefinement(e,t),this._change(),this},r.prototype.removeExclude=function(){return this.removeFacetExclusion.apply(this,arguments)},r.prototype.removeTag=function(e){return this.state=this.state.removeTagRefinement(e),this._change(),this},r.prototype.toggleFacetExclusion=function(e,t){return this.state=this.state.toggleExcludeFacetRefinement(e,t),this._change(),this},r.prototype.toggleExclude=function(){return this.toggleFacetExclusion.apply(this,arguments)},r.prototype.toggleRefinement=function(e,t){return this.state=this.state.toggleRefinement(e,t),this._change(),this},r.prototype.toggleRefine=function(){return this.toggleRefinement.apply(this,arguments)},r.prototype.toggleTag=function(e){return this.state=this.state.toggleTagRefinement(e),this._change(),this},r.prototype.nextPage=function(){return this.setCurrentPage(this.state.page+1)},r.prototype.previousPage=function(){return this.setCurrentPage(this.state.page-1)},r.prototype.setCurrentPage=function(e){if(0>e)throw new Error("Page requested below 0.");return this.state=this.state.setPage(e),this._change(),this},r.prototype.setIndex=function(e){return this.state=this.state.setIndex(e),this._change(),this},r.prototype.setQueryParameter=function(e,t){var n=this.state.setQueryParameter(e,t);return this.state===n?this:(this.state=n,this._change(),this)},r.prototype.setState=function(e){return this.state=new o(e),this._change(),this},r.prototype.getState=function(e){return void 0===e?this.state:this.state.filter(e)},r.prototype.getStateAsQueryString=function(e){var t=e&&e.filters||["query","attribute:*"],n=this.getState(t);return d.getQueryStringFromState(n,e)},r.getConfigurationFromQueryString=d.getStateFromQueryString,r.getForeignConfigurationInQueryString=d.getUnrecognizedParametersInQueryString,r.prototype.setStateFromQueryString=function(e,t){var n=t&&t.triggerChange||!1,r=d.getStateFromQueryString(e,t),o=this.state.setQueryParameters(r);n?this.setState(o):this.overrideStateWithoutTriggeringChangeEvent(o)},r.prototype.overrideStateWithoutTriggeringChangeEvent=function(e){return this.state=new o(e),this},r.prototype.isRefined=function(e,t){if(this.state.isConjunctiveFacet(e))return this.state.isFacetRefined(e,t);if(this.state.isDisjunctiveFacet(e))return this.state.isDisjunctiveFacetRefined(e,t);throw new Error(e+" is not properly defined in this helper configuration(use the facets or disjunctiveFacets keys to configure it)")},r.prototype.hasRefinements=function(e){return f(this.state.getNumericRefinements(e))?this.state.isConjunctiveFacet(e)?this.state.isFacetRefined(e):this.state.isDisjunctiveFacet(e)?this.state.isDisjunctiveFacetRefined(e):this.state.isHierarchicalFacet(e)?this.state.isHierarchicalFacetRefined(e):!1:!0},r.prototype.isExcluded=function(e,t){return this.state.isExcludeRefined(e,t)},r.prototype.isDisjunctiveRefined=function(e,t){return this.state.isDisjunctiveFacetRefined(e,t)},r.prototype.hasTag=function(e){return this.state.isTagRefined(e)},r.prototype.isTagRefined=function(){return this.hasTagRefinements.apply(this,arguments)},r.prototype.getIndex=function(){return this.state.index},r.prototype.getCurrentPage=function(){return this.state.page},r.prototype.getTags=function(){return this.state.tagRefinements},r.prototype.getQueryParameter=function(e){return this.state.getQueryParameter(e)},r.prototype.getRefinements=function(e){var t=[];if(this.state.isConjunctiveFacet(e)){var n=this.state.getConjunctiveRefinements(e);c(n,function(e){t.push({value:e,type:"conjunctive"})});var r=this.state.getExcludeRefinements(e);c(r,function(e){t.push({value:e,type:"exclude"})})}else if(this.state.isDisjunctiveFacet(e)){var o=this.state.getDisjunctiveRefinements(e);c(o,function(e){t.push({value:e,type:"disjunctive"})})}var i=this.state.getNumericRefinements(e);return c(i,function(e,n){t.push({value:e,operator:n,type:"numeric"})}),t},r.prototype.getHierarchicalFacetBreadcrumb=function(e){return l(this.state.getHierarchicalRefinement(e)[0].split(this.state._getHierarchicalFacetSeparator(this.state.getHierarchicalFacetByName(e))),function(e){return h(e)})},r.prototype._search=function(){var e=this.state,t=a._getQueries(e.index,e);this.emit("search",e,this.lastResults),this.client.search(t,p(this._handleResponse,this,e,this._queryId++))},r.prototype._handleResponse=function(e,t,n,r){if(!(t<this._lastQueryIdReceived)){if(this._lastQueryIdReceived=t,n)return void this.emit("error",n);var o=this.lastResults=new i(e,r);this.emit("result",o,e)}},r.prototype.containsRefinement=function(e,t,n,r){return e||0!==t.length||0!==n.length||0!==r.length},r.prototype._hasDisjunctiveRefinements=function(e){return this.state.disjunctiveRefinements[e]&&this.state.disjunctiveRefinements[e].length>0},r.prototype._change=function(){this.emit("change",this.state,this.lastResults)},e.exports=r},function(e,t,n){"use strict";function r(e){var t=e?r._parseNumbers(e):{};this.index=t.index||"",this.query=t.query||"",this.facets=t.facets||[],this.disjunctiveFacets=t.disjunctiveFacets||[],this.hierarchicalFacets=t.hierarchicalFacets||[],this.facetsRefinements=t.facetsRefinements||{},this.facetsExcludes=t.facetsExcludes||{},this.disjunctiveFacetsRefinements=t.disjunctiveFacetsRefinements||{},this.numericRefinements=t.numericRefinements||{},this.tagRefinements=t.tagRefinements||[],this.hierarchicalFacetsRefinements=t.hierarchicalFacetsRefinements||{},this.numericFilters=t.numericFilters,this.tagFilters=t.tagFilters,this.hitsPerPage=t.hitsPerPage,this.maxValuesPerFacet=t.maxValuesPerFacet,this.page=t.page||0,this.queryType=t.queryType,this.typoTolerance=t.typoTolerance,this.minWordSizefor1Typo=t.minWordSizefor1Typo,this.minWordSizefor2Typos=t.minWordSizefor2Typos,this.allowTyposOnNumericTokens=t.allowTyposOnNumericTokens,this.ignorePlurals=t.ignorePlurals,this.restrictSearchableAttributes=t.restrictSearchableAttributes,this.advancedSyntax=t.advancedSyntax,this.analytics=t.analytics,this.analyticsTags=t.analyticsTags,this.synonyms=t.synonyms,this.replaceSynonymsInHighlight=t.replaceSynonymsInHighlight,this.optionalWords=t.optionalWords,this.removeWordsIfNoResults=t.removeWordsIfNoResults,this.attributesToRetrieve=t.attributesToRetrieve,this.attributesToHighlight=t.attributesToHighlight,this.highlightPreTag=t.highlightPreTag,this.highlightPostTag=t.highlightPostTag,this.attributesToSnippet=t.attributesToSnippet,this.getRankingInfo=t.getRankingInfo,this.distinct=t.distinct,this.aroundLatLng=t.aroundLatLng,this.aroundLatLngViaIP=t.aroundLatLngViaIP,this.aroundRadius=t.aroundRadius,this.minimumAroundRadius=t.minimumAroundRadius,this.aroundPrecision=t.aroundPrecision,this.insideBoundingBox=t.insideBoundingBox,this.insidePolygon=t.insidePolygon,this.offset=t.offset,this.length=t.length,a(t,function(e,t){this.hasOwnProperty(t)||window.console&&window.console.error("Unsupported SearchParameter: `"+t+"` (this will throw in the next version)")},this)}var o=n(25),i=n(75),a=n(82),s=n(17),u=n(84),c=n(108),l=n(111),p=n(115),f=n(121),h=n(36),d=n(124),v=n(126),m=n(125),g=n(127),y=n(28),b=n(128),w=n(132),x=n(133),_=n(53),P=n(138),C=n(139),E=n(140); r.PARAMETERS=o(new r),r._parseNumbers=function(e){var t={},n=["aroundPrecision","aroundRadius","getRankingInfo","minWordSizefor2Typos","minWordSizefor1Typo","page","maxValuesPerFacet"];if(s(n,function(n){var r=e[n];m(r)&&(t[n]=parseFloat(e[n]))}),e.numericRefinements){var r={};s(e.numericRefinements,function(e,t){r[t]={},s(e,function(e,n){var o=c(e,function(e){return h(e)?c(e,function(e){return m(e)?parseFloat(e):e}):m(e)?parseFloat(e):e});r[t][n]=o})}),t.numericRefinements=r}return _({},e,t)},r.make=function(e){var t=new r(e);return P(t)},r.validate=function(e,t){var n=t||{},r=o(n),i=u(r,function(t){return!e.hasOwnProperty(t)});return 1===i.length?new Error("Property "+i[0]+" is not defined on SearchParameters (see http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)"):i.length>1?new Error("Properties "+i.join(" ")+" are not defined on SearchParameters (see http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)"):e.tagFilters&&n.tagRefinements&&n.tagRefinements.length>0?new Error("[Tags] Cannot switch from the managed tag API to the advanced API. It is probably an error, if it is really what you want, you should first clear the tags with clearTags method."):e.tagRefinements.length>0&&n.tagFilters?new Error("[Tags] Cannot switch from the advanced tag API to the managed API. It is probably an error, if it is not, you should first clear the tags with clearTags method."):e.numericFilters&&n.numericRefinements&&!d(n.numericRefinements)?new Error("[Numeric filters] Can't switch from the advanced to the managed API. It is probably an error, if this is really what you want, you have to first clear the numeric filters."):!d(e.numericRefinements)&&n.numericFilters?new Error("[Numeric filters] Can't switch from the managed API to the advanced. It is probably an error, if this is really what you want, you have to first clear the numeric filters."):null},r.prototype={constructor:r,clearRefinements:function(e){var t=E.clearRefinement;return this.setQueryParameters({page:0,numericRefinements:this._clearNumericRefinements(e),facetsRefinements:t(this.facetsRefinements,e,"conjunctiveFacet"),facetsExcludes:t(this.facetsExcludes,e,"exclude"),disjunctiveFacetsRefinements:t(this.disjunctiveFacetsRefinements,e,"disjunctiveFacet"),hierarchicalFacetsRefinements:t(this.hierarchicalFacetsRefinements,e,"hierarchicalFacet")})},clearTags:function(){return void 0===this.tagFilters&&0===this.tagRefinements.length?this:this.setQueryParameters({page:0,tagFilters:void 0,tagRefinements:[]})},setIndex:function(e){return e===this.index?this:this.setQueryParameters({index:e,page:0})},setQuery:function(e){return e===this.query?this:this.setQueryParameters({query:e,page:0})},setPage:function(e){return e===this.page?this:this.setQueryParameters({page:e})},setFacets:function(e){return this.setQueryParameters({facets:e})},setDisjunctiveFacets:function(e){return this.setQueryParameters({disjunctiveFacets:e})},setHitsPerPage:function(e){return this.hitsPerPage===e?this:this.setQueryParameters({hitsPerPage:e,page:0})},setTypoTolerance:function(e){return this.typoTolerance===e?this:this.setQueryParameters({typoTolerance:e,page:0})},addNumericRefinement:function(e,t,n){var r;if(g(n))r=n;else if(m(n))r=parseFloat(n);else{if(!h(n))throw new Error("The value should be a number, a parseable string or an array of those.");r=c(n,function(e){return m(e)?parseFloat(e):e})}if(this.isNumericRefined(e,t,r))return this;var o=_({},this.numericRefinements);return o[e]=_({},o[e]),o[e][t]?(o[e][t]=o[e][t].slice(),o[e][t].push(r)):o[e][t]=[r],this.setQueryParameters({page:0,numericRefinements:o})},getConjunctiveRefinements:function(e){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return this.facetsRefinements[e]||[]},getDisjunctiveRefinements:function(e){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return this.disjunctiveFacetsRefinements[e]||[]},getHierarchicalRefinement:function(e){return this.hierarchicalFacetsRefinements[e]||[]},getExcludeRefinements:function(e){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return this.facetsExcludes[e]||[]},removeNumericRefinement:function(e,t,n){return void 0!==n?this.isNumericRefined(e,t,n)?this.setQueryParameters({page:0,numericRefinements:this._clearNumericRefinements(function(r,o){return o===e&&r.op===t&&r.val===n})}):this:void 0!==t?this.isNumericRefined(e,t)?this.setQueryParameters({page:0,numericRefinements:this._clearNumericRefinements(function(n,r){return r===e&&n.op===t})}):this:this.isNumericRefined(e)?this.setQueryParameters({page:0,numericRefinements:this._clearNumericRefinements(function(t,n){return n===e})}):this},getNumericRefinements:function(e){return this.numericRefinements[e]||{}},getNumericRefinement:function(e,t){return this.numericRefinements[e]&&this.numericRefinements[e][t]},_clearNumericRefinements:function(e){return v(e)?{}:m(e)?p(this.numericRefinements,e):y(e)?l(this.numericRefinements,function(t,n,r){var o={};return s(n,function(t,n){var i=[];s(t,function(t){var o=e({val:t,op:n},r,"numeric");o||i.push(t)}),d(i)||(o[n]=i)}),d(o)||(t[r]=o),t},{}):void 0},addFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return E.isRefined(this.facetsRefinements,e,t)?this:this.setQueryParameters({page:0,facetsRefinements:E.addRefinement(this.facetsRefinements,e,t)})},addExcludeRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return E.isRefined(this.facetsExcludes,e,t)?this:this.setQueryParameters({page:0,facetsExcludes:E.addRefinement(this.facetsExcludes,e,t)})},addDisjunctiveFacetRefinement:function(e,t){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return E.isRefined(this.disjunctiveFacetsRefinements,e,t)?this:this.setQueryParameters({page:0,disjunctiveFacetsRefinements:E.addRefinement(this.disjunctiveFacetsRefinements,e,t)})},addTagRefinement:function(e){if(this.isTagRefined(e))return this;var t={page:0,tagRefinements:this.tagRefinements.concat(e)};return this.setQueryParameters(t)},removeFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return E.isRefined(this.facetsRefinements,e,t)?this.setQueryParameters({page:0,facetsRefinements:E.removeRefinement(this.facetsRefinements,e,t)}):this},removeExcludeRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return E.isRefined(this.facetsExcludes,e,t)?this.setQueryParameters({page:0,facetsExcludes:E.removeRefinement(this.facetsExcludes,e,t)}):this},removeDisjunctiveFacetRefinement:function(e,t){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return E.isRefined(this.disjunctiveFacetsRefinements,e,t)?this.setQueryParameters({page:0,disjunctiveFacetsRefinements:E.removeRefinement(this.disjunctiveFacetsRefinements,e,t)}):this},removeTagRefinement:function(e){if(!this.isTagRefined(e))return this;var t={page:0,tagRefinements:u(this.tagRefinements,function(t){return t!==e})};return this.setQueryParameters(t)},toggleRefinement:function(e,t){if(this.isHierarchicalFacet(e))return this.toggleHierarchicalFacetRefinement(e,t);if(this.isConjunctiveFacet(e))return this.toggleFacetRefinement(e,t);if(this.isDisjunctiveFacet(e))return this.toggleDisjunctiveFacetRefinement(e,t);throw new Error("Cannot refine the undeclared facet "+e+"; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets")},toggleFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return this.setQueryParameters({page:0,facetsRefinements:E.toggleRefinement(this.facetsRefinements,e,t)})},toggleExcludeFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return this.setQueryParameters({page:0,facetsExcludes:E.toggleRefinement(this.facetsExcludes,e,t)})},toggleDisjunctiveFacetRefinement:function(e,t){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return this.setQueryParameters({page:0,disjunctiveFacetsRefinements:E.toggleRefinement(this.disjunctiveFacetsRefinements,e,t)})},toggleHierarchicalFacetRefinement:function(e,t){if(!this.isHierarchicalFacet(e))throw new Error(e+" is not defined in the hierarchicalFacets attribute of the helper configuration");var n=this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(e)),r={},o=void 0!==this.hierarchicalFacetsRefinements[e]&&this.hierarchicalFacetsRefinements[e].length>0&&(this.hierarchicalFacetsRefinements[e][0]===t||0===this.hierarchicalFacetsRefinements[e][0].indexOf(t+n));return r[e]=o?-1===t.indexOf(n)?[]:[t.slice(0,t.lastIndexOf(n))]:[t],this.setQueryParameters({page:0,hierarchicalFacetsRefinements:x({},r,this.hierarchicalFacetsRefinements)})},toggleTagRefinement:function(e){return this.isTagRefined(e)?this.removeTagRefinement(e):this.addTagRefinement(e)},isDisjunctiveFacet:function(e){return f(this.disjunctiveFacets,e)>-1},isHierarchicalFacet:function(e){return void 0!==this.getHierarchicalFacetByName(e)},isConjunctiveFacet:function(e){return f(this.facets,e)>-1},isFacetRefined:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return E.isRefined(this.facetsRefinements,e,t)},isExcludeRefined:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return E.isRefined(this.facetsExcludes,e,t)},isDisjunctiveFacetRefined:function(e,t){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return E.isRefined(this.disjunctiveFacetsRefinements,e,t)},isHierarchicalFacetRefined:function(e,t){if(!this.isHierarchicalFacet(e))throw new Error(e+" is not defined in the hierarchicalFacets attribute of the helper configuration");var n=this.getHierarchicalRefinement(e);return t?-1!==f(n,t):n.length>0},isNumericRefined:function(e,t,n){if(v(n)&&v(t))return!!this.numericRefinements[e];if(v(n))return this.numericRefinements[e]&&!v(this.numericRefinements[e][t]);var r=parseFloat(n);return this.numericRefinements[e]&&!v(this.numericRefinements[e][t])&&-1!==f(this.numericRefinements[e][t],r)},isTagRefined:function(e){return-1!==f(this.tagRefinements,e)},getRefinedDisjunctiveFacets:function(){var e=i(o(this.numericRefinements),this.disjunctiveFacets);return o(this.disjunctiveFacetsRefinements).concat(e).concat(this.getRefinedHierarchicalFacets())},getRefinedHierarchicalFacets:function(){return i(w(this.hierarchicalFacets,"name"),o(this.hierarchicalFacetsRefinements))},getUnrefinedDisjunctiveFacets:function(){var e=this.getRefinedDisjunctiveFacets();return u(this.disjunctiveFacets,function(t){return-1===f(e,t)})},managedParameters:["index","facets","disjunctiveFacets","facetsRefinements","facetsExcludes","disjunctiveFacetsRefinements","numericRefinements","tagRefinements","hierarchicalFacets","hierarchicalFacetsRefinements"],getQueryParams:function(){var e=this.managedParameters,t={};return a(this,function(n,r){-1===f(e,r)&&void 0!==n&&(t[r]=n)}),t},getQueryParameter:function(e){if(!this.hasOwnProperty(e))throw new Error("Parameter '"+e+"' is not an attribute of SearchParameters (http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)");return this[e]},setQueryParameter:function(e,t){if(this[e]===t)return this;var n={};return n[e]=t,this.setQueryParameters(n)},setQueryParameters:function(e){var t=r.validate(this,e);if(t)throw t;return this.mutateMe(function(t){var n=o(e);return s(n,function(n){t[n]=e[n]}),t})},filter:function(e){return C(this,e)},mutateMe:function(e){var t=new this.constructor(this);return e(t,this),P(t)},_getHierarchicalFacetSortBy:function(e){return e.sortBy||["isRefined:desc","name:asc"]},_getHierarchicalFacetSeparator:function(e){return e.separator||" > "},getHierarchicalFacetByName:function(e){return b(this.hierarchicalFacets,{name:e})}},e.exports=r},function(e,t,n){var r=n(76),o=n(78),i=n(79),a=n(30),s=n(61),u=s(function(e){for(var t=e.length,n=t,s=Array(d),u=r,c=!0,l=[];n--;){var p=e[n]=a(p=e[n])?p:[];s[n]=c&&p.length>=120?i(n&&p):null}var f=e[0],h=-1,d=f?f.length:0,v=s[0];e:for(;++h<d;)if(p=f[h],(v?o(v,p):u(l,p,0))<0){for(var n=t;--n;){var m=s[n];if((m?o(m,p):u(e[n],p,0))<0)continue e}v&&v.push(p),l.push(p)}return l});e.exports=u},function(e,t,n){function r(e,t,n){if(t!==t)return o(e,n);for(var r=n-1,i=e.length;++r<i;)if(e[r]===t)return r;return-1}var o=n(77);e.exports=r},function(e){function t(e,t,n){for(var r=e.length,o=t+(n?0:-1);n?o--:++o<r;){var i=e[o];if(i!==i)return o}return-1}e.exports=t},function(e,t,n){function r(e,t){var n=e.data,r="string"==typeof t||o(t)?n.set.has(t):n.hash[t];return r?0:-1}var o=n(24);e.exports=r},function(e,t,n){(function(t){function r(e){return s&&a?new o(e):null}var o=n(80),i=n(26),a=i(t,"Set"),s=i(Object,"create");e.exports=r}).call(t,function(){return this}())},function(e,t,n){(function(t){function r(e){var t=e?e.length:0;for(this.data={hash:s(null),set:new a};t--;)this.push(e[t])}var o=n(81),i=n(26),a=i(t,"Set"),s=i(Object,"create");r.prototype.push=o,e.exports=r}).call(t,function(){return this}())},function(e,t,n){function r(e){var t=this.data;"string"==typeof e||o(e)?t.set.add(e):t.hash[e]=!0}var o=n(24);e.exports=r},function(e,t,n){var r=n(20),o=n(83),i=o(r);e.exports=i},function(e,t,n){function r(e){return function(t,n,r){return("function"!=typeof n||void 0!==r)&&(n=o(n,r,3)),e(t,n)}}var o=n(41);e.exports=r},function(e,t,n){function r(e,t,n){var r=s(e)?o:a;return t=i(t,n,3),r(e,t)}var o=n(85),i=n(86),a=n(107),s=n(36);e.exports=r},function(e){function t(e,t){for(var n=-1,r=e.length,o=-1,i=[];++n<r;){var a=e[n];t(a,n,e)&&(i[++o]=a)}return i}e.exports=t},function(e,t,n){function r(e,t,n){var r=typeof e;return"function"==r?void 0===t?e:a(e,t,n):null==e?s:"object"==r?o(e):void 0===t?u(e):i(e,t)}var o=n(87),i=n(98),a=n(41),s=n(42),u=n(105);e.exports=r},function(e,t,n){function r(e){var t=i(e);if(1==t.length&&t[0][2]){var n=t[0][0],r=t[0][1];return function(e){return null==e?!1:e[n]===r&&(void 0!==r||n in a(e))}}return function(e){return o(e,t)}}var o=n(88),i=n(95),a=n(23);e.exports=r},function(e,t,n){function r(e,t,n){var r=t.length,a=r,s=!n;if(null==e)return!a;for(e=i(e);r--;){var u=t[r];if(s&&u[2]?u[1]!==e[u[0]]:!(u[0]in e))return!1}for(;++r<a;){u=t[r];var c=u[0],l=e[c],p=u[1];if(s&&u[2]){if(void 0===l&&!(c in e))return!1}else{var f=n?n(l,p,c):void 0;if(!(void 0===f?o(p,l,n,!0):f))return!1}}return!0}var o=n(89),i=n(23);e.exports=r},function(e,t,n){function r(e,t,n,s,u,c){return e===t?!0:null==e||null==t||!i(e)&&!a(t)?e!==e&&t!==t:o(e,t,r,n,s,u,c)}var o=n(90),i=n(24),a=n(29);e.exports=r},function(e,t,n){function r(e,t,n,r,f,v,m){var g=s(e),y=s(t),b=l,w=l;g||(b=d.call(e),b==c?b=p:b!=p&&(g=u(e))),y||(w=d.call(t),w==c?w=p:w!=p&&(y=u(t)));var x=b==p,_=w==p,P=b==w;if(P&&!g&&!x)return i(e,t,b);if(!f){var C=x&&h.call(e,"__wrapped__"),E=_&&h.call(t,"__wrapped__");if(C||E)return n(C?e.value():e,E?t.value():t,r,f,v,m)}if(!P)return!1;v||(v=[]),m||(m=[]);for(var R=v.length;R--;)if(v[R]==e)return m[R]==t;v.push(e),m.push(t);var T=(g?o:a)(e,t,n,r,f,v,m);return v.pop(),m.pop(),T}var o=n(91),i=n(93),a=n(94),s=n(36),u=n(58),c="[object Arguments]",l="[object Array]",p="[object Object]",f=Object.prototype,h=f.hasOwnProperty,d=f.toString;e.exports=r},function(e,t,n){function r(e,t,n,r,i,a,s){var u=-1,c=e.length,l=t.length;if(c!=l&&!(i&&l>c))return!1;for(;++u<c;){var p=e[u],f=t[u],h=r?r(i?f:p,i?p:f,u):void 0;if(void 0!==h){if(h)continue;return!1}if(i){if(!o(t,function(e){return p===e||n(p,e,r,i,a,s)}))return!1}else if(p!==f&&!n(p,f,r,i,a,s))return!1}return!0}var o=n(92);e.exports=r},function(e){function t(e,t){for(var n=-1,r=e.length;++n<r;)if(t(e[n],n,e))return!0;return!1}e.exports=t},function(e){function t(e,t,u){switch(u){case n:case r:return+e==+t;case o:return e.name==t.name&&e.message==t.message;case i:return e!=+e?t!=+t:e==+t;case a:case s:return e==t+""}return!1}var n="[object Boolean]",r="[object Date]",o="[object Error]",i="[object Number]",a="[object RegExp]",s="[object String]";e.exports=t},function(e,t,n){function r(e,t,n,r,i,s,u){var c=o(e),l=c.length,p=o(t),f=p.length;if(l!=f&&!i)return!1;for(var h=l;h--;){var d=c[h];if(!(i?d in t:a.call(t,d)))return!1}for(var v=i;++h<l;){d=c[h];var m=e[d],g=t[d],y=r?r(i?g:m,i?m:g,d):void 0;if(!(void 0===y?n(m,g,r,i,s,u):y))return!1;v||(v="constructor"==d)}if(!v){var b=e.constructor,w=t.constructor;if(b!=w&&"constructor"in e&&"constructor"in t&&!("function"==typeof b&&b instanceof b&&"function"==typeof w&&w instanceof w))return!1}return!0}var o=n(25),i=Object.prototype,a=i.hasOwnProperty;e.exports=r},function(e,t,n){function r(e){for(var t=i(e),n=t.length;n--;)t[n][2]=o(t[n][1]);return t}var o=n(96),i=n(97);e.exports=r},function(e,t,n){function r(e){return e===e&&!o(e)}var o=n(24);e.exports=r},function(e,t,n){function r(e){e=i(e);for(var t=-1,n=o(e),r=n.length,a=Array(r);++t<r;){var s=n[t];a[t]=[s,e[s]]}return a}var o=n(25),i=n(23);e.exports=r},function(e,t,n){function r(e,t){var n=s(e),r=u(e)&&c(t),h=e+"";return e=f(e),function(s){if(null==s)return!1;var u=h;if(s=p(s),!(!n&&r||u in s)){if(s=1==e.length?s:o(s,a(e,0,-1)),null==s)return!1;u=l(e),s=p(s)}return s[u]===t?void 0!==t||u in s:i(t,s[u],void 0,!0)}}var o=n(99),i=n(89),a=n(100),s=n(36),u=n(101),c=n(96),l=n(102),p=n(23),f=n(103);e.exports=r},function(e,t,n){function r(e,t,n){if(null!=e){void 0!==n&&n in o(e)&&(t=[n]);for(var r=0,i=t.length;null!=e&&i>r;)e=e[t[r++]];return r&&r==i?e:void 0}}var o=n(23);e.exports=r},function(e){function t(e,t,n){var r=-1,o=e.length;t=null==t?0:+t||0,0>t&&(t=-t>o?0:o+t),n=void 0===n||n>o?o:+n||0,0>n&&(n+=o),o=t>n?0:n-t>>>0,t>>>=0;for(var i=Array(o);++r<o;)i[r]=e[r+t];return i}e.exports=t},function(e,t,n){function r(e,t){var n=typeof e;if("string"==n&&s.test(e)||"number"==n)return!0;if(o(e))return!1;var r=!a.test(e);return r||null!=t&&e in i(t)}var o=n(36),i=n(23),a=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/,s=/^\w*$/;e.exports=r},function(e){function t(e){var t=e?e.length:0;return t?e[t-1]:void 0}e.exports=t},function(e,t,n){function r(e){if(i(e))return e;var t=[];return o(e).replace(a,function(e,n,r,o){t.push(r?o.replace(s,"$1"):n||e)}),t}var o=n(104),i=n(36),a=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g,s=/\\(\\)?/g;e.exports=r},function(e){function t(e){return null==e?"":e+""}e.exports=t},function(e,t,n){function r(e){return a(e)?o(e):i(e)}var o=n(32),i=n(106),a=n(101);e.exports=r},function(e,t,n){function r(e){var t=e+"";return e=i(e),function(n){return o(n,e,t)}}var o=n(99),i=n(103);e.exports=r},function(e,t,n){function r(e,t){var n=[];return o(e,function(e,r,o){t(e,r,o)&&n.push(e)}),n}var o=n(19);e.exports=r},function(e,t,n){function r(e,t,n){var r=s(e)?o:a;return t=i(t,n,3),r(e,t)}var o=n(109),i=n(86),a=n(110),s=n(36);e.exports=r},function(e){function t(e,t){for(var n=-1,r=e.length,o=Array(r);++n<r;)o[n]=t(e[n],n,e);return o}e.exports=t},function(e,t,n){function r(e,t){var n=-1,r=i(e)?Array(e.length):[];return o(e,function(e,o,i){r[++n]=t(e,o,i)}),r}var o=n(19),i=n(30);e.exports=r},function(e,t,n){var r=n(112),o=n(19),i=n(113),a=i(r,o);e.exports=a},function(e){function t(e,t,n,r){var o=-1,i=e.length;for(r&&i&&(n=e[++o]);++o<i;)n=t(n,e[o],o,e);return n}e.exports=t},function(e,t,n){function r(e,t){return function(n,r,s,u){var c=arguments.length<3;return"function"==typeof r&&void 0===u&&a(n)?e(n,r,s,c):i(n,o(r,u,4),s,c,t)}}var o=n(86),i=n(114),a=n(36);e.exports=r},function(e){function t(e,t,n,r,o){return o(e,function(e,o,i){n=r?(r=!1,e):t(n,e,o,i)}),n}e.exports=t},function(e,t,n){var r=n(109),o=n(116),i=n(117),a=n(41),s=n(38),u=n(119),c=n(120),l=n(61),p=l(function(e,t){if(null==e)return{};if("function"!=typeof t[0]){var t=r(i(t),String);return u(e,o(s(e),t))}var n=a(t[0],t[1],3);return c(e,function(e,t,r){return!n(e,t,r)})});e.exports=p},function(e,t,n){function r(e,t){var n=e?e.length:0,r=[];if(!n)return r;var u=-1,c=o,l=!0,p=l&&t.length>=s?a(t):null,f=t.length;p&&(c=i,l=!1,t=p);e:for(;++u<n;){var h=e[u];if(l&&h===h){for(var d=f;d--;)if(t[d]===h)continue e;r.push(h)}else c(t,h,0)<0&&r.push(h)}return r}var o=n(76),i=n(78),a=n(79),s=200;e.exports=r},function(e,t,n){function r(e,t,n,c){c||(c=[]);for(var l=-1,p=e.length;++l<p;){var f=e[l];u(f)&&s(f)&&(n||a(f)||i(f))?t?r(f,t,n,c):o(c,f):n||(c[c.length]=f)}return c}var o=n(118),i=n(35),a=n(36),s=n(30),u=n(29);e.exports=r},function(e){function t(e,t){for(var n=-1,r=t.length,o=e.length;++n<r;)e[o+n]=t[n];return e}e.exports=t},function(e,t,n){function r(e,t){e=o(e);for(var n=-1,r=t.length,i={};++n<r;){var a=t[n];a in e&&(i[a]=e[a])}return i}var o=n(23);e.exports=r},function(e,t,n){function r(e,t){var n={};return o(e,function(e,r,o){t(e,r,o)&&(n[r]=e)}),n}var o=n(57);e.exports=r},function(e,t,n){function r(e,t,n){var r=e?e.length:0;if(!r)return-1;if("number"==typeof n)n=0>n?a(r+n,0):n;else if(n){var s=i(e,t);return r>s&&(t===t?t===e[s]:e[s]!==e[s])?s:-1}return o(e,t,n||0)}var o=n(76),i=n(122),a=Math.max;e.exports=r},function(e,t,n){function r(e,t,n){var r=0,a=e?e.length:r;if("number"==typeof t&&t===t&&s>=a){for(;a>r;){var u=r+a>>>1,c=e[u];(n?t>=c:t>c)&&null!==c?r=u+1:a=u}return a}return o(e,t,i,n)}var o=n(123),i=n(42),a=4294967295,s=a>>>1;e.exports=r},function(e){function t(e,t,o,a){t=o(t);for(var s=0,u=e?e.length:0,c=t!==t,l=null===t,p=void 0===t;u>s;){var f=n((s+u)/2),h=o(e[f]),d=void 0!==h,v=h===h;if(c)var m=v||a;else m=l?v&&d&&(a||null!=h):p?v&&(a||d):null==h?!1:a?t>=h:t>h;m?s=f+1:u=f}return r(u,i)}var n=Math.floor,r=Math.min,o=4294967295,i=o-1;e.exports=t},function(e,t,n){function r(e){return null==e?!0:a(e)&&(i(e)||c(e)||o(e)||u(e)&&s(e.splice))?!e.length:!l(e).length}var o=n(35),i=n(36),a=n(30),s=n(28),u=n(29),c=n(125),l=n(25);e.exports=r},function(e,t,n){function r(e){return"string"==typeof e||o(e)&&s.call(e)==i}var o=n(29),i="[object String]",a=Object.prototype,s=a.toString;e.exports=r},function(e){function t(e){return void 0===e}e.exports=t},function(e,t,n){function r(e){return"number"==typeof e||o(e)&&s.call(e)==i}var o=n(29),i="[object Number]",a=Object.prototype,s=a.toString;e.exports=r},function(e,t,n){var r=n(19),o=n(129),i=o(r);e.exports=i},function(e,t,n){function r(e,t){return function(n,r,u){if(r=o(r,u,3),s(n)){var c=a(n,r,t);return c>-1?n[c]:void 0}return i(n,r,e)}}var o=n(86),i=n(130),a=n(131),s=n(36);e.exports=r},function(e){function t(e,t,n,r){var o;return n(e,function(e,n,i){return t(e,n,i)?(o=r?n:e,!1):void 0}),o}e.exports=t},function(e){function t(e,t,n){for(var r=e.length,o=n?r:-1;n?o--:++o<r;)if(t(e[o],o,e))return o;return-1}e.exports=t},function(e,t,n){function r(e,t){return o(e,i(t))}var o=n(108),i=n(105);e.exports=r},function(e,t,n){var r=n(134),o=n(136),i=n(137),a=i(r,o);e.exports=a},function(e,t,n){var r=n(135),o=n(46),i=n(60),a=i(function(e,t,n){return n?r(e,t,n):o(e,t)});e.exports=a},function(e,t,n){function r(e,t,n){for(var r=-1,i=o(t),a=i.length;++r<a;){var s=i[r],u=e[s],c=n(u,t[s],s,e,t);(c===c?c===u:u!==u)&&(void 0!==u||s in e)||(e[s]=c)}return e}var o=n(25);e.exports=r},function(e){function t(e,t){return void 0===e?t:e}e.exports=t},function(e,t,n){function r(e,t){return o(function(n){var r=n[0];return null==r?r:(n.push(t),e.apply(void 0,n))})}var o=n(61);e.exports=r},function(e,t,n){"use strict";var r=n(17),o=n(42),i=n(24),a=function(e){return i(e)?(r(e,a),Object.isFrozen(e)||Object.freeze(e),e):e};e.exports=Object.freeze?a:o},function(e,t,n){"use strict";function r(e,t){var n={},r=i(t,function(e){return-1!==e.indexOf("attribute:")}),c=a(r,function(e){return e.split(":")[1]});-1===u(c,"*")?o(c,function(t){e.isConjunctiveFacet(t)&&e.isFacetRefined(t)&&(n.facetsRefinements||(n.facetsRefinements={}),n.facetsRefinements[t]=e.facetsRefinements[t]),e.isDisjunctiveFacet(t)&&e.isDisjunctiveFacetRefined(t)&&(n.disjunctiveFacetsRefinements||(n.disjunctiveFacetsRefinements={}),n.disjunctiveFacetsRefinements[t]=e.disjunctiveFacetsRefinements[t]);var r=e.getNumericRefinements(t);s(r)||(n.numericRefinements||(n.numericRefinements={}),n.numericRefinements[t]=e.numericRefinements[t])}):(s(e.numericRefinements)||(n.numericRefinements=e.numericRefinements),s(e.facetsRefinements)||(n.facetsRefinements=e.facetsRefinements),s(e.disjunctiveFacetsRefinements)||(n.disjunctiveFacetsRefinements=e.disjunctiveFacetsRefinements),s(e.hierarchicalFacetsRefinements)||(n.hierarchicalFacetsRefinements=e.hierarchicalFacetsRefinements));var l=i(t,function(e){return-1===e.indexOf("attribute:")});return o(l,function(t){n[t]=e[t]}),n}var o=n(17),i=n(84),a=n(108),s=n(124),u=n(121);e.exports=r},function(e,t,n){"use strict";var r=n(126),o=n(125),i=n(28),a=n(124),s=n(133),u=n(111),c=n(84),l=n(115),p={addRefinement:function(e,t,n){if(p.isRefined(e,t,n))return e;var r=""+n,o=e[t]?e[t].concat(r):[r],i={};return i[t]=o,s({},i,e)},removeRefinement:function(e,t,n){if(r(n))return p.clearRefinement(e,t);var o=""+n;return p.clearRefinement(e,function(e,n){return t===n&&o===e})},toggleRefinement:function(e,t,n){if(r(n))throw new Error("toggleRefinement should be used with a value");return p.isRefined(e,t,n)?p.removeRefinement(e,t,n):p.addRefinement(e,t,n)},clearRefinement:function(e,t,n){return r(t)?{}:o(t)?l(e,t):i(t)?u(e,function(e,r,o){var i=c(r,function(e){return!t(e,o,n)});return a(i)||(e[o]=i),e},{}):void 0},isRefined:function(e,t,o){var i=n(121),a=!!e[t]&&e[t].length>0;if(r(o)||!a)return a;var s=""+o;return-1!==i(e[t],s)}};e.exports=p},function(e,t,n){"use strict";function r(e){var t={};return p(e,function(e,n){t[e]=n}),t}function o(e,t,n){t&&t[n]&&(e.stats=t[n])}function i(e,t){return m(e,function(e){return g(e.attributes,t)})}function a(e,t){var n=t.results[0];this.query=n.query,this.hits=n.hits,this.index=n.index,this.hitsPerPage=n.hitsPerPage,this.nbHits=n.nbHits,this.nbPages=n.nbPages,this.page=n.page,this.processingTimeMS=v(t.results,"processingTimeMS"),this.disjunctiveFacets=[],this.hierarchicalFacets=y(e.hierarchicalFacets,function(){return[]}),this.facets=[];var a=e.getRefinedDisjunctiveFacets(),s=r(e.facets),u=r(e.disjunctiveFacets),c=1;p(n.facets,function(t,r){var a=i(e.hierarchicalFacets,r);if(a)this.hierarchicalFacets[d(e.hierarchicalFacets,{name:a.name})].push({attribute:r,data:t,exhaustive:n.exhaustiveFacetsCount});else{var c,l=-1!==h(e.disjunctiveFacets,r),p=-1!==h(e.facets,r);l&&(c=u[r],this.disjunctiveFacets[c]={name:r,data:t,exhaustive:n.exhaustiveFacetsCount},o(this.disjunctiveFacets[c],n.facets_stats,r)),p&&(c=s[r],this.facets[c]={name:r,data:t,exhaustive:n.exhaustiveFacetsCount},o(this.facets[c],n.facets_stats,r))}},this),p(a,function(r){var i=t.results[c],a=e.getHierarchicalFacetByName(r);p(i.facets,function(t,r){var s;if(a){s=d(e.hierarchicalFacets,{name:a.name});var c=d(this.hierarchicalFacets[s],{attribute:r});this.hierarchicalFacets[s][c].data=x({},this.hierarchicalFacets[s][c].data,t)}else{s=u[r];var l=n.facets&&n.facets[r]||{};this.disjunctiveFacets[s]={name:r,data:w({},t,l),exhaustive:i.exhaustiveFacetsCount},o(this.disjunctiveFacets[s],i.facets_stats,r),e.disjunctiveFacetsRefinements[r]&&p(e.disjunctiveFacetsRefinements[r],function(t){!this.disjunctiveFacets[s].data[t]&&h(e.disjunctiveFacetsRefinements[r],t)>-1&&(this.disjunctiveFacets[s].data[t]=0)},this)}},this),c++},this),p(e.getRefinedHierarchicalFacets(),function(n){var r=e.getHierarchicalFacetByName(n),o=e.getHierarchicalRefinement(n);if(!(0===o.length||o[0].split(e._getHierarchicalFacetSeparator(r)).length<2)){var i=t.results[c];p(i.facets,function(t,n){var i=d(e.hierarchicalFacets,{name:r.name}),a=d(this.hierarchicalFacets[i],{attribute:n}),s={};if(o.length>0){var u=o[0].split(e._getHierarchicalFacetSeparator(r))[0];s[u]=this.hierarchicalFacets[i][a].data[u]}this.hierarchicalFacets[i][a].data=w(s,t,this.hierarchicalFacets[i][a].data)},this),c++}},this),p(e.facetsExcludes,function(e,t){var r=s[t];this.facets[r]={name:t,data:n.facets[t],exhaustive:n.exhaustiveFacetsCount},p(e,function(e){this.facets[r]=this.facets[r]||{name:t},this.facets[r].data=this.facets[r].data||{},this.facets[r].data[e]=0},this)},this),this.hierarchicalFacets=y(this.hierarchicalFacets,T(e)),this.facets=f(this.facets),this.disjunctiveFacets=f(this.disjunctiveFacets),this._state=e}function s(e,t){var n={name:t};if(e._state.isConjunctiveFacet(t)){var r=m(e.facets,n);return r?y(r.data,function(n,r){return{name:r,count:n,isRefined:e._state.isFacetRefined(t,r)}}):[]}if(e._state.isDisjunctiveFacet(t)){var o=m(e.disjunctiveFacets,n);return o?y(o.data,function(n,r){return{name:r,count:n,isRefined:e._state.isDisjunctiveFacetRefined(t,r)}}):[]}return e._state.isHierarchicalFacet(t)?m(e.hierarchicalFacets,n):void 0}function u(e,t){if(!t.data||0===t.data.length)return t;var n=y(t.data,C(u,e)),r=e(n),o=x({},t,{data:r});return o}function c(e,t){return t.sort(e)}function l(e,t){var n=m(e,{name:t});return n&&n.stats}var p=n(17),f=n(142),h=n(121),d=n(143),v=n(145),m=n(128),g=n(152),y=n(108),b=n(153),w=n(133),x=n(53),_=n(36),P=n(28),C=n(158),E=n(185),R=n(186),T=n(187);a.prototype.getFacetByName=function(e){var t={name:e};return m(this.facets,t)||m(this.disjunctiveFacets,t)||m(this.hierarchicalFacets,t)},a.DEFAULT_SORT=["isRefined:desc","count:desc","name:asc"],a.prototype.getFacetValues=function(e,t){var n=s(this,e);if(!n)throw new Error(e+" is not a retrieved facet.");var r=w({},t,{sortBy:a.DEFAULT_SORT});if(_(r.sortBy)){var o=R(r.sortBy);return _(n)?b(n,o[0],o[1]):u(E(b,o[0],o[1]),n)}if(P(r.sortBy))return _(n)?n.sort(r.sortBy):u(C(c,r.sortBy),n);throw new Error("options.sortBy is optional but if defined it must be either an array of string (predicates) or a sorting function")},a.prototype.getFacetStats=function(e){if(this._state.isConjunctiveFacet(e))return l(this.facets,e);if(this._state.isDisjunctiveFacet(e))return l(this.disjunctiveFacets,e);throw new Error(e+" is not present in `facets` or `disjunctiveFacets`")},e.exports=a},function(e){function t(e){for(var t=-1,n=e?e.length:0,r=-1,o=[];++t<n;){var i=e[t];i&&(o[++r]=i)}return o}e.exports=t},function(e,t,n){var r=n(144),o=r();e.exports=o},function(e,t,n){function r(e){return function(t,n,r){return t&&t.length?(n=o(n,r,3),i(t,n,e)):-1}}var o=n(86),i=n(131);e.exports=r},function(e,t,n){e.exports=n(146)},function(e,t,n){function r(e,t,n){return n&&u(e,t,n)&&(t=void 0),t=i(t,n,3),1==t.length?o(s(e)?e:c(e),t):a(e,t)}var o=n(147),i=n(86),a=n(148),s=n(36),u=n(52),c=n(149);e.exports=r},function(e){function t(e,t){for(var n=e.length,r=0;n--;)r+=+t(e[n])||0;return r}e.exports=t},function(e,t,n){function r(e,t){var n=0;return o(e,function(e,r,o){n+=+t(e,r,o)||0}),n}var o=n(19);e.exports=r},function(e,t,n){function r(e){return null==e?[]:o(e)?i(e)?e:Object(e):a(e)}var o=n(30),i=n(24),a=n(150);e.exports=r},function(e,t,n){function r(e){return o(e,i(e))}var o=n(151),i=n(25);e.exports=r},function(e){function t(e,t){for(var n=-1,r=t.length,o=Array(r);++n<r;)o[n]=e[t[n]];return o}e.exports=t},function(e,t,n){function r(e,t,n,r){var f=e?i(e):0;return u(f)||(e=l(e),f=e.length),n="number"!=typeof n||r&&s(t,n,r)?0:0>n?p(f+n,0):n||0,"string"==typeof e||!a(e)&&c(e)?f>=n&&e.indexOf(t,n)>-1:!!f&&o(e,t,n)>-1}var o=n(76),i=n(31),a=n(36),s=n(52),u=n(33),c=n(125),l=n(150),p=Math.max;e.exports=r},function(e,t,n){function r(e,t,n,r){return null==e?[]:(r&&a(t,n,r)&&(n=void 0), i(t)||(t=null==t?[]:[t]),i(n)||(n=null==n?[]:[n]),o(e,t,n))}var o=n(154),i=n(36),a=n(52);e.exports=r},function(e,t,n){function r(e,t,n){var r=-1;t=o(t,function(e){return i(e)});var c=a(e,function(e){var n=o(t,function(t){return t(e)});return{criteria:n,index:++r,value:e}});return s(c,function(e,t){return u(e,t,n)})}var o=n(109),i=n(86),a=n(110),s=n(155),u=n(156);e.exports=r},function(e){function t(e,t){var n=e.length;for(e.sort(t);n--;)e[n]=e[n].value;return e}e.exports=t},function(e,t,n){function r(e,t,n){for(var r=-1,i=e.criteria,a=t.criteria,s=i.length,u=n.length;++r<s;){var c=o(i[r],a[r]);if(c){if(r>=u)return c;var l=n[r];return c*("asc"===l||l===!0?1:-1)}}return e.index-t.index}var o=n(157);e.exports=r},function(e){function t(e,t){if(e!==t){var n=null===e,r=void 0===e,o=e===e,i=null===t,a=void 0===t,s=t===t;if(e>t&&!i||!o||n&&!a&&s||r&&s)return 1;if(t>e&&!n||!s||i&&!r&&o||a&&o)return-1}return 0}e.exports=t},function(e,t,n){var r=n(159),o=32,i=r(o);i.placeholder={},e.exports=i},function(e,t,n){function r(e){var t=a(function(n,r){var a=i(r,t.placeholder);return o(n,e,void 0,r,a)});return t}var o=n(160),i=n(180),a=n(61);e.exports=r},function(e,t,n){function r(e,t,n,r,g,y,b,w){var x=t&f;if(!x&&"function"!=typeof e)throw new TypeError(v);var _=r?r.length:0;if(_||(t&=~(h|d),r=g=void 0),_-=g?g.length:0,t&d){var P=r,C=g;r=g=void 0}var E=x?void 0:u(e),R=[e,t,n,r,g,P,C,y,b,w];if(E&&(c(R,E),t=R[1],w=R[9]),R[9]=null==w?x?0:e.length:m(w-_,0)||0,t==p)var T=i(R[0],R[2]);else T=t!=h&&t!=(p|h)||R[4].length?a.apply(void 0,R):s.apply(void 0,R);var O=E?o:l;return O(T,R)}var o=n(161),i=n(163),a=n(166),s=n(183),u=n(172),c=n(184),l=n(181),p=1,f=2,h=32,d=64,v="Expected a function",m=Math.max;e.exports=r},function(e,t,n){var r=n(42),o=n(162),i=o?function(e,t){return o.set(e,t),e}:r;e.exports=i},function(e,t,n){(function(t){var r=n(26),o=r(t,"WeakMap"),i=o&&new o;e.exports=i}).call(t,function(){return this}())},function(e,t,n){(function(t){function r(e,n){function r(){var o=this&&this!==t&&this instanceof r?i:e;return o.apply(n,arguments)}var i=o(e);return r}var o=n(164);e.exports=r}).call(t,function(){return this}())},function(e,t,n){function r(e){return function(){var t=arguments;switch(t.length){case 0:return new e;case 1:return new e(t[0]);case 2:return new e(t[0],t[1]);case 3:return new e(t[0],t[1],t[2]);case 4:return new e(t[0],t[1],t[2],t[3]);case 5:return new e(t[0],t[1],t[2],t[3],t[4]);case 6:return new e(t[0],t[1],t[2],t[3],t[4],t[5]);case 7:return new e(t[0],t[1],t[2],t[3],t[4],t[5],t[6])}var n=o(e.prototype),r=e.apply(n,t);return i(r)?r:n}}var o=n(165),i=n(24);e.exports=r},function(e,t,n){var r=n(24),o=function(){function e(){}return function(t){if(r(t)){e.prototype=t;var n=new e;e.prototype=void 0}return n||{}}}();e.exports=o},function(e,t,n){(function(t){function r(e,n,x,_,P,C,E,R,T,O){function S(){for(var d=arguments.length,v=d,m=Array(d);v--;)m[v]=arguments[v];if(_&&(m=i(m,_,P)),C&&(m=a(m,C,E)),I||A){var b=S.placeholder,F=l(m,b);if(d-=F.length,O>d){var U=R?o(R):void 0,L=w(O-d,0),B=I?F:void 0,q=I?void 0:F,H=I?m:void 0,V=I?void 0:m;n|=I?g:y,n&=~(I?y:g),D||(n&=~(f|h));var W=[e,n,x,H,B,V,q,U,T,L],K=r.apply(void 0,W);return u(e)&&p(K,W),K.placeholder=b,K}}var Q=j?x:this,Y=k?Q[e]:e;return R&&(m=c(m,R)),N&&T<m.length&&(m.length=T),this&&this!==t&&this instanceof S&&(Y=M||s(e)),Y.apply(Q,m)}var N=n&b,j=n&f,k=n&h,I=n&v,D=n&d,A=n&m,M=k?void 0:s(e);return S}var o=n(45),i=n(167),a=n(168),s=n(164),u=n(169),c=n(179),l=n(180),p=n(181),f=1,h=2,d=4,v=8,m=16,g=32,y=64,b=128,w=Math.max;e.exports=r}).call(t,function(){return this}())},function(e){function t(e,t,r){for(var o=r.length,i=-1,a=n(e.length-o,0),s=-1,u=t.length,c=Array(u+a);++s<u;)c[s]=t[s];for(;++i<o;)c[r[i]]=e[i];for(;a--;)c[s++]=e[i++];return c}var n=Math.max;e.exports=t},function(e){function t(e,t,r){for(var o=-1,i=r.length,a=-1,s=n(e.length-i,0),u=-1,c=t.length,l=Array(s+c);++a<s;)l[a]=e[a];for(var p=a;++u<c;)l[p+u]=t[u];for(;++o<i;)l[p+r[o]]=e[a++];return l}var n=Math.max;e.exports=t},function(e,t,n){function r(e){var t=a(e),n=s[t];if("function"!=typeof n||!(t in o.prototype))return!1;if(e===n)return!0;var r=i(n);return!!r&&e===r[0]}var o=n(170),i=n(172),a=n(174),s=n(176);e.exports=r},function(e,t,n){function r(e){this.__wrapped__=e,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=a,this.__views__=[]}var o=n(165),i=n(171),a=Number.POSITIVE_INFINITY;r.prototype=o(i.prototype),r.prototype.constructor=r,e.exports=r},function(e){function t(){}e.exports=t},function(e,t,n){var r=n(162),o=n(173),i=r?function(e){return r.get(e)}:o;e.exports=i},function(e){function t(){}e.exports=t},function(e,t,n){function r(e){for(var t=e.name+"",n=o[t],r=n?n.length:0;r--;){var i=n[r],a=i.func;if(null==a||a==e)return i.name}return t}var o=n(175);e.exports=r},function(e){var t={};e.exports=t},function(e,t,n){function r(e){if(u(e)&&!s(e)&&!(e instanceof o)){if(e instanceof i)return e;if(p.call(e,"__chain__")&&p.call(e,"__wrapped__"))return c(e)}return new i(e)}var o=n(170),i=n(177),a=n(171),s=n(36),u=n(29),c=n(178),l=Object.prototype,p=l.hasOwnProperty;r.prototype=a.prototype,e.exports=r},function(e,t,n){function r(e,t,n){this.__wrapped__=e,this.__actions__=n||[],this.__chain__=!!t}var o=n(165),i=n(171);r.prototype=o(i.prototype),r.prototype.constructor=r,e.exports=r},function(e,t,n){function r(e){return e instanceof o?e.clone():new i(e.__wrapped__,e.__chain__,a(e.__actions__))}var o=n(170),i=n(177),a=n(45);e.exports=r},function(e,t,n){function r(e,t){for(var n=e.length,r=a(t.length,n),s=o(e);r--;){var u=t[r];e[r]=i(u,n)?s[u]:void 0}return e}var o=n(45),i=n(37),a=Math.min;e.exports=r},function(e){function t(e,t){for(var r=-1,o=e.length,i=-1,a=[];++r<o;)e[r]===t&&(e[r]=n,a[++i]=r);return a}var n="__lodash_placeholder__";e.exports=t},function(e,t,n){var r=n(161),o=n(182),i=150,a=16,s=function(){var e=0,t=0;return function(n,s){var u=o(),c=a-(u-t);if(t=u,c>0){if(++e>=i)return n}else e=0;return r(n,s)}}();e.exports=s},function(e,t,n){var r=n(26),o=r(Date,"now"),i=o||function(){return(new Date).getTime()};e.exports=i},function(e,t,n){(function(t){function r(e,n,r,a){function s(){for(var n=-1,o=arguments.length,i=-1,l=a.length,p=Array(l+o);++i<l;)p[i]=a[i];for(;o--;)p[i++]=arguments[++n];var f=this&&this!==t&&this instanceof s?c:e;return f.apply(u?r:this,p)}var u=n&i,c=o(e);return s}var o=n(164),i=1;e.exports=r}).call(t,function(){return this}())},function(e,t,n){function r(e,t){var n=e[1],r=t[1],v=n|r,m=p>v,g=r==p&&n==l||r==p&&n==f&&e[7].length<=t[8]||r==(p|f)&&n==l;if(!m&&!g)return e;r&u&&(e[2]=t[2],v|=n&u?0:c);var y=t[3];if(y){var b=e[3];e[3]=b?i(b,y,t[4]):o(y),e[4]=b?s(e[3],h):o(t[4])}return y=t[5],y&&(b=e[5],e[5]=b?a(b,y,t[6]):o(y),e[6]=b?s(e[5],h):o(t[6])),y=t[7],y&&(e[7]=o(y)),r&p&&(e[8]=null==e[8]?t[8]:d(e[8],t[8])),null==e[9]&&(e[9]=t[9]),e[0]=t[0],e[1]=v,e}var o=n(45),i=n(167),a=n(168),s=n(180),u=1,c=4,l=8,p=128,f=256,h="__lodash_placeholder__",d=Math.min;e.exports=r},function(e,t,n){var r=n(159),o=64,i=r(o);i.placeholder={},e.exports=i},function(e,t,n){"use strict";var r=n(111);e.exports=function(e){return r(e,function(e,t){var n=t.split(":");return e[0].push(n[0]),e[1].push(n[1]),e},[[],[]])}},function(e,t,n){"use strict";function r(e){return function(t,n){var r=e.hierarchicalFacets[n],i=e.hierarchicalFacetsRefinements[r.name]&&e.hierarchicalFacetsRefinements[r.name][0]||"",a=e._getHierarchicalFacetSeparator(r),s=d(e._getHierarchicalFacetSortBy(r)),u=o(s,a,i);return c(t,u,{name:e.hierarchicalFacets[n].name,count:null,isRefined:!0,path:null,data:null})}}function o(e,t,n){return function(r,o,s){var c=r;if(s>0){var p=0;for(c=r;s>p;)c=c&&f(c.data,{isRefined:!0}),p++}if(c){var d=i(c.path,n,t);c.data=l(u(h(o.data,d),a(t,n)),e[0],e[1])}return r}}function i(e,t,n){return function(r,o){return-1===o.indexOf(n)||-1===o.indexOf(n)&&-1===t.indexOf(n)||0===t.indexOf(o+n)||0===o.indexOf(e+n)}}function a(e,t){return function(n,r){return{name:p(s(r.split(e))),path:r,count:n,isRefined:t===r||0===t.indexOf(r+e),data:null}}}e.exports=r;var s=n(102),u=n(108),c=n(111),l=n(153),p=n(188),f=n(128),h=n(194),d=n(186)},function(e,t,n){function r(e,t,n){var r=e;return(e=o(e))?(n?s(r,t,n):null==t)?e.slice(u(e),c(e)+1):(t+="",e.slice(i(e,t),a(e,t)+1)):e}var o=n(104),i=n(189),a=n(190),s=n(52),u=n(191),c=n(193);e.exports=r},function(e){function t(e,t){for(var n=-1,r=e.length;++n<r&&t.indexOf(e.charAt(n))>-1;);return n}e.exports=t},function(e){function t(e,t){for(var n=e.length;n--&&t.indexOf(e.charAt(n))>-1;);return n}e.exports=t},function(e,t,n){function r(e){for(var t=-1,n=e.length;++t<n&&o(e.charCodeAt(t)););return t}var o=n(192);e.exports=r},function(e){function t(e){return 160>=e&&e>=9&&13>=e||32==e||160==e||5760==e||6158==e||e>=8192&&(8202>=e||8232==e||8233==e||8239==e||8287==e||12288==e||65279==e)}e.exports=t},function(e,t,n){function r(e){for(var t=e.length;t--&&o(e.charCodeAt(t)););return t}var o=n(192);e.exports=r},function(e,t,n){var r=n(117),o=n(41),i=n(119),a=n(120),s=n(61),u=s(function(e,t){return null==e?{}:"function"==typeof t[0]?a(e,o(t[0],t[1],3)):i(e,r(t))});e.exports=u},function(e,t,n){"use strict";var r=n(17),o=n(108),i=n(111),a=n(53),s=n(36),u={_getQueries:function(e,t){var n=[];return n.push({indexName:e,query:t.query,params:this._getHitsSearchParams(t)}),r(t.getRefinedDisjunctiveFacets(),function(r){n.push({indexName:e,query:t.query,params:this._getDisjunctiveFacetSearchParams(t,r)})},this),r(t.getRefinedHierarchicalFacets(),function(r){var o=t.getHierarchicalFacetByName(r),i=t.getHierarchicalRefinement(r);i.length>0&&i[0].split(t._getHierarchicalFacetSeparator(o)).length>1&&n.push({indexName:e,query:t.query,params:this._getDisjunctiveFacetSearchParams(t,r,!0)})},this),n},_getHitsSearchParams:function(e){var t=e.facets.concat(e.disjunctiveFacets).concat(this._getHitsHierarchicalFacetsAttributes(e)),n=this._getFacetFilters(e),r=this._getNumericFilters(e),o=this._getTagFilters(e),i={facets:t,tagFilters:o};return(e.distinct===!0||e.distinct===!1)&&(i.distinct=e.distinct),n.length>0&&(i.facetFilters=n),r.length>0&&(i.numericFilters=r),a(e.getQueryParams(),i)},_getDisjunctiveFacetSearchParams:function(e,t,n){var r=this._getFacetFilters(e,t,n),o=this._getNumericFilters(e,t),i=this._getTagFilters(e),s={hitsPerPage:1,page:0,attributesToRetrieve:[],attributesToHighlight:[],attributesToSnippet:[],tagFilters:i},u=e.getHierarchicalFacetByName(t);return s.facets=u?this._getDisjunctiveHierarchicalFacetAttribute(e,u,n):t,(e.distinct===!0||e.distinct===!1)&&(s.distinct=e.distinct),o.length>0&&(s.numericFilters=o),r.length>0&&(s.facetFilters=r),a(e.getQueryParams(),s)},_getNumericFilters:function(e,t){if(e.numericFilters)return e.numericFilters;var n=[];return r(e.numericRefinements,function(e,i){r(e,function(e,a){t!==i&&r(e,function(e){if(s(e)){var t=o(e,function(e){return i+a+e});n.push(t)}else n.push(i+a+e)})})}),n},_getTagFilters:function(e){return e.tagFilters?e.tagFilters:e.tagRefinements.join(",")},_getFacetFilters:function(e,t,n){var o=[];return r(e.facetsRefinements,function(e,t){r(e,function(e){o.push(t+":"+e)})}),r(e.facetsExcludes,function(e,t){r(e,function(e){o.push(t+":-"+e)})}),r(e.disjunctiveFacetsRefinements,function(e,n){if(n!==t&&e&&0!==e.length){var i=[];r(e,function(e){i.push(n+":"+e)}),o.push(i)}}),r(e.hierarchicalFacetsRefinements,function(r,i){var a=r[0];if(void 0!==a){var s,u=e.getHierarchicalFacetByName(i),c=e._getHierarchicalFacetSeparator(u);if(t===i){if(-1===a.indexOf(c)||n===!0)return;s=u.attributes[a.split(c).length-2],a=a.slice(0,a.lastIndexOf(c))}else s=u.attributes[a.split(c).length-1];o.push([s+":"+a])}}),o},_getHitsHierarchicalFacetsAttributes:function(e){var t=[];return i(e.hierarchicalFacets,function(t,n){var r=e.getHierarchicalRefinement(n.name)[0];if(!r)return t.push(n.attributes[0]),t;var o=r.split(e._getHierarchicalFacetSeparator(n)).length,i=n.attributes.slice(0,o+1);return t.concat(i)},t)},_getDisjunctiveHierarchicalFacetAttribute:function(e,t,n){if(n===!0)return[t.attributes[0]];var r=e.getHierarchicalRefinement(t.name)[0]||"",o=r.split(e._getHierarchicalFacetSeparator(t)).length-1;return t.attributes.slice(0,o+1)}};e.exports=u},function(e,t,n){(function(e,r){function o(e,n){var r={seen:[],stylize:a};return arguments.length>=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),v(n)?r.showHidden=n:n&&t._extend(r,n),x(r.showHidden)&&(r.showHidden=!1),x(r.depth)&&(r.depth=2),x(r.colors)&&(r.colors=!1),x(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=i),u(r,e,r.depth)}function i(e,t){var n=o.styles[t];return n?"["+o.colors[n][0]+"m"+e+"["+o.colors[n][1]+"m":e}function a(e){return e}function s(e){var t={};return e.forEach(function(e){t[e]=!0}),t}function u(e,n,r){if(e.customInspect&&n&&R(n.inspect)&&n.inspect!==t.inspect&&(!n.constructor||n.constructor.prototype!==n)){var o=n.inspect(r,e);return b(o)||(o=u(e,o,r)),o}var i=c(e,n);if(i)return i;var a=Object.keys(n),v=s(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(n)),E(n)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return l(n);if(0===a.length){if(R(n)){var m=n.name?": "+n.name:"";return e.stylize("[Function"+m+"]","special")}if(_(n))return e.stylize(RegExp.prototype.toString.call(n),"regexp");if(C(n))return e.stylize(Date.prototype.toString.call(n),"date");if(E(n))return l(n)}var g="",y=!1,w=["{","}"];if(d(n)&&(y=!0,w=["[","]"]),R(n)){var x=n.name?": "+n.name:"";g=" [Function"+x+"]"}if(_(n)&&(g=" "+RegExp.prototype.toString.call(n)),C(n)&&(g=" "+Date.prototype.toUTCString.call(n)),E(n)&&(g=" "+l(n)),0===a.length&&(!y||0==n.length))return w[0]+g+w[1];if(0>r)return _(n)?e.stylize(RegExp.prototype.toString.call(n),"regexp"):e.stylize("[Object]","special");e.seen.push(n);var P;return P=y?p(e,n,r,v,a):a.map(function(t){return f(e,n,r,v,t,y)}),e.seen.pop(),h(P,g,w)}function c(e,t){if(x(t))return e.stylize("undefined","undefined");if(b(t)){var n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}return y(t)?e.stylize(""+t,"number"):v(t)?e.stylize(""+t,"boolean"):m(t)?e.stylize("null","null"):void 0}function l(e){return"["+Error.prototype.toString.call(e)+"]"}function p(e,t,n,r,o){for(var i=[],a=0,s=t.length;s>a;++a)i.push(j(t,String(a))?f(e,t,n,r,String(a),!0):"");return o.forEach(function(o){o.match(/^\d+$/)||i.push(f(e,t,n,r,o,!0))}),i}function f(e,t,n,r,o,i){var a,s,c;if(c=Object.getOwnPropertyDescriptor(t,o)||{value:t[o]},c.get?s=c.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):c.set&&(s=e.stylize("[Setter]","special")),j(r,o)||(a="["+o+"]"),s||(e.seen.indexOf(c.value)<0?(s=m(n)?u(e,c.value,null):u(e,c.value,n-1),s.indexOf("\n")>-1&&(s=i?s.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+s.split("\n").map(function(e){return" "+e}).join("\n"))):s=e.stylize("[Circular]","special")),x(a)){if(i&&o.match(/^\d+$/))return s;a=JSON.stringify(""+o),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+s}function h(e,t,n){var r=0,o=e.reduce(function(e,t){return r++,t.indexOf("\n")>=0&&r++,e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0);return o>60?n[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+n[1]:n[0]+t+" "+e.join(", ")+" "+n[1]}function d(e){return Array.isArray(e)}function v(e){return"boolean"==typeof e}function m(e){return null===e}function g(e){return null==e}function y(e){return"number"==typeof e}function b(e){return"string"==typeof e}function w(e){return"symbol"==typeof e}function x(e){return void 0===e}function _(e){return P(e)&&"[object RegExp]"===O(e)}function P(e){return"object"==typeof e&&null!==e}function C(e){return P(e)&&"[object Date]"===O(e)}function E(e){return P(e)&&("[object Error]"===O(e)||e instanceof Error)}function R(e){return"function"==typeof e}function T(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||"undefined"==typeof e}function O(e){return Object.prototype.toString.call(e)}function S(e){return 10>e?"0"+e.toString(10):e.toString(10)}function N(){var e=new Date,t=[S(e.getHours()),S(e.getMinutes()),S(e.getSeconds())].join(":");return[e.getDate(),A[e.getMonth()],t].join(" ")}function j(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var k=/%[sdj%]/g;t.format=function(e){if(!b(e)){for(var t=[],n=0;n<arguments.length;n++)t.push(o(arguments[n]));return t.join(" ")}for(var n=1,r=arguments,i=r.length,a=String(e).replace(k,function(e){if("%%"===e)return"%";if(n>=i)return e;switch(e){case"%s":return String(r[n++]);case"%d":return Number(r[n++]);case"%j":try{return JSON.stringify(r[n++])}catch(t){return"[Circular]"}default:return e}}),s=r[n];i>n;s=r[++n])a+=m(s)||!P(s)?" "+s:" "+o(s);return a},t.deprecate=function(n,o){function i(){if(!a){if(r.throwDeprecation)throw new Error(o);r.traceDeprecation?console.trace(o):console.error(o),a=!0}return n.apply(this,arguments)}if(x(e.process))return function(){return t.deprecate(n,o).apply(this,arguments)};if(r.noDeprecation===!0)return n;var a=!1;return i};var I,D={};t.debuglog=function(e){if(x(I)&&(I={NODE_ENV:"production"}.NODE_DEBUG||""),e=e.toUpperCase(),!D[e])if(new RegExp("\\b"+e+"\\b","i").test(I)){var n=r.pid;D[e]=function(){var r=t.format.apply(t,arguments);console.error("%s %d: %s",e,n,r)}}else D[e]=function(){};return D[e]},t.inspect=o,o.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},o.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"},t.isArray=d,t.isBoolean=v,t.isNull=m,t.isNullOrUndefined=g,t.isNumber=y,t.isString=b,t.isSymbol=w,t.isUndefined=x,t.isRegExp=_,t.isObject=P,t.isDate=C,t.isError=E,t.isFunction=R,t.isPrimitive=T,t.isBuffer=n(197);var A=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];t.log=function(){console.log("%s - %s",N(),t.format.apply(t,arguments))},t.inherits=n(198),t._extend=function(e,t){if(!t||!P(t))return e;for(var n=Object.keys(t),r=n.length;r--;)e[n[r]]=t[n[r]];return e}}).call(t,function(){return this}(),n(8))},function(e){e.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},function(e){e.exports="function"==typeof Object.create?function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:function(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}},function(e,t,n){var r=n(160),o=n(180),i=n(61),a=1,s=32,u=i(function(e,t,n){var i=a;if(n.length){var c=o(n,u.placeholder);i|=s}return r(e,i,t,n,c)});u.placeholder={},e.exports=u},function(e,t,n){"use strict";function r(e){return v(e)?h(e,r):m(e)?p(e,r):d(e)?g(e):e}function o(e,t,n){if(null!==e&&(t=t.replace(e,""),n=n.replace(e,"")),-1!==b.indexOf(t)||-1!==b.indexOf(n)){if("q"===t)return-1;if("q"===n)return 1;var r=-1!==y.indexOf(t),o=-1!==y.indexOf(n);if(r&&!o)return 1;if(o&&!r)return-1}return t.localeCompare(n)}var i=n(201),a=n(74),s=n(203),u=n(199),c=n(17),l=n(194),p=n(108),f=n(207),h=n(209),d=n(125),v=n(56),m=n(36),g=n(205).encode,y=["dFR","fR","nR","hFR","tR"],b=i.ENCODED_PARAMETERS;t.getStateFromQueryString=function(e,t){var n=t&&t.prefix||"",r=s.parse(e),o=new RegExp("^"+n),u=f(r,function(e,t){if(n&&o.test(t)){var r=t.replace(o,"");return i.decode(r)}var a=i.decode(t);return a||t}),c=a._parseNumbers(u);return l(c,a.PARAMETERS)},t.getUnrecognizedParametersInQueryString=function(e,t){var n=t&&t.prefix,r={},o=s.parse(e);if(n){var a=new RegExp("^"+n);c(o,function(e,t){a.test(t)||(r[t]=e)})}else c(o,function(e,t){i.decode(t)||(r[t]=e)});return r},t.getQueryStringFromState=function(e,t){var n=t&&t.moreAttributes,a=t&&t.prefix||"",c=r(e),l=f(c,function(e,t){var n=i.encode(t);return a+n}),p=""===a?null:new RegExp("^"+a),h=u(o,null,p);if(n){var d=s.stringify(l,{encode:!1,sort:h}),v=s.stringify(n,{encode:!1});return d?d+"&"+v:v}return s.stringify(l,{encode:!1,sort:h})}},function(e,t,n){"use strict";var r=n(202),o=n(25),i={advancedSyntax:"aS",allowTyposOnNumericTokens:"aTONT",analyticsTags:"aT",analytics:"a",aroundLatLngViaIP:"aLLVIP",aroundLatLng:"aLL",aroundPrecision:"aP",aroundRadius:"aR",attributesToHighlight:"aTH",attributesToRetrieve:"aTR",attributesToSnippet:"aTS",disjunctiveFacetsRefinements:"dFR",disjunctiveFacets:"dF",distinct:"d",facetsExcludes:"fE",facetsRefinements:"fR",facets:"f",getRankingInfo:"gRI",hierarchicalFacetsRefinements:"hFR",hierarchicalFacets:"hF",highlightPostTag:"hPoT",highlightPreTag:"hPrT",hitsPerPage:"hPP",ignorePlurals:"iP",index:"idx",insideBoundingBox:"iBB",insidePolygon:"iPg",length:"l",maxValuesPerFacet:"mVPF",minimumAroundRadius:"mAR",minWordSizefor1Typo:"mWS1T",minWordSizefor2Typos:"mWS2T",numericFilters:"nF",numericRefinements:"nR",offset:"o",optionalWords:"oW",page:"p",queryType:"qT",query:"q",removeWordsIfNoResults:"rWINR",replaceSynonymsInHighlight:"rSIH",restrictSearchableAttributes:"rSA",synonyms:"s",tagFilters:"tF",tagRefinements:"tR",typoTolerance:"tT"},a=r(i);e.exports={ENCODED_PARAMETERS:o(a),decode:function(e){return a[e]},encode:function(e){return i[e]}}},function(e,t,n){function r(e,t,n){n&&o(e,t,n)&&(t=void 0);for(var r=-1,a=i(e),u=a.length,c={};++r<u;){var l=a[r],p=e[l];t?s.call(c,p)?c[p].push(l):c[p]=[l]:c[p]=l}return c}var o=n(52),i=n(25),a=Object.prototype,s=a.hasOwnProperty;e.exports=r},function(e,t,n){var r=n(204),o=n(206);e.exports={stringify:r,parse:o}},function(e,t,n){var r=n(205),o={delimiter:"&",arrayPrefixGenerators:{brackets:function(e){return e+"[]"},indices:function(e,t){return e+"["+t+"]"},repeat:function(e){return e}},strictNullHandling:!1,skipNulls:!1,encode:!0};o.stringify=function(e,t,n,i,a,s,u,c){if("function"==typeof u)e=u(t,e);else if(r.isBuffer(e))e=e.toString();else if(e instanceof Date)e=e.toISOString();else if(null===e){if(i)return s?r.encode(t):t;e=""}if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return s?[r.encode(t)+"="+r.encode(e)]:[t+"="+e];var l=[];if("undefined"==typeof e)return l;var p;if(Array.isArray(u))p=u;else{var f=Object.keys(e);p=c?f.sort(c):f}for(var h=0,d=p.length;d>h;++h){var v=p[h];a&&null===e[v]||(l=l.concat(Array.isArray(e)?o.stringify(e[v],n(t,v),n,i,a,s,u):o.stringify(e[v],t+"["+v+"]",n,i,a,s,u)))}return l},e.exports=function(e,t){t=t||{};var n,r,i="undefined"==typeof t.delimiter?o.delimiter:t.delimiter,a="boolean"==typeof t.strictNullHandling?t.strictNullHandling:o.strictNullHandling,s="boolean"==typeof t.skipNulls?t.skipNulls:o.skipNulls,u="boolean"==typeof t.encode?t.encode:o.encode,c="function"==typeof t.sort?t.sort:null;"function"==typeof t.filter?(r=t.filter,e=r("",e)):Array.isArray(t.filter)&&(n=r=t.filter);var l=[];if("object"!=typeof e||null===e)return"";var p;p=t.arrayFormat in o.arrayPrefixGenerators?t.arrayFormat:"indices"in t?t.indices?"indices":"repeat":"indices";var f=o.arrayPrefixGenerators[p];n||(n=Object.keys(e)),c&&n.sort(c);for(var h=0,d=n.length;d>h;++h){var v=n[h];s&&null===e[v]||(l=l.concat(o.stringify(e[v],v,f,a,s,u,r,c)))}return l.join(i)}},function(e,t){var n={};n.hexTable=new Array(256);for(var r=0;256>r;++r)n.hexTable[r]="%"+((16>r?"0":"")+r.toString(16)).toUpperCase();t.arrayToObject=function(e,t){for(var n=t.plainObjects?Object.create(null):{},r=0,o=e.length;o>r;++r)"undefined"!=typeof e[r]&&(n[r]=e[r]);return n},t.merge=function(e,n,r){if(!n)return e;if("object"!=typeof n)return Array.isArray(e)?e.push(n):"object"==typeof e?e[n]=!0:e=[e,n],e;if("object"!=typeof e)return e=[e].concat(n);Array.isArray(e)&&!Array.isArray(n)&&(e=t.arrayToObject(e,r));for(var o=Object.keys(n),i=0,a=o.length;a>i;++i){var s=o[i],u=n[s];e[s]=Object.prototype.hasOwnProperty.call(e,s)?t.merge(e[s],u,r):u}return e},t.decode=function(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch(t){return e}},t.encode=function(e){if(0===e.length)return e;"string"!=typeof e&&(e=""+e);for(var t="",r=0,o=e.length;o>r;++r){var i=e.charCodeAt(r);45===i||46===i||95===i||126===i||i>=48&&57>=i||i>=65&&90>=i||i>=97&&122>=i?t+=e[r]:128>i?t+=n.hexTable[i]:2048>i?t+=n.hexTable[192|i>>6]+n.hexTable[128|63&i]:55296>i||i>=57344?t+=n.hexTable[224|i>>12]+n.hexTable[128|i>>6&63]+n.hexTable[128|63&i]:(++r,i=65536+((1023&i)<<10|1023&e.charCodeAt(r)),t+=n.hexTable[240|i>>18]+n.hexTable[128|i>>12&63]+n.hexTable[128|i>>6&63]+n.hexTable[128|63&i])}return t},t.compact=function(e,n){if("object"!=typeof e||null===e)return e;n=n||[];var r=n.indexOf(e);if(-1!==r)return n[r];if(n.push(e),Array.isArray(e)){for(var o=[],i=0,a=e.length;a>i;++i)"undefined"!=typeof e[i]&&o.push(e[i]);return o}var s=Object.keys(e);for(i=0,a=s.length;a>i;++i){var u=s[i];e[u]=t.compact(e[u],n)}return e},t.isRegExp=function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},t.isBuffer=function(e){return null===e||"undefined"==typeof e?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}},function(e,t,n){var r=n(205),o={delimiter:"&",depth:5,arrayLimit:20,parameterLimit:1e3,strictNullHandling:!1,plainObjects:!1,allowPrototypes:!1,allowDots:!1};o.parseValues=function(e,t){for(var n={},o=e.split(t.delimiter,t.parameterLimit===1/0?void 0:t.parameterLimit),i=0,a=o.length;a>i;++i){var s=o[i],u=-1===s.indexOf("]=")?s.indexOf("="):s.indexOf("]=")+1;if(-1===u)n[r.decode(s)]="",t.strictNullHandling&&(n[r.decode(s)]=null);else{var c=r.decode(s.slice(0,u)),l=r.decode(s.slice(u+1));n[c]=Object.prototype.hasOwnProperty.call(n,c)?[].concat(n[c]).concat(l):l}}return n},o.parseObject=function(e,t,n){if(!e.length)return t;var r,i=e.shift();if("[]"===i)r=[],r=r.concat(o.parseObject(e,t,n));else{r=n.plainObjects?Object.create(null):{};var a="["===i[0]&&"]"===i[i.length-1]?i.slice(1,i.length-1):i,s=parseInt(a,10),u=""+s;!isNaN(s)&&i!==a&&u===a&&s>=0&&n.parseArrays&&s<=n.arrayLimit?(r=[],r[s]=o.parseObject(e,t,n)):r[a]=o.parseObject(e,t,n)}return r},o.parseKeys=function(e,t,n){if(e){n.allowDots&&(e=e.replace(/\.([^\.\[]+)/g,"[$1]"));var r=/^([^\[\]]*)/,i=/(\[[^\[\]]*\])/g,a=r.exec(e),s=[];if(a[1]){if(!n.plainObjects&&Object.prototype.hasOwnProperty(a[1])&&!n.allowPrototypes)return;s.push(a[1])}for(var u=0;null!==(a=i.exec(e))&&u<n.depth;)++u,(n.plainObjects||!Object.prototype.hasOwnProperty(a[1].replace(/\[|\]/g,""))||n.allowPrototypes)&&s.push(a[1]);return a&&s.push("["+e.slice(a.index)+"]"),o.parseObject(s,t,n)}},e.exports=function(e,t){if(t=t||{},t.delimiter="string"==typeof t.delimiter||r.isRegExp(t.delimiter)?t.delimiter:o.delimiter,t.depth="number"==typeof t.depth?t.depth:o.depth,t.arrayLimit="number"==typeof t.arrayLimit?t.arrayLimit:o.arrayLimit,t.parseArrays=t.parseArrays!==!1,t.allowDots="boolean"==typeof t.allowDots?t.allowDots:o.allowDots,t.plainObjects="boolean"==typeof t.plainObjects?t.plainObjects:o.plainObjects,t.allowPrototypes="boolean"==typeof t.allowPrototypes?t.allowPrototypes:o.allowPrototypes,t.parameterLimit="number"==typeof t.parameterLimit?t.parameterLimit:o.parameterLimit,t.strictNullHandling="boolean"==typeof t.strictNullHandling?t.strictNullHandling:o.strictNullHandling,""===e||null===e||"undefined"==typeof e)return t.plainObjects?Object.create(null):{};for(var n="string"==typeof e?o.parseValues(e,t):e,i=t.plainObjects?Object.create(null):{},a=Object.keys(n),s=0,u=a.length;u>s;++s){var c=a[s],l=o.parseKeys(c,n[c],t);i=r.merge(i,l,t)}return r.compact(i)}},function(e,t,n){var r=n(208),o=r(!0);e.exports=o},function(e,t,n){function r(e){return function(t,n,r){var a={};return n=o(n,r,3),i(t,function(t,r,o){var i=n(t,r,o);r=e?i:r,t=e?t:i,a[r]=t}),a}}var o=n(86),i=n(20);e.exports=r},function(e,t,n){var r=n(208),o=r();e.exports=o},function(e){"use strict";e.exports="2.6.4"},function(e,t,n){var r=n(117),o=n(212),i=n(61),a=i(function(e){return o(r(e,!1,!0))});e.exports=a},function(e,t,n){function r(e,t){var n=-1,r=o,u=e.length,c=!0,l=c&&u>=s,p=l?a():null,f=[];p?(r=i,c=!1):(l=!1,p=t?[]:f);e:for(;++n<u;){var h=e[n],d=t?t(h,n,e):h;if(c&&h===h){for(var v=p.length;v--;)if(p[v]===d)continue e;t&&p.push(d),f.push(h)}else r(p,d,0)<0&&((t||l)&&p.push(d),f.push(h))}return f}var o=n(76),i=n(78),a=n(79),s=200;e.exports=r},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e){var t=e;return function(){var e=Date.now(),n=e-t;return t=e,n}}function i(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.useHash||!1,n=t?f:h;return new d(n,e)}var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s=n(72),u=s.AlgoliaSearchHelper,c=n(214).split(".")[0],l=n(215),p=n(53),f={character:"#",onpopstate:function(e){window.addEventListener("hashchange",e)},pushState:function(e){window.location.assign(this.createURL(e))},replaceState:function(e){window.location.replace(this.createURL(e))},createURL:function(e){return document.location.search+this.character+e},readUrl:function(){return window.location.hash.slice(1)}},h={character:"?",onpopstate:function(e){window.addEventListener("popstate",e)},pushState:function(e){window.history.pushState(null,"",this.createURL(e))},replaceState:function(e){window.history.replaceState(null,"",this.createURL(e))},createURL:function(e){return this.character+e+document.location.hash},readUrl:function(){return window.location.search.slice(1)}},d=function(){function e(t,n){r(this,e),this.__initLast=!0,this.urlUtils=t,this.originalConfig=null,this.timer=o(Date.now()),this.threshold=n.threshold||700,this.trackedParameters=n.trackedParameters||["query","attribute:*","index","page","hitsPerPage"]}return a(e,[{key:"getConfiguration",value:function(e){this.originalConfig=e;var t=this.urlUtils.readUrl(),n=u.getConfigurationFromQueryString(t);return n}},{key:"onPopState",value:function(e){var t=this.urlUtils.readUrl(),n=u.getConfigurationFromQueryString(t),r=p({},this.originalConfig,n),o=e.getState(this.trackedParameters),i=p({},this.originalConfig,o);l(i,r)||e.setState(r).search()}},{key:"init",value:function(e,t){this.urlUtils.onpopstate(this.onPopState.bind(this,t))}},{key:"render",value:function(e){var t=e.helper,n=t.getState(this.trackedParameters),r=this.urlUtils.readUrl(),o=u.getConfigurationFromQueryString(r);if(!l(n,o)){var i=u.getForeignConfigurationInQueryString(r);i.is_v=c;var a=t.getStateAsQueryString({filters:this.trackedParameters,moreAttributes:i});this.timer()<this.threshold?this.urlUtils.replaceState(a):this.urlUtils.pushState(a)}}},{key:"createURL",value:function(e){var t=this.urlUtils.readUrl(),n=e.filter(this.trackedParameters),r=s.url.getUnrecognizedParametersInQueryString(t);return r.is_v=c,this.urlUtils.createURL(s.url.getQueryStringFromState(n))}}]),e}();e.exports=i},function(e){"use strict";e.exports="0.8.0"},function(e,t,n){function r(e,t,n,r){n="function"==typeof n?i(n,r,3):void 0;var a=n?n(e,t):void 0;return void 0===a?o(e,t,n):!!a}var o=n(89),i=n(41);e.exports=r},function(e,t,n){"use strict";function r(e){var t=e.container,r=e.attributes,d=void 0===r?[]:r,v=e.separator,m=e.limit,g=void 0===m?100:m,y=e.sortBy,b=void 0===y?["name:asc"]:y,w=e.cssClasses,x=void 0===w?{}:w,_=e.hideContainerWhenNoResults,P=void 0===_?!0:_,C=e.templates,E=void 0===C?h:C,R=e.transformData,T=u.getContainerNode(t),O="Usage: hierarchicalMenu({container, attributes, [separator, sortBy, limit, cssClasses.{root, list, item}, templates.{header, item, footer}, transformData, hideContainerWhenNoResults]})",S=f(n(381));if(P===!0&&(S=p(S)),!t||!d||!d.length)throw new Error(O);var N=d[0];return{getConfiguration:function(){return{hierarchicalFacets:[{name:N,attributes:d,separator:v}]}},render:function(e){var t=e.results,n=e.helper,r=e.templatesConfig,p=e.createURL,f=e.state,d=i(t,N,b),v=0===d.length,m=u.prepareTemplateProps({ transformData:R,defaultTemplates:h,templatesConfig:r,templates:E}),y={root:l(c(null),x.root),header:l(c("header"),x.header),body:l(c("body"),x.body),footer:l(c("footer"),x.footer),list:l(c("list"),x.list),depth:c("list","lvl"),item:l(c("item"),x.item),active:l(c("item","active"),x.active),link:l(c("link"),x.link),count:l(c("count"),x.count)};s.render(a.createElement(S,{createURL:function(e){return p(f.toggleRefinement(N,e))},cssClasses:y,facetNameKey:"path",facetValues:d,limit:g,shouldAutoHideContainer:v,templateProps:m,toggleRefinement:o.bind(null,n,N)}),T)}}}function o(e,t,n){e.toggleRefinement(t,n).search()}function i(e,t,n){var r=e.getFacetValues(t,{sortBy:n});return r.data||[]}var a=n(217),s=n(369),u=n(370),c=u.bemHelper("ais-hierarchical-menu"),l=n(371),p=n(372),f=n(373),h=n(380);e.exports=r},function(e,t,n){"use strict";e.exports=n(218)},function(e,t,n){"use strict";var r=n(219),o=n(359),i=n(363),a=n(254),s=n(368),u={};a(u,i),a(u,{findDOMNode:s("findDOMNode","ReactDOM","react-dom",r,r.findDOMNode),render:s("render","ReactDOM","react-dom",r,r.render),unmountComponentAtNode:s("unmountComponentAtNode","ReactDOM","react-dom",r,r.unmountComponentAtNode),renderToString:s("renderToString","ReactDOMServer","react-dom/server",o,o.renderToString),renderToStaticMarkup:s("renderToStaticMarkup","ReactDOMServer","react-dom/server",o,o.renderToStaticMarkup)}),u.__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=r,e.exports=u},function(e,t,n){"use strict";{var r=n(220),o=n(221),i=n(286),a=n(260),s=n(243),u=n(233),c=n(265),l=n(269),p=n(357),f=n(306),h=n(358);n(240)}i.inject();var d=u.measure("React","render",s.render),v={findDOMNode:f,render:d,unmountComponentAtNode:s.unmountComponentAtNode,version:p,unstable_batchedUpdates:l.batchedUpdates,unstable_renderSubtreeIntoContainer:h};"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject&&__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({CurrentOwner:r,InstanceHandles:a,Mount:s,Reconciler:c,TextComponent:o});e.exports=v},function(e){"use strict";var t={current:null};e.exports=t},function(e,t,n){"use strict";var r=n(222),o=n(237),i=n(241),a=n(243),s=n(254),u=n(236),c=n(235),l=(n(285),function(){});s(l.prototype,{construct:function(e){this._currentElement=e,this._stringText=""+e,this._rootNodeID=null,this._mountIndex=0},mountComponent:function(e,t,n){if(this._rootNodeID=e,t.useCreateElement){var r=n[a.ownerDocumentContextKey],i=r.createElement("span");return o.setAttributeForID(i,e),a.getID(i),c(i,this._stringText),i}var s=u(this._stringText);return t.renderToStaticMarkup?s:"<span "+o.createMarkupForID(e)+">"+s+"</span>"},receiveComponent:function(e){if(e!==this._currentElement){this._currentElement=e;var t=""+e;if(t!==this._stringText){this._stringText=t;var n=a.getNode(this._rootNodeID);r.updateTextContent(n,t)}}},unmountComponent:function(){i.unmountIDFromEnvironment(this._rootNodeID)}}),e.exports=l},function(e,t,n){"use strict";function r(e,t,n){var r=n>=e.childNodes.length?null:e.childNodes.item(n);e.insertBefore(t,r)}var o=n(223),i=n(231),a=n(233),s=n(234),u=n(235),c=n(228),l={dangerouslyReplaceNodeWithMarkup:o.dangerouslyReplaceNodeWithMarkup,updateTextContent:u,processUpdates:function(e,t){for(var n,a=null,l=null,p=0;p<e.length;p++)if(n=e[p],n.type===i.MOVE_EXISTING||n.type===i.REMOVE_NODE){var f=n.fromIndex,h=n.parentNode.childNodes[f],d=n.parentID;h?void 0:c(!1),a=a||{},a[d]=a[d]||[],a[d][f]=h,l=l||[],l.push(h)}var v;if(v=t.length&&"string"==typeof t[0]?o.dangerouslyRenderMarkup(t):t,l)for(var m=0;m<l.length;m++)l[m].parentNode.removeChild(l[m]);for(var g=0;g<e.length;g++)switch(n=e[g],n.type){case i.INSERT_MARKUP:r(n.parentNode,v[n.markupIndex],n.toIndex);break;case i.MOVE_EXISTING:r(n.parentNode,a[n.parentID][n.fromIndex],n.toIndex);break;case i.SET_MARKUP:s(n.parentNode,n.content);break;case i.TEXT_CONTENT:u(n.parentNode,n.content);break;case i.REMOVE_NODE:}}};a.measureMethods(l,"DOMChildrenOperations",{updateTextContent:"updateTextContent"}),e.exports=l},function(e,t,n){"use strict";function r(e){return e.substring(1,e.indexOf(" "))}var o=n(224),i=n(225),a=n(230),s=n(229),u=n(228),c=/^(<[^ \/>]+)/,l="data-danger-index",p={dangerouslyRenderMarkup:function(e){o.canUseDOM?void 0:u(!1);for(var t,n={},p=0;p<e.length;p++)e[p]?void 0:u(!1),t=r(e[p]),t=s(t)?t:"*",n[t]=n[t]||[],n[t][p]=e[p];var f=[],h=0;for(t in n)if(n.hasOwnProperty(t)){var d,v=n[t];for(d in v)if(v.hasOwnProperty(d)){var m=v[d];v[d]=m.replace(c,"$1 "+l+'="'+d+'" ')}for(var g=i(v.join(""),a),y=0;y<g.length;++y){var b=g[y];b.hasAttribute&&b.hasAttribute(l)&&(d=+b.getAttribute(l),b.removeAttribute(l),f.hasOwnProperty(d)?u(!1):void 0,f[d]=b,h+=1)}}return h!==f.length?u(!1):void 0,f.length!==e.length?u(!1):void 0,f},dangerouslyReplaceNodeWithMarkup:function(e,t){o.canUseDOM?void 0:u(!1),t?void 0:u(!1),"html"===e.tagName.toLowerCase()?u(!1):void 0;var n;n="string"==typeof t?i(t,a)[0]:t,e.parentNode.replaceChild(n,e)}};e.exports=p},function(e){"use strict";var t=!("undefined"==typeof window||!window.document||!window.document.createElement),n={canUseDOM:t,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:t&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:t&&!!window.screen,isInWorker:!t};e.exports=n},function(e,t,n){"use strict";function r(e){var t=e.match(l);return t&&t[1].toLowerCase()}function o(e,t){var n=c;c?void 0:u(!1);var o=r(e),i=o&&s(o);if(i){n.innerHTML=i[1]+e+i[2];for(var l=i[0];l--;)n=n.lastChild}else n.innerHTML=e;var p=n.getElementsByTagName("script");p.length&&(t?void 0:u(!1),a(p).forEach(t));for(var f=a(n.childNodes);n.lastChild;)n.removeChild(n.lastChild);return f}var i=n(224),a=n(226),s=n(229),u=n(228),c=i.canUseDOM?document.createElement("div"):null,l=/^\s*<(\w+)/;e.exports=o},function(e,t,n){"use strict";function r(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"length"in e&&!("setInterval"in e)&&"number"!=typeof e.nodeType&&(Array.isArray(e)||"callee"in e||"item"in e)}function o(e){return r(e)?Array.isArray(e)?e.slice():i(e):[e]}var i=n(227);e.exports=o},function(e,t,n){"use strict";function r(e){var t=e.length;if(Array.isArray(e)||"object"!=typeof e&&"function"!=typeof e?o(!1):void 0,"number"!=typeof t?o(!1):void 0,0===t||t-1 in e?void 0:o(!1),e.hasOwnProperty)try{return Array.prototype.slice.call(e)}catch(n){}for(var r=Array(t),i=0;t>i;i++)r[i]=e[i];return r}var o=n(228);e.exports=r},function(e){"use strict";var t=function(e,t,n,r,o,i,a,s){if(!e){var u;if(void 0===t)u=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[n,r,o,i,a,s],l=0;u=new Error("Invariant Violation: "+t.replace(/%s/g,function(){return c[l++]}))}throw u.framesToPop=1,u}};e.exports=t},function(e,t,n){"use strict";function r(e){return a?void 0:i(!1),f.hasOwnProperty(e)||(e="*"),s.hasOwnProperty(e)||(a.innerHTML="*"===e?"<link />":"<"+e+"></"+e+">",s[e]=!a.firstChild),s[e]?f[e]:null}var o=n(224),i=n(228),a=o.canUseDOM?document.createElement("div"):null,s={},u=[1,'<select multiple="true">',"</select>"],c=[1,"<table>","</table>"],l=[3,"<table><tbody><tr>","</tr></tbody></table>"],p=[1,'<svg xmlns="http://www.w3.org/2000/svg">',"</svg>"],f={"*":[1,"?<div>","</div>"],area:[1,"<map>","</map>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],legend:[1,"<fieldset>","</fieldset>"],param:[1,"<object>","</object>"],tr:[2,"<table><tbody>","</tbody></table>"],optgroup:u,option:u,caption:c,colgroup:c,tbody:c,tfoot:c,thead:c,td:l,th:l},h=["circle","clipPath","defs","ellipse","g","image","line","linearGradient","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","text","tspan"];h.forEach(function(e){f[e]=p,s[e]=!0}),e.exports=r},function(e){"use strict";function t(e){return function(){return e}}function n(){}n.thatReturns=t,n.thatReturnsFalse=t(!1),n.thatReturnsTrue=t(!0),n.thatReturnsNull=t(null),n.thatReturnsThis=function(){return this},n.thatReturnsArgument=function(e){return e},e.exports=n},function(e,t,n){"use strict";var r=n(232),o=r({INSERT_MARKUP:null,MOVE_EXISTING:null,REMOVE_NODE:null,SET_MARKUP:null,TEXT_CONTENT:null});e.exports=o},function(e,t,n){"use strict";var r=n(228),o=function(e){var t,n={};e instanceof Object&&!Array.isArray(e)?void 0:r(!1);for(t in e)e.hasOwnProperty(t)&&(n[t]=t);return n};e.exports=o},function(e){"use strict";function t(e,t,n){return n}var n={enableMeasure:!1,storedMeasure:t,measureMethods:function(e,t,n){},measure:function(e,t,n){return n},injection:{injectMeasure:function(e){n.storedMeasure=e}}};e.exports=n},function(e,t,n){"use strict";var r=n(224),o=/^[ \r\n\t\f]/,i=/<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/,a=function(e,t){e.innerHTML=t};if("undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction&&(a=function(e,t){MSApp.execUnsafeLocalFunction(function(){e.innerHTML=t})}),r.canUseDOM){var s=document.createElement("div");s.innerHTML=" ",""===s.innerHTML&&(a=function(e,t){if(e.parentNode&&e.parentNode.replaceChild(e,e),o.test(t)||"<"===t[0]&&i.test(t)){e.innerHTML=String.fromCharCode(65279)+t;var n=e.firstChild;1===n.data.length?e.removeChild(n):n.deleteData(0,1)}else e.innerHTML=t})}e.exports=a},function(e,t,n){"use strict";var r=n(224),o=n(236),i=n(234),a=function(e,t){e.textContent=t};r.canUseDOM&&("textContent"in document.documentElement||(a=function(e,t){i(e,o(t))})),e.exports=a},function(e){"use strict";function t(e){return r[e]}function n(e){return(""+e).replace(o,t)}var r={"&":"&amp;",">":"&gt;","<":"&lt;",'"':"&quot;","'":"&#x27;"},o=/[&><"']/g;e.exports=n},function(e,t,n){"use strict";function r(e){return l.hasOwnProperty(e)?!0:c.hasOwnProperty(e)?!1:u.test(e)?(l[e]=!0,!0):(c[e]=!0,!1)}function o(e,t){return null==t||e.hasBooleanValue&&!t||e.hasNumericValue&&isNaN(t)||e.hasPositiveNumericValue&&1>t||e.hasOverloadedBooleanValue&&t===!1}var i=n(238),a=n(233),s=n(239),u=(n(240),/^[a-zA-Z_][\w\.\-]*$/),c={},l={},p={createMarkupForID:function(e){return i.ID_ATTRIBUTE_NAME+"="+s(e)},setAttributeForID:function(e,t){e.setAttribute(i.ID_ATTRIBUTE_NAME,t)},createMarkupForProperty:function(e,t){var n=i.properties.hasOwnProperty(e)?i.properties[e]:null;if(n){if(o(n,t))return"";var r=n.attributeName;return n.hasBooleanValue||n.hasOverloadedBooleanValue&&t===!0?r+'=""':r+"="+s(t)}return i.isCustomAttribute(e)?null==t?"":e+"="+s(t):null},createMarkupForCustomAttribute:function(e,t){return r(e)&&null!=t?e+"="+s(t):""},setValueForProperty:function(e,t,n){var r=i.properties.hasOwnProperty(t)?i.properties[t]:null;if(r){var a=r.mutationMethod;if(a)a(e,n);else if(o(r,n))this.deleteValueForProperty(e,t);else if(r.mustUseAttribute){var s=r.attributeName,u=r.attributeNamespace;u?e.setAttributeNS(u,s,""+n):r.hasBooleanValue||r.hasOverloadedBooleanValue&&n===!0?e.setAttribute(s,""):e.setAttribute(s,""+n)}else{var c=r.propertyName;r.hasSideEffects&&""+e[c]==""+n||(e[c]=n)}}else i.isCustomAttribute(t)&&p.setValueForAttribute(e,t,n)},setValueForAttribute:function(e,t,n){r(t)&&(null==n?e.removeAttribute(t):e.setAttribute(t,""+n))},deleteValueForProperty:function(e,t){var n=i.properties.hasOwnProperty(t)?i.properties[t]:null;if(n){var r=n.mutationMethod;if(r)r(e,void 0);else if(n.mustUseAttribute)e.removeAttribute(n.attributeName);else{var o=n.propertyName,a=i.getDefaultValueForProperty(e.nodeName,o);n.hasSideEffects&&""+e[o]===a||(e[o]=a)}}else i.isCustomAttribute(t)&&e.removeAttribute(t)}};a.measureMethods(p,"DOMPropertyOperations",{setValueForProperty:"setValueForProperty",setValueForAttribute:"setValueForAttribute",deleteValueForProperty:"deleteValueForProperty"}),e.exports=p},function(e,t,n){"use strict";function r(e,t){return(e&t)===t}var o=n(228),i={MUST_USE_ATTRIBUTE:1,MUST_USE_PROPERTY:2,HAS_SIDE_EFFECTS:4,HAS_BOOLEAN_VALUE:8,HAS_NUMERIC_VALUE:16,HAS_POSITIVE_NUMERIC_VALUE:48,HAS_OVERLOADED_BOOLEAN_VALUE:64,injectDOMPropertyConfig:function(e){var t=i,n=e.Properties||{},a=e.DOMAttributeNamespaces||{},u=e.DOMAttributeNames||{},c=e.DOMPropertyNames||{},l=e.DOMMutationMethods||{};e.isCustomAttribute&&s._isCustomAttributeFunctions.push(e.isCustomAttribute);for(var p in n){s.properties.hasOwnProperty(p)?o(!1):void 0;var f=p.toLowerCase(),h=n[p],d={attributeName:f,attributeNamespace:null,propertyName:p,mutationMethod:null,mustUseAttribute:r(h,t.MUST_USE_ATTRIBUTE),mustUseProperty:r(h,t.MUST_USE_PROPERTY),hasSideEffects:r(h,t.HAS_SIDE_EFFECTS),hasBooleanValue:r(h,t.HAS_BOOLEAN_VALUE),hasNumericValue:r(h,t.HAS_NUMERIC_VALUE),hasPositiveNumericValue:r(h,t.HAS_POSITIVE_NUMERIC_VALUE),hasOverloadedBooleanValue:r(h,t.HAS_OVERLOADED_BOOLEAN_VALUE)};if(d.mustUseAttribute&&d.mustUseProperty?o(!1):void 0,!d.mustUseProperty&&d.hasSideEffects?o(!1):void 0,d.hasBooleanValue+d.hasNumericValue+d.hasOverloadedBooleanValue<=1?void 0:o(!1),u.hasOwnProperty(p)){var v=u[p];d.attributeName=v}a.hasOwnProperty(p)&&(d.attributeNamespace=a[p]),c.hasOwnProperty(p)&&(d.propertyName=c[p]),l.hasOwnProperty(p)&&(d.mutationMethod=l[p]),s.properties[p]=d}}},a={},s={ID_ATTRIBUTE_NAME:"data-reactid",properties:{},getPossibleStandardName:null,_isCustomAttributeFunctions:[],isCustomAttribute:function(e){for(var t=0;t<s._isCustomAttributeFunctions.length;t++){var n=s._isCustomAttributeFunctions[t];if(n(e))return!0}return!1},getDefaultValueForProperty:function(e,t){var n,r=a[e];return r||(a[e]=r={}),t in r||(n=document.createElement(e),r[t]=n[t]),r[t]},injection:i};e.exports=s},function(e,t,n){"use strict";function r(e){return'"'+o(e)+'"'}var o=n(236);e.exports=r},function(e,t,n){"use strict";var r=n(230),o=r;e.exports=o},function(e,t,n){"use strict";var r=n(242),o=n(243),i={processChildrenUpdates:r.dangerouslyProcessChildrenUpdates,replaceNodeWithMarkupByID:r.dangerouslyReplaceNodeWithMarkupByID,unmountIDFromEnvironment:function(e){o.purgeID(e)}};e.exports=i},function(e,t,n){"use strict";var r=n(222),o=n(237),i=n(243),a=n(233),s=n(228),u={dangerouslySetInnerHTML:"`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.",style:"`style` must be set using `updateStylesByID()`."},c={updatePropertyByID:function(e,t,n){var r=i.getNode(e);u.hasOwnProperty(t)?s(!1):void 0,null!=n?o.setValueForProperty(r,t,n):o.deleteValueForProperty(r,t)},dangerouslyReplaceNodeWithMarkupByID:function(e,t){var n=i.getNode(e);r.dangerouslyReplaceNodeWithMarkup(n,t)},dangerouslyProcessChildrenUpdates:function(e,t){for(var n=0;n<e.length;n++)e[n].parentNode=i.getNode(e[n].parentID);r.processUpdates(e,t)}};a.measureMethods(c,"ReactDOMIDOperations",{dangerouslyReplaceNodeWithMarkupByID:"dangerouslyReplaceNodeWithMarkupByID",dangerouslyProcessChildrenUpdates:"dangerouslyProcessChildrenUpdates"}),e.exports=c},function(e,t,n){"use strict";function r(e,t){for(var n=Math.min(e.length,t.length),r=0;n>r;r++)if(e.charAt(r)!==t.charAt(r))return r;return e.length===t.length?-1:n}function o(e){return e?e.nodeType===H?e.documentElement:e.firstChild:null}function i(e){var t=o(e);return t&&$.getID(t)}function a(e){var t=s(e);if(t)if(B.hasOwnProperty(t)){var n=B[t];n!==e&&(p(n,t)?M(!1):void 0,B[t]=e)}else B[t]=e;return t}function s(e){return e&&e.getAttribute&&e.getAttribute(L)||""}function u(e,t){var n=s(e);n!==t&&delete B[n],e.setAttribute(L,t),B[t]=e}function c(e){return B.hasOwnProperty(e)&&p(B[e],e)||(B[e]=$.findReactNodeByID(e)),B[e]}function l(e){var t=R.get(e)._rootNodeID;return C.isNullComponentID(t)?null:(B.hasOwnProperty(t)&&p(B[t],t)||(B[t]=$.findReactNodeByID(t)),B[t])}function p(e,t){if(e){s(e)!==t?M(!1):void 0;var n=$.findReactContainerForID(t);if(n&&D(n,e))return!0}return!1}function f(e){delete B[e]}function h(e){var t=B[e];return t&&p(t,e)?void(z=t):!1}function d(e){z=null,E.traverseAncestors(e,h);var t=z;return z=null,t}function v(e,t,n,r,o,i){_.useCreateElement&&(i=k({},i),i[W]=n.nodeType===H?n:n.ownerDocument);var a=S.mountComponent(e,t,r,i);e._renderedComponent._topLevelWrapper=e,$._mountImageIntoNode(a,n,o,r)}function m(e,t,n,r,o){var i=j.ReactReconcileTransaction.getPooled(r);i.perform(v,null,e,t,n,i,r,o),j.ReactReconcileTransaction.release(i)}function g(e,t){for(S.unmountComponent(e),t.nodeType===H&&(t=t.documentElement);t.lastChild;)t.removeChild(t.lastChild)}function y(e){var t=i(e);return t?t!==E.getReactRootIDFromNodeID(t):!1}function b(e){for(;e&&e.parentNode!==e;e=e.parentNode)if(1===e.nodeType){var t=s(e);if(t){var n,r=E.getReactRootIDFromNodeID(t),o=e;do if(n=s(o),o=o.parentNode,null==o)return null;while(n!==r);if(o===Q[r])return e}}return null}var w=n(238),x=n(244),_=(n(220),n(256)),P=n(257),C=n(259),E=n(260),R=n(262),T=n(263),O=n(233),S=n(265),N=n(268),j=n(269),k=n(254),I=n(273),D=n(274),A=n(277),M=n(228),F=n(234),U=n(282),L=(n(285),n(240),w.ID_ATTRIBUTE_NAME),B={},q=1,H=9,V=11,W="__ReactMount_ownerDocument$"+Math.random().toString(36).slice(2),K={},Q={},Y=[],z=null,G=function(){};G.prototype.isReactComponent={},G.prototype.render=function(){return this.props};var $={TopLevelWrapper:G,_instancesByReactRootID:K,scrollMonitor:function(e,t){t()},_updateRootComponent:function(e,t,n,r){return $.scrollMonitor(n,function(){N.enqueueElementInternal(e,t),r&&N.enqueueCallbackInternal(e,r)}),e},_registerComponent:function(e,t){!t||t.nodeType!==q&&t.nodeType!==H&&t.nodeType!==V?M(!1):void 0,x.ensureScrollValueMonitoring();var n=$.registerContainer(t);return K[n]=e,n},_renderNewRootComponent:function(e,t,n,r){var o=A(e,null),i=$._registerComponent(o,t);return j.batchedUpdates(m,o,i,t,n,r),o},renderSubtreeIntoContainer:function(e,t,n,r){return null==e||null==e._reactInternalInstance?M(!1):void 0,$._renderSubtreeIntoContainer(e,t,n,r)},_renderSubtreeIntoContainer:function(e,t,n,r){P.isValidElement(t)?void 0:M(!1);var a=new P(G,null,null,null,null,null,t),u=K[i(n)];if(u){var c=u._currentElement,l=c.props;if(U(l,t)){var p=u._renderedComponent.getPublicInstance(),f=r&&function(){r.call(p)};return $._updateRootComponent(u,a,n,f),p}$.unmountComponentAtNode(n)}var h=o(n),d=h&&!!s(h),v=y(n),m=d&&!u&&!v,g=$._renderNewRootComponent(a,n,m,null!=e?e._reactInternalInstance._processChildContext(e._reactInternalInstance._context):I)._renderedComponent.getPublicInstance();return r&&r.call(g),g},render:function(e,t,n){return $._renderSubtreeIntoContainer(null,e,t,n)},registerContainer:function(e){var t=i(e);return t&&(t=E.getReactRootIDFromNodeID(t)),t||(t=E.createReactRootID()),Q[t]=e,t},unmountComponentAtNode:function(e){!e||e.nodeType!==q&&e.nodeType!==H&&e.nodeType!==V?M(!1):void 0;var t=i(e),n=K[t];if(!n){{var r=(y(e),s(e));r&&r===E.getReactRootIDFromNodeID(r)}return!1}return j.batchedUpdates(g,n,e),delete K[t],delete Q[t],!0},findReactContainerForID:function(e){var t=E.getReactRootIDFromNodeID(e),n=Q[t];return n},findReactNodeByID:function(e){var t=$.findReactContainerForID(e);return $.findComponentRoot(t,e)},getFirstReactDOM:function(e){return b(e)},findComponentRoot:function(e,t){var n=Y,r=0,o=d(t)||e;for(n[0]=o.firstChild,n.length=1;r<n.length;){for(var i,a=n[r++];a;){var s=$.getID(a);s?t===s?i=a:E.isAncestorIDOf(s,t)&&(n.length=r=0,n.push(a.firstChild)):n.push(a.firstChild),a=a.nextSibling}if(i)return n.length=0,i}n.length=0,M(!1)},_mountImageIntoNode:function(e,t,n,i){if(!t||t.nodeType!==q&&t.nodeType!==H&&t.nodeType!==V?M(!1):void 0,n){var a=o(t);if(T.canReuseMarkup(e,a))return;var s=a.getAttribute(T.CHECKSUM_ATTR_NAME);a.removeAttribute(T.CHECKSUM_ATTR_NAME);var u=a.outerHTML;a.setAttribute(T.CHECKSUM_ATTR_NAME,s);{var c=e,l=r(c,u);" (client) "+c.substring(l-20,l+20)+"\n (server) "+u.substring(l-20,l+20)}t.nodeType===H?M(!1):void 0}if(t.nodeType===H?M(!1):void 0,i.useCreateElement){for(;t.lastChild;)t.removeChild(t.lastChild);t.appendChild(e)}else F(t,e)},ownerDocumentContextKey:W,getReactRootID:i,getID:a,setID:u,getNode:c,getNodeFromInstance:l,isValid:p,purgeID:f};O.measureMethods($,"ReactMount",{_renderNewRootComponent:"_renderNewRootComponent",_mountImageIntoNode:"_mountImageIntoNode"}),e.exports=$},function(e,t,n){"use strict";function r(e){return Object.prototype.hasOwnProperty.call(e,m)||(e[m]=d++,f[e[m]]={}),f[e[m]]}var o=n(245),i=n(246),a=n(247),s=n(252),u=n(233),c=n(253),l=n(254),p=n(255),f={},h=!1,d=0,v={topAbort:"abort",topBlur:"blur",topCanPlay:"canplay",topCanPlayThrough:"canplaythrough",topChange:"change",topClick:"click",topCompositionEnd:"compositionend",topCompositionStart:"compositionstart",topCompositionUpdate:"compositionupdate",topContextMenu:"contextmenu",topCopy:"copy",topCut:"cut",topDoubleClick:"dblclick",topDrag:"drag",topDragEnd:"dragend",topDragEnter:"dragenter",topDragExit:"dragexit",topDragLeave:"dragleave",topDragOver:"dragover",topDragStart:"dragstart",topDrop:"drop",topDurationChange:"durationchange",topEmptied:"emptied",topEncrypted:"encrypted",topEnded:"ended",topError:"error",topFocus:"focus",topInput:"input",topKeyDown:"keydown",topKeyPress:"keypress",topKeyUp:"keyup",topLoadedData:"loadeddata",topLoadedMetadata:"loadedmetadata",topLoadStart:"loadstart",topMouseDown:"mousedown",topMouseMove:"mousemove",topMouseOut:"mouseout",topMouseOver:"mouseover",topMouseUp:"mouseup",topPaste:"paste",topPause:"pause",topPlay:"play",topPlaying:"playing",topProgress:"progress",topRateChange:"ratechange",topScroll:"scroll",topSeeked:"seeked",topSeeking:"seeking",topSelectionChange:"selectionchange",topStalled:"stalled",topSuspend:"suspend",topTextInput:"textInput",topTimeUpdate:"timeupdate",topTouchCancel:"touchcancel",topTouchEnd:"touchend",topTouchMove:"touchmove",topTouchStart:"touchstart",topVolumeChange:"volumechange",topWaiting:"waiting",topWheel:"wheel"},m="_reactListenersID"+String(Math.random()).slice(2),g=l({},s,{ReactEventListener:null,injection:{injectReactEventListener:function(e){e.setHandleTopLevel(g.handleTopLevel),g.ReactEventListener=e}},setEnabled:function(e){g.ReactEventListener&&g.ReactEventListener.setEnabled(e)},isEnabled:function(){return!(!g.ReactEventListener||!g.ReactEventListener.isEnabled())},listenTo:function(e,t){for(var n=t,i=r(n),s=a.registrationNameDependencies[e],u=o.topLevelTypes,c=0;c<s.length;c++){var l=s[c];i.hasOwnProperty(l)&&i[l]||(l===u.topWheel?p("wheel")?g.ReactEventListener.trapBubbledEvent(u.topWheel,"wheel",n):p("mousewheel")?g.ReactEventListener.trapBubbledEvent(u.topWheel,"mousewheel",n):g.ReactEventListener.trapBubbledEvent(u.topWheel,"DOMMouseScroll",n):l===u.topScroll?p("scroll",!0)?g.ReactEventListener.trapCapturedEvent(u.topScroll,"scroll",n):g.ReactEventListener.trapBubbledEvent(u.topScroll,"scroll",g.ReactEventListener.WINDOW_HANDLE):l===u.topFocus||l===u.topBlur?(p("focus",!0)?(g.ReactEventListener.trapCapturedEvent(u.topFocus,"focus",n),g.ReactEventListener.trapCapturedEvent(u.topBlur,"blur",n)):p("focusin")&&(g.ReactEventListener.trapBubbledEvent(u.topFocus,"focusin",n),g.ReactEventListener.trapBubbledEvent(u.topBlur,"focusout",n)),i[u.topBlur]=!0,i[u.topFocus]=!0):v.hasOwnProperty(l)&&g.ReactEventListener.trapBubbledEvent(l,v[l],n),i[l]=!0)}},trapBubbledEvent:function(e,t,n){return g.ReactEventListener.trapBubbledEvent(e,t,n)},trapCapturedEvent:function(e,t,n){return g.ReactEventListener.trapCapturedEvent(e,t,n)},ensureScrollValueMonitoring:function(){if(!h){var e=c.refreshScrollValues;g.ReactEventListener.monitorScrollValue(e),h=!0}},eventNameDispatchConfigs:i.eventNameDispatchConfigs,registrationNameModules:i.registrationNameModules,putListener:i.putListener,getListener:i.getListener,deleteListener:i.deleteListener,deleteAllListeners:i.deleteAllListeners});u.measureMethods(g,"ReactBrowserEventEmitter",{putListener:"putListener",deleteListener:"deleteListener"}),e.exports=g},function(e,t,n){"use strict";var r=n(232),o=r({bubbled:null,captured:null}),i=r({topAbort:null,topBlur:null,topCanPlay:null,topCanPlayThrough:null,topChange:null,topClick:null,topCompositionEnd:null,topCompositionStart:null,topCompositionUpdate:null,topContextMenu:null,topCopy:null,topCut:null,topDoubleClick:null,topDrag:null,topDragEnd:null,topDragEnter:null,topDragExit:null,topDragLeave:null,topDragOver:null,topDragStart:null,topDrop:null,topDurationChange:null,topEmptied:null,topEncrypted:null,topEnded:null,topError:null,topFocus:null,topInput:null,topKeyDown:null,topKeyPress:null,topKeyUp:null,topLoad:null,topLoadedData:null,topLoadedMetadata:null,topLoadStart:null,topMouseDown:null,topMouseMove:null,topMouseOut:null,topMouseOver:null,topMouseUp:null,topPaste:null,topPause:null,topPlay:null,topPlaying:null,topProgress:null,topRateChange:null,topReset:null,topScroll:null,topSeeked:null,topSeeking:null,topSelectionChange:null,topStalled:null,topSubmit:null,topSuspend:null,topTextInput:null,topTimeUpdate:null,topTouchCancel:null,topTouchEnd:null,topTouchMove:null,topTouchStart:null,topVolumeChange:null,topWaiting:null,topWheel:null}),a={topLevelTypes:i,PropagationPhases:o};e.exports=a},function(e,t,n){"use strict";var r=n(247),o=n(248),i=n(249),a=n(250),s=n(251),u=n(228),c=(n(240),{}),l=null,p=function(e,t){e&&(o.executeDispatchesInOrder(e,t),e.isPersistent()||e.constructor.release(e))},f=function(e){return p(e,!0)},h=function(e){return p(e,!1)},d=null,v={injection:{injectMount:o.injection.injectMount,injectInstanceHandle:function(e){d=e},getInstanceHandle:function(){return d},injectEventPluginOrder:r.injectEventPluginOrder,injectEventPluginsByName:r.injectEventPluginsByName},eventNameDispatchConfigs:r.eventNameDispatchConfigs,registrationNameModules:r.registrationNameModules,putListener:function(e,t,n){"function"!=typeof n?u(!1):void 0;var o=c[t]||(c[t]={});o[e]=n;var i=r.registrationNameModules[t];i&&i.didPutListener&&i.didPutListener(e,t,n)},getListener:function(e,t){var n=c[t];return n&&n[e]},deleteListener:function(e,t){var n=r.registrationNameModules[t];n&&n.willDeleteListener&&n.willDeleteListener(e,t);var o=c[t];o&&delete o[e]},deleteAllListeners:function(e){for(var t in c)if(c[t][e]){var n=r.registrationNameModules[t];n&&n.willDeleteListener&&n.willDeleteListener(e,t),delete c[t][e]}},extractEvents:function(e,t,n,o,i){for(var s,u=r.plugins,c=0;c<u.length;c++){var l=u[c];if(l){var p=l.extractEvents(e,t,n,o,i);p&&(s=a(s,p))}}return s},enqueueEvents:function(e){e&&(l=a(l,e))},processEventQueue:function(e){var t=l;l=null,e?s(t,f):s(t,h),l?u(!1):void 0,i.rethrowCaughtError()},__purge:function(){c={}},__getListenerBank:function(){return c}};e.exports=v},function(e,t,n){"use strict";function r(){if(s)for(var e in u){var t=u[e],n=s.indexOf(e);if(n>-1?void 0:a(!1),!c.plugins[n]){t.extractEvents?void 0:a(!1),c.plugins[n]=t;var r=t.eventTypes;for(var i in r)o(r[i],t,i)?void 0:a(!1)}}}function o(e,t,n){c.eventNameDispatchConfigs.hasOwnProperty(n)?a(!1):void 0,c.eventNameDispatchConfigs[n]=e;var r=e.phasedRegistrationNames;if(r){for(var o in r)if(r.hasOwnProperty(o)){var s=r[o];i(s,t,n)}return!0}return e.registrationName?(i(e.registrationName,t,n),!0):!1}function i(e,t,n){c.registrationNameModules[e]?a(!1):void 0,c.registrationNameModules[e]=t,c.registrationNameDependencies[e]=t.eventTypes[n].dependencies}var a=n(228),s=null,u={},c={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{},registrationNameDependencies:{},injectEventPluginOrder:function(e){s?a(!1):void 0,s=Array.prototype.slice.call(e),r()},injectEventPluginsByName:function(e){var t=!1;for(var n in e)if(e.hasOwnProperty(n)){var o=e[n];u.hasOwnProperty(n)&&u[n]===o||(u[n]?a(!1):void 0,u[n]=o,t=!0)}t&&r()},getPluginModuleForEvent:function(e){var t=e.dispatchConfig;if(t.registrationName)return c.registrationNameModules[t.registrationName]||null;for(var n in t.phasedRegistrationNames)if(t.phasedRegistrationNames.hasOwnProperty(n)){var r=c.registrationNameModules[t.phasedRegistrationNames[n]];if(r)return r}return null},_resetEventPlugins:function(){s=null;for(var e in u)u.hasOwnProperty(e)&&delete u[e];c.plugins.length=0;var t=c.eventNameDispatchConfigs;for(var n in t)t.hasOwnProperty(n)&&delete t[n];var r=c.registrationNameModules;for(var o in r)r.hasOwnProperty(o)&&delete r[o]}};e.exports=c},function(e,t,n){"use strict";function r(e){return e===m.topMouseUp||e===m.topTouchEnd||e===m.topTouchCancel}function o(e){return e===m.topMouseMove||e===m.topTouchMove}function i(e){return e===m.topMouseDown||e===m.topTouchStart}function a(e,t,n,r){var o=e.type||"unknown-event";e.currentTarget=v.Mount.getNode(r),t?h.invokeGuardedCallbackWithCatch(o,n,e,r):h.invokeGuardedCallback(o,n,e,r),e.currentTarget=null}function s(e,t){var n=e._dispatchListeners,r=e._dispatchIDs;if(Array.isArray(n))for(var o=0;o<n.length&&!e.isPropagationStopped();o++)a(e,t,n[o],r[o]);else n&&a(e,t,n,r);e._dispatchListeners=null,e._dispatchIDs=null}function u(e){var t=e._dispatchListeners,n=e._dispatchIDs;if(Array.isArray(t)){for(var r=0;r<t.length&&!e.isPropagationStopped();r++)if(t[r](e,n[r]))return n[r]}else if(t&&t(e,n))return n;return null}function c(e){var t=u(e);return e._dispatchIDs=null,e._dispatchListeners=null,t}function l(e){var t=e._dispatchListeners,n=e._dispatchIDs;Array.isArray(t)?d(!1):void 0;var r=t?t(e,n):null;return e._dispatchListeners=null,e._dispatchIDs=null,r}function p(e){return!!e._dispatchListeners}var f=n(245),h=n(249),d=n(228),v=(n(240),{Mount:null,injectMount:function(e){v.Mount=e}}),m=f.topLevelTypes,g={isEndish:r,isMoveish:o,isStartish:i,executeDirectDispatch:l,executeDispatchesInOrder:s,executeDispatchesInOrderStopAtTrue:c,hasDispatches:p,getNode:function(e){return v.Mount.getNode(e)},getID:function(e){return v.Mount.getID(e)},injection:v};e.exports=g},function(e){"use strict";function t(e,t,r,o){try{return t(r,o)}catch(i){return void(null===n&&(n=i))}}var n=null,r={invokeGuardedCallback:t,invokeGuardedCallbackWithCatch:t,rethrowCaughtError:function(){if(n){var e=n;throw n=null,e}}};e.exports=r},function(e,t,n){"use strict";function r(e,t){if(null==t?o(!1):void 0,null==e)return t;var n=Array.isArray(e),r=Array.isArray(t);return n&&r?(e.push.apply(e,t),e):n?(e.push(t),e):r?[e].concat(t):[e,t]}var o=n(228);e.exports=r},function(e){"use strict";var t=function(e,t,n){Array.isArray(e)?e.forEach(t,n):e&&t.call(n,e)};e.exports=t},function(e,t,n){"use strict";function r(e){o.enqueueEvents(e),o.processEventQueue(!1)}var o=n(246),i={handleTopLevel:function(e,t,n,i,a){var s=o.extractEvents(e,t,n,i,a);r(s)}};e.exports=i},function(e){"use strict";var t={currentScrollLeft:0,currentScrollTop:0,refreshScrollValues:function(e){t.currentScrollLeft=e.x,t.currentScrollTop=e.y}};e.exports=t},function(e){"use strict";function t(e){if(null==e)throw new TypeError("Object.assign target cannot be null or undefined");for(var t=Object(e),n=Object.prototype.hasOwnProperty,r=1;r<arguments.length;r++){var o=arguments[r];if(null!=o){var i=Object(o);for(var a in i)n.call(i,a)&&(t[a]=i[a])}}return t}e.exports=t},function(e,t,n){"use strict";function r(e,t){if(!i.canUseDOM||t&&!("addEventListener"in document))return!1;var n="on"+e,r=n in document;if(!r){var a=document.createElement("div");a.setAttribute(n,"return;"),r="function"==typeof a[n]}return!r&&o&&"wheel"===e&&(r=document.implementation.hasFeature("Events.wheel","3.0")),r}var o,i=n(224);i.canUseDOM&&(o=document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature("","")!==!0),e.exports=r},function(e){"use strict";var t={useCreateElement:!1};e.exports=t},function(e,t,n){"use strict";var r=n(220),o=n(254),i=(n(258),"function"==typeof Symbol&&Symbol["for"]&&Symbol["for"]("react.element")||60103),a={key:!0,ref:!0,__self:!0,__source:!0},s=function(e,t,n,r,o,a,s){var u={$$typeof:i,type:e,key:t,ref:n,props:s,_owner:a};return u};s.createElement=function(e,t,n){var o,i={},u=null,c=null,l=null,p=null;if(null!=t){c=void 0===t.ref?null:t.ref,u=void 0===t.key?null:""+t.key,l=void 0===t.__self?null:t.__self,p=void 0===t.__source?null:t.__source;for(o in t)t.hasOwnProperty(o)&&!a.hasOwnProperty(o)&&(i[o]=t[o])}var f=arguments.length-2;if(1===f)i.children=n;else if(f>1){for(var h=Array(f),d=0;f>d;d++)h[d]=arguments[d+2];i.children=h}if(e&&e.defaultProps){var v=e.defaultProps;for(o in v)"undefined"==typeof i[o]&&(i[o]=v[o])}return s(e,u,c,l,p,r.current,i)},s.createFactory=function(e){var t=s.createElement.bind(null,e);return t.type=e,t},s.cloneAndReplaceKey=function(e,t){ var n=s(e.type,t,e.ref,e._self,e._source,e._owner,e.props);return n},s.cloneAndReplaceProps=function(e,t){var n=s(e.type,e.key,e.ref,e._self,e._source,e._owner,t);return n},s.cloneElement=function(e,t,n){var i,u=o({},e.props),c=e.key,l=e.ref,p=e._self,f=e._source,h=e._owner;if(null!=t){void 0!==t.ref&&(l=t.ref,h=r.current),void 0!==t.key&&(c=""+t.key);for(i in t)t.hasOwnProperty(i)&&!a.hasOwnProperty(i)&&(u[i]=t[i])}var d=arguments.length-2;if(1===d)u.children=n;else if(d>1){for(var v=Array(d),m=0;d>m;m++)v[m]=arguments[m+2];u.children=v}return s(e.type,c,l,p,f,h,u)},s.isValidElement=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===i},e.exports=s},function(e){"use strict";var t=!1;e.exports=t},function(e){"use strict";function t(e){return!!o[e]}function n(e){o[e]=!0}function r(e){delete o[e]}var o={},i={isNullComponentID:t,registerNullComponentID:n,deregisterNullComponentID:r};e.exports=i},function(e,t,n){"use strict";function r(e){return h+e.toString(36)}function o(e,t){return e.charAt(t)===h||t===e.length}function i(e){return""===e||e.charAt(0)===h&&e.charAt(e.length-1)!==h}function a(e,t){return 0===t.indexOf(e)&&o(t,e.length)}function s(e){return e?e.substr(0,e.lastIndexOf(h)):""}function u(e,t){if(i(e)&&i(t)?void 0:f(!1),a(e,t)?void 0:f(!1),e===t)return e;var n,r=e.length+d;for(n=r;n<t.length&&!o(t,n);n++);return t.substr(0,n)}function c(e,t){var n=Math.min(e.length,t.length);if(0===n)return"";for(var r=0,a=0;n>=a;a++)if(o(e,a)&&o(t,a))r=a;else if(e.charAt(a)!==t.charAt(a))break;var s=e.substr(0,r);return i(s)?void 0:f(!1),s}function l(e,t,n,r,o,i){e=e||"",t=t||"",e===t?f(!1):void 0;var c=a(t,e);c||a(e,t)?void 0:f(!1);for(var l=0,p=c?s:u,h=e;;h=p(h,t)){var d;if(o&&h===e||i&&h===t||(d=n(h,c,r)),d===!1||h===t)break;l++<v?void 0:f(!1)}}var p=n(261),f=n(228),h=".",d=h.length,v=1e4,m={createReactRootID:function(){return r(p.createReactRootIndex())},createReactID:function(e,t){return e+t},getReactRootIDFromNodeID:function(e){if(e&&e.charAt(0)===h&&e.length>1){var t=e.indexOf(h,1);return t>-1?e.substr(0,t):e}return null},traverseEnterLeave:function(e,t,n,r,o){var i=c(e,t);i!==e&&l(e,i,n,r,!1,!0),i!==t&&l(i,t,n,o,!0,!1)},traverseTwoPhase:function(e,t,n){e&&(l("",e,t,n,!0,!1),l(e,"",t,n,!1,!0))},traverseTwoPhaseSkipTarget:function(e,t,n){e&&(l("",e,t,n,!0,!0),l(e,"",t,n,!0,!0))},traverseAncestors:function(e,t,n){l("",e,t,n,!0,!1)},getFirstCommonAncestorID:c,_getNextDescendantID:u,isAncestorIDOf:a,SEPARATOR:h};e.exports=m},function(e){"use strict";var t={injectCreateReactRootIndex:function(e){n.createReactRootIndex=e}},n={createReactRootIndex:null,injection:t};e.exports=n},function(e){"use strict";var t={remove:function(e){e._reactInternalInstance=void 0},get:function(e){return e._reactInternalInstance},has:function(e){return void 0!==e._reactInternalInstance},set:function(e,t){e._reactInternalInstance=t}};e.exports=t},function(e,t,n){"use strict";var r=n(264),o=/\/?>/,i={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(e){var t=r(e);return e.replace(o," "+i.CHECKSUM_ATTR_NAME+'="'+t+'"$&')},canReuseMarkup:function(e,t){var n=t.getAttribute(i.CHECKSUM_ATTR_NAME);n=n&&parseInt(n,10);var o=r(e);return o===n}};e.exports=i},function(e){"use strict";function t(e){for(var t=1,r=0,o=0,i=e.length,a=-4&i;a>o;){for(;o<Math.min(o+4096,a);o+=4)r+=(t+=e.charCodeAt(o))+(t+=e.charCodeAt(o+1))+(t+=e.charCodeAt(o+2))+(t+=e.charCodeAt(o+3));t%=n,r%=n}for(;i>o;o++)r+=t+=e.charCodeAt(o);return t%=n,r%=n,t|r<<16}var n=65521;e.exports=t},function(e,t,n){"use strict";function r(){o.attachRefs(this,this._currentElement)}var o=n(266),i={mountComponent:function(e,t,n,o){var i=e.mountComponent(t,n,o);return e._currentElement&&null!=e._currentElement.ref&&n.getReactMountReady().enqueue(r,e),i},unmountComponent:function(e){o.detachRefs(e,e._currentElement),e.unmountComponent()},receiveComponent:function(e,t,n,i){var a=e._currentElement;if(t!==a||i!==e._context){var s=o.shouldUpdateRefs(a,t);s&&o.detachRefs(e,a),e.receiveComponent(t,n,i),s&&e._currentElement&&null!=e._currentElement.ref&&n.getReactMountReady().enqueue(r,e)}},performUpdateIfNecessary:function(e,t){e.performUpdateIfNecessary(t)}};e.exports=i},function(e,t,n){"use strict";function r(e,t,n){"function"==typeof e?e(t.getPublicInstance()):i.addComponentAsRefTo(t,e,n)}function o(e,t,n){"function"==typeof e?e(null):i.removeComponentAsRefFrom(t,e,n)}var i=n(267),a={};a.attachRefs=function(e,t){if(null!==t&&t!==!1){var n=t.ref;null!=n&&r(n,e,t._owner)}},a.shouldUpdateRefs=function(e,t){var n=null===e||e===!1,r=null===t||t===!1;return n||r||t._owner!==e._owner||t.ref!==e.ref},a.detachRefs=function(e,t){if(null!==t&&t!==!1){var n=t.ref;null!=n&&o(n,e,t._owner)}},e.exports=a},function(e,t,n){"use strict";var r=n(228),o={isValidOwner:function(e){return!(!e||"function"!=typeof e.attachRef||"function"!=typeof e.detachRef)},addComponentAsRefTo:function(e,t,n){o.isValidOwner(n)?void 0:r(!1),n.attachRef(t,e)},removeComponentAsRefFrom:function(e,t,n){o.isValidOwner(n)?void 0:r(!1),n.getPublicInstance().refs[t]===e.getPublicInstance()&&n.detachRef(t)}};e.exports=o},function(e,t,n){"use strict";function r(e){s.enqueueUpdate(e)}function o(e,t){var n=a.get(e);return n?n:null}var i=(n(220),n(257)),a=n(262),s=n(269),u=n(254),c=n(228),l=(n(240),{isMounted:function(e){var t=a.get(e);return t?!!t._renderedComponent:!1},enqueueCallback:function(e,t){"function"!=typeof t?c(!1):void 0;var n=o(e);return n?(n._pendingCallbacks?n._pendingCallbacks.push(t):n._pendingCallbacks=[t],void r(n)):null},enqueueCallbackInternal:function(e,t){"function"!=typeof t?c(!1):void 0,e._pendingCallbacks?e._pendingCallbacks.push(t):e._pendingCallbacks=[t],r(e)},enqueueForceUpdate:function(e){var t=o(e,"forceUpdate");t&&(t._pendingForceUpdate=!0,r(t))},enqueueReplaceState:function(e,t){var n=o(e,"replaceState");n&&(n._pendingStateQueue=[t],n._pendingReplaceState=!0,r(n))},enqueueSetState:function(e,t){var n=o(e,"setState");if(n){var i=n._pendingStateQueue||(n._pendingStateQueue=[]);i.push(t),r(n)}},enqueueSetProps:function(e,t){var n=o(e,"setProps");n&&l.enqueueSetPropsInternal(n,t)},enqueueSetPropsInternal:function(e,t){var n=e._topLevelWrapper;n?void 0:c(!1);var o=n._pendingElement||n._currentElement,a=o.props,s=u({},a.props,t);n._pendingElement=i.cloneAndReplaceProps(o,i.cloneAndReplaceProps(a,s)),r(n)},enqueueReplaceProps:function(e,t){var n=o(e,"replaceProps");n&&l.enqueueReplacePropsInternal(n,t)},enqueueReplacePropsInternal:function(e,t){var n=e._topLevelWrapper;n?void 0:c(!1);var o=n._pendingElement||n._currentElement,a=o.props;n._pendingElement=i.cloneAndReplaceProps(o,i.cloneAndReplaceProps(a,t)),r(n)},enqueueElementInternal:function(e,t){e._pendingElement=t,r(e)}});e.exports=l},function(e,t,n){"use strict";function r(){R.ReactReconcileTransaction&&w?void 0:m(!1)}function o(){this.reinitializeTransaction(),this.dirtyComponentsLength=null,this.callbackQueue=l.getPooled(),this.reconcileTransaction=R.ReactReconcileTransaction.getPooled(!1)}function i(e,t,n,o,i,a){r(),w.batchedUpdates(e,t,n,o,i,a)}function a(e,t){return e._mountOrder-t._mountOrder}function s(e){var t=e.dirtyComponentsLength;t!==g.length?m(!1):void 0,g.sort(a);for(var n=0;t>n;n++){var r=g[n],o=r._pendingCallbacks;if(r._pendingCallbacks=null,h.performUpdateIfNecessary(r,e.reconcileTransaction),o)for(var i=0;i<o.length;i++)e.callbackQueue.enqueue(o[i],r.getPublicInstance())}}function u(e){return r(),w.isBatchingUpdates?void g.push(e):void w.batchedUpdates(u,e)}function c(e,t){w.isBatchingUpdates?void 0:m(!1),y.enqueue(e,t),b=!0}var l=n(270),p=n(271),f=n(233),h=n(265),d=n(272),v=n(254),m=n(228),g=[],y=l.getPooled(),b=!1,w=null,x={initialize:function(){this.dirtyComponentsLength=g.length},close:function(){this.dirtyComponentsLength!==g.length?(g.splice(0,this.dirtyComponentsLength),C()):g.length=0}},_={initialize:function(){this.callbackQueue.reset()},close:function(){this.callbackQueue.notifyAll()}},P=[x,_];v(o.prototype,d.Mixin,{getTransactionWrappers:function(){return P},destructor:function(){this.dirtyComponentsLength=null,l.release(this.callbackQueue),this.callbackQueue=null,R.ReactReconcileTransaction.release(this.reconcileTransaction),this.reconcileTransaction=null},perform:function(e,t,n){return d.Mixin.perform.call(this,this.reconcileTransaction.perform,this.reconcileTransaction,e,t,n)}}),p.addPoolingTo(o);var C=function(){for(;g.length||b;){if(g.length){var e=o.getPooled();e.perform(s,null,e),o.release(e)}if(b){b=!1;var t=y;y=l.getPooled(),t.notifyAll(),l.release(t)}}};C=f.measure("ReactUpdates","flushBatchedUpdates",C);var E={injectReconcileTransaction:function(e){e?void 0:m(!1),R.ReactReconcileTransaction=e},injectBatchingStrategy:function(e){e?void 0:m(!1),"function"!=typeof e.batchedUpdates?m(!1):void 0,"boolean"!=typeof e.isBatchingUpdates?m(!1):void 0,w=e}},R={ReactReconcileTransaction:null,batchedUpdates:i,enqueueUpdate:u,flushBatchedUpdates:C,injection:E,asap:c};e.exports=R},function(e,t,n){"use strict";function r(){this._callbacks=null,this._contexts=null}var o=n(271),i=n(254),a=n(228);i(r.prototype,{enqueue:function(e,t){this._callbacks=this._callbacks||[],this._contexts=this._contexts||[],this._callbacks.push(e),this._contexts.push(t)},notifyAll:function(){var e=this._callbacks,t=this._contexts;if(e){e.length!==t.length?a(!1):void 0,this._callbacks=null,this._contexts=null;for(var n=0;n<e.length;n++)e[n].call(t[n]);e.length=0,t.length=0}},reset:function(){this._callbacks=null,this._contexts=null},destructor:function(){this.reset()}}),o.addPoolingTo(r),e.exports=r},function(e,t,n){"use strict";var r=n(228),o=function(e){var t=this;if(t.instancePool.length){var n=t.instancePool.pop();return t.call(n,e),n}return new t(e)},i=function(e,t){var n=this;if(n.instancePool.length){var r=n.instancePool.pop();return n.call(r,e,t),r}return new n(e,t)},a=function(e,t,n){var r=this;if(r.instancePool.length){var o=r.instancePool.pop();return r.call(o,e,t,n),o}return new r(e,t,n)},s=function(e,t,n,r){var o=this;if(o.instancePool.length){var i=o.instancePool.pop();return o.call(i,e,t,n,r),i}return new o(e,t,n,r)},u=function(e,t,n,r,o){var i=this;if(i.instancePool.length){var a=i.instancePool.pop();return i.call(a,e,t,n,r,o),a}return new i(e,t,n,r,o)},c=function(e){var t=this;e instanceof t?void 0:r(!1),e.destructor(),t.instancePool.length<t.poolSize&&t.instancePool.push(e)},l=10,p=o,f=function(e,t){var n=e;return n.instancePool=[],n.getPooled=t||p,n.poolSize||(n.poolSize=l),n.release=c,n},h={addPoolingTo:f,oneArgumentPooler:o,twoArgumentPooler:i,threeArgumentPooler:a,fourArgumentPooler:s,fiveArgumentPooler:u};e.exports=h},function(e,t,n){"use strict";var r=n(228),o={reinitializeTransaction:function(){this.transactionWrappers=this.getTransactionWrappers(),this.wrapperInitData?this.wrapperInitData.length=0:this.wrapperInitData=[],this._isInTransaction=!1},_isInTransaction:!1,getTransactionWrappers:null,isInTransaction:function(){return!!this._isInTransaction},perform:function(e,t,n,o,i,a,s,u){this.isInTransaction()?r(!1):void 0;var c,l;try{this._isInTransaction=!0,c=!0,this.initializeAll(0),l=e.call(t,n,o,i,a,s,u),c=!1}finally{try{if(c)try{this.closeAll(0)}catch(p){}else this.closeAll(0)}finally{this._isInTransaction=!1}}return l},initializeAll:function(e){for(var t=this.transactionWrappers,n=e;n<t.length;n++){var r=t[n];try{this.wrapperInitData[n]=i.OBSERVED_ERROR,this.wrapperInitData[n]=r.initialize?r.initialize.call(this):null}finally{if(this.wrapperInitData[n]===i.OBSERVED_ERROR)try{this.initializeAll(n+1)}catch(o){}}}},closeAll:function(e){this.isInTransaction()?void 0:r(!1);for(var t=this.transactionWrappers,n=e;n<t.length;n++){var o,a=t[n],s=this.wrapperInitData[n];try{o=!0,s!==i.OBSERVED_ERROR&&a.close&&a.close.call(this,s),o=!1}finally{if(o)try{this.closeAll(n+1)}catch(u){}}}this.wrapperInitData.length=0}},i={Mixin:o,OBSERVED_ERROR:{}};e.exports=i},function(e){"use strict";var t={};e.exports=t},function(e,t,n){"use strict";function r(e,t){var n=!0;e:for(;n;){var r=e,i=t;if(n=!1,r&&i){if(r===i)return!0;if(o(r))return!1;if(o(i)){e=r,t=i.parentNode,n=!0;continue e}return r.contains?r.contains(i):r.compareDocumentPosition?!!(16&r.compareDocumentPosition(i)):!1}return!1}}var o=n(275);e.exports=r},function(e,t,n){"use strict";function r(e){return o(e)&&3==e.nodeType}var o=n(276);e.exports=r},function(e){"use strict";function t(e){return!(!e||!("function"==typeof Node?e instanceof Node:"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName))}e.exports=t},function(e,t,n){"use strict";function r(e){return"function"==typeof e&&"undefined"!=typeof e.prototype&&"function"==typeof e.prototype.mountComponent&&"function"==typeof e.prototype.receiveComponent}function o(e){var t;if(null===e||e===!1)t=new a(o);else if("object"==typeof e){var n=e;!n||"function"!=typeof n.type&&"string"!=typeof n.type?c(!1):void 0,t="string"==typeof n.type?s.createInternalComponent(n):r(n.type)?new n.type(n):new l}else"string"==typeof e||"number"==typeof e?t=s.createInstanceForText(e):c(!1);return t.construct(e),t._mountIndex=0,t._mountImage=null,t}var i=n(278),a=n(283),s=n(284),u=n(254),c=n(228),l=(n(240),function(){});u(l.prototype,i.Mixin,{_instantiateReactComponent:o}),e.exports=o},function(e,t,n){"use strict";function r(e){var t=e._currentElement._owner||null;if(t){var n=t.getName();if(n)return" Check the render method of `"+n+"`."}return""}function o(){}{var i=n(279),a=n(220),s=n(257),u=n(262),c=n(233),l=n(280),p=(n(281),n(265)),f=n(268),h=n(254),d=n(273),v=n(228),m=n(282);n(240)}o.prototype.render=function(){var e=u.get(this)._currentElement.type;return e(this.props,this.context,this.updater)};var g=1,y={construct:function(e){this._currentElement=e,this._rootNodeID=null,this._instance=null,this._pendingElement=null,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._renderedComponent=null,this._context=null,this._mountOrder=0,this._topLevelWrapper=null,this._pendingCallbacks=null},mountComponent:function(e,t,n){this._context=n,this._mountOrder=g++,this._rootNodeID=e;var r,i,a=this._processProps(this._currentElement.props),c=this._processContext(n),l=this._currentElement.type,h="prototype"in l;h&&(r=new l(a,c,f)),(!h||null===r||r===!1||s.isValidElement(r))&&(i=r,r=new o(l)),r.props=a,r.context=c,r.refs=d,r.updater=f,this._instance=r,u.set(r,this);var m=r.state;void 0===m&&(r.state=m=null),"object"!=typeof m||Array.isArray(m)?v(!1):void 0,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,r.componentWillMount&&(r.componentWillMount(),this._pendingStateQueue&&(r.state=this._processPendingState(r.props,r.context))),void 0===i&&(i=this._renderValidatedComponent()),this._renderedComponent=this._instantiateReactComponent(i);var y=p.mountComponent(this._renderedComponent,e,t,this._processChildContext(n));return r.componentDidMount&&t.getReactMountReady().enqueue(r.componentDidMount,r),y},unmountComponent:function(){var e=this._instance;e.componentWillUnmount&&e.componentWillUnmount(),p.unmountComponent(this._renderedComponent),this._renderedComponent=null,this._instance=null,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._pendingCallbacks=null,this._pendingElement=null,this._context=null,this._rootNodeID=null,this._topLevelWrapper=null,u.remove(e)},_maskContext:function(e){var t=null,n=this._currentElement.type,r=n.contextTypes;if(!r)return d;t={};for(var o in r)t[o]=e[o];return t},_processContext:function(e){var t=this._maskContext(e);return t},_processChildContext:function(e){var t=this._currentElement.type,n=this._instance,r=n.getChildContext&&n.getChildContext();if(r){"object"!=typeof t.childContextTypes?v(!1):void 0;for(var o in r)o in t.childContextTypes?void 0:v(!1);return h({},e,r)}return e},_processProps:function(e){return e},_checkPropTypes:function(e,t,n){var o=this.getName();for(var i in e)if(e.hasOwnProperty(i)){var a;try{"function"!=typeof e[i]?v(!1):void 0,a=e[i](t,i,o,n)}catch(s){a=s}if(a instanceof Error){{r(this)}n===l.prop}}},receiveComponent:function(e,t,n){var r=this._currentElement,o=this._context;this._pendingElement=null,this.updateComponent(t,r,e,o,n)},performUpdateIfNecessary:function(e){null!=this._pendingElement&&p.receiveComponent(this,this._pendingElement||this._currentElement,e,this._context),(null!==this._pendingStateQueue||this._pendingForceUpdate)&&this.updateComponent(e,this._currentElement,this._currentElement,this._context,this._context)},updateComponent:function(e,t,n,r,o){var i,a=this._instance,s=this._context===o?a.context:this._processContext(o);t===n?i=n.props:(i=this._processProps(n.props),a.componentWillReceiveProps&&a.componentWillReceiveProps(i,s));var u=this._processPendingState(i,s),c=this._pendingForceUpdate||!a.shouldComponentUpdate||a.shouldComponentUpdate(i,u,s);c?(this._pendingForceUpdate=!1,this._performComponentUpdate(n,i,u,s,e,o)):(this._currentElement=n,this._context=o,a.props=i,a.state=u,a.context=s)},_processPendingState:function(e,t){var n=this._instance,r=this._pendingStateQueue,o=this._pendingReplaceState;if(this._pendingReplaceState=!1,this._pendingStateQueue=null,!r)return n.state;if(o&&1===r.length)return r[0];for(var i=h({},o?r[0]:n.state),a=o?1:0;a<r.length;a++){var s=r[a];h(i,"function"==typeof s?s.call(n,i,e,t):s)}return i},_performComponentUpdate:function(e,t,n,r,o,i){var a,s,u,c=this._instance,l=Boolean(c.componentDidUpdate);l&&(a=c.props,s=c.state,u=c.context),c.componentWillUpdate&&c.componentWillUpdate(t,n,r),this._currentElement=e,this._context=i,c.props=t,c.state=n,c.context=r,this._updateRenderedComponent(o,i),l&&o.getReactMountReady().enqueue(c.componentDidUpdate.bind(c,a,s,u),c)},_updateRenderedComponent:function(e,t){var n=this._renderedComponent,r=n._currentElement,o=this._renderValidatedComponent();if(m(r,o))p.receiveComponent(n,o,e,this._processChildContext(t));else{var i=this._rootNodeID,a=n._rootNodeID;p.unmountComponent(n),this._renderedComponent=this._instantiateReactComponent(o);var s=p.mountComponent(this._renderedComponent,i,e,this._processChildContext(t));this._replaceNodeWithMarkupByID(a,s)}},_replaceNodeWithMarkupByID:function(e,t){i.replaceNodeWithMarkupByID(e,t)},_renderValidatedComponentWithoutOwnerOrContext:function(){var e=this._instance,t=e.render();return t},_renderValidatedComponent:function(){var e;a.current=this;try{e=this._renderValidatedComponentWithoutOwnerOrContext()}finally{a.current=null}return null===e||e===!1||s.isValidElement(e)?void 0:v(!1),e},attachRef:function(e,t){var n=this.getPublicInstance();null==n?v(!1):void 0;var r=t.getPublicInstance(),o=n.refs===d?n.refs={}:n.refs;o[e]=r},detachRef:function(e){var t=this.getPublicInstance().refs;delete t[e]},getName:function(){var e=this._currentElement.type,t=this._instance&&this._instance.constructor;return e.displayName||t&&t.displayName||e.name||t&&t.name||null},getPublicInstance:function(){var e=this._instance;return e instanceof o?null:e},_instantiateReactComponent:null};c.measureMethods(y,"ReactCompositeComponent",{mountComponent:"mountComponent",updateComponent:"updateComponent",_renderValidatedComponent:"_renderValidatedComponent"});var b={Mixin:y};e.exports=b},function(e,t,n){"use strict";var r=n(228),o=!1,i={unmountIDFromEnvironment:null,replaceNodeWithMarkupByID:null,processChildrenUpdates:null,injection:{injectEnvironment:function(e){o?r(!1):void 0,i.unmountIDFromEnvironment=e.unmountIDFromEnvironment,i.replaceNodeWithMarkupByID=e.replaceNodeWithMarkupByID,i.processChildrenUpdates=e.processChildrenUpdates,o=!0}}};e.exports=i},function(e,t,n){"use strict";var r=n(232),o=r({prop:null,context:null,childContext:null});e.exports=o},function(e){"use strict";var t={};e.exports=t},function(e){"use strict";function t(e,t){var n=null===e||e===!1,r=null===t||t===!1;if(n||r)return n===r;var o=typeof e,i=typeof t;return"string"===o||"number"===o?"string"===i||"number"===i:"object"===i&&e.type===t.type&&e.key===t.key}e.exports=t},function(e,t,n){"use strict";var r,o=n(257),i=n(259),a=n(265),s=n(254),u={injectEmptyComponent:function(e){r=o.createElement(e)}},c=function(e){this._currentElement=null,this._rootNodeID=null,this._renderedComponent=e(r)};s(c.prototype,{construct:function(){},mountComponent:function(e,t,n){return i.registerNullComponentID(e),this._rootNodeID=e,a.mountComponent(this._renderedComponent,e,t,n)},receiveComponent:function(){},unmountComponent:function(){a.unmountComponent(this._renderedComponent),i.deregisterNullComponentID(this._rootNodeID),this._rootNodeID=null,this._renderedComponent=null}}),c.injection=u,e.exports=c},function(e,t,n){"use strict";function r(e){if("function"==typeof e.type)return e.type;var t=e.type,n=p[t];return null==n&&(p[t]=n=c(t)),n}function o(e){return l?void 0:u(!1),new l(e.type,e.props)}function i(e){return new f(e)}function a(e){return e instanceof f}var s=n(254),u=n(228),c=null,l=null,p={},f=null,h={injectGenericComponentClass:function(e){l=e},injectTextComponentClass:function(e){f=e},injectComponentClasses:function(e){s(p,e)}},d={getComponentClassForElement:r,createInternalComponent:o,createInstanceForText:i,isTextComponent:a,injection:h};e.exports=d},function(e,t,n){"use strict";var r=(n(254),n(230)),o=(n(240),r);e.exports=o},function(e,t,n){"use strict";function r(){if(!E){E=!0,g.EventEmitter.injectReactEventListener(m),g.EventPluginHub.injectEventPluginOrder(s),g.EventPluginHub.injectInstanceHandle(y),g.EventPluginHub.injectMount(b),g.EventPluginHub.injectEventPluginsByName({SimpleEventPlugin:P,EnterLeaveEventPlugin:u,ChangeEventPlugin:i,SelectEventPlugin:x,BeforeInputEventPlugin:o}),g.NativeComponent.injectGenericComponentClass(d),g.NativeComponent.injectTextComponentClass(v),g.Class.injectMixin(p),g.DOMProperty.injectDOMPropertyConfig(l),g.DOMProperty.injectDOMPropertyConfig(C),g.EmptyComponent.injectEmptyComponent("noscript"),g.Updates.injectReconcileTransaction(w),g.Updates.injectBatchingStrategy(h),g.RootIndex.injectCreateReactRootIndex(c.canUseDOM?a.createReactRootIndex:_.createReactRootIndex),g.Component.injectEnvironment(f)}}var o=n(287),i=n(295),a=n(298),s=n(299),u=n(300),c=n(224),l=n(304),p=n(305),f=n(241),h=n(307),d=n(308),v=n(221),m=n(333),g=n(336),y=n(260),b=n(243),w=n(340),x=n(345),_=n(346),P=n(347),C=n(356),E=!1;e.exports={inject:r}},function(e,t,n){"use strict";function r(){var e=window.opera;return"object"==typeof e&&"function"==typeof e.version&&parseInt(e.version(),10)<=12}function o(e){return(e.ctrlKey||e.altKey||e.metaKey)&&!(e.ctrlKey&&e.altKey)}function i(e){switch(e){case O.topCompositionStart:return S.compositionStart;case O.topCompositionEnd:return S.compositionEnd;case O.topCompositionUpdate:return S.compositionUpdate}}function a(e,t){return e===O.topKeyDown&&t.keyCode===x}function s(e,t){switch(e){case O.topKeyUp:return-1!==w.indexOf(t.keyCode);case O.topKeyDown:return t.keyCode!==x;case O.topKeyPress:case O.topMouseDown:case O.topBlur:return!0;default:return!1}}function u(e){var t=e.detail;return"object"==typeof t&&"data"in t?t.data:null}function c(e,t,n,r,o){var c,l;if(_?c=i(e):j?s(e,r)&&(c=S.compositionEnd):a(e,r)&&(c=S.compositionStart),!c)return null;E&&(j||c!==S.compositionStart?c===S.compositionEnd&&j&&(l=j.getData()):j=m.getPooled(t));var p=g.getPooled(c,n,r,o);if(l)p.data=l;else{var f=u(r);null!==f&&(p.data=f)}return d.accumulateTwoPhaseDispatches(p),p}function l(e,t){switch(e){case O.topCompositionEnd:return u(t);case O.topKeyPress:var n=t.which;return n!==R?null:(N=!0,T);case O.topTextInput:var r=t.data;return r===T&&N?null:r;default:return null}}function p(e,t){if(j){if(e===O.topCompositionEnd||s(e,t)){var n=j.getData();return m.release(j),j=null,n}return null}switch(e){case O.topPaste:return null;case O.topKeyPress:return t.which&&!o(t)?String.fromCharCode(t.which):null;case O.topCompositionEnd:return E?null:t.data;default:return null}}function f(e,t,n,r,o){var i;if(i=C?l(e,r):p(e,r),!i)return null;var a=y.getPooled(S.beforeInput,n,r,o);return a.data=i,d.accumulateTwoPhaseDispatches(a),a}var h=n(245),d=n(288),v=n(224),m=n(289),g=n(291),y=n(293),b=n(294),w=[9,13,27,32],x=229,_=v.canUseDOM&&"CompositionEvent"in window,P=null;v.canUseDOM&&"documentMode"in document&&(P=document.documentMode);var C=v.canUseDOM&&"TextEvent"in window&&!P&&!r(),E=v.canUseDOM&&(!_||P&&P>8&&11>=P),R=32,T=String.fromCharCode(R),O=h.topLevelTypes,S={beforeInput:{phasedRegistrationNames:{bubbled:b({onBeforeInput:null}),captured:b({onBeforeInputCapture:null})},dependencies:[O.topCompositionEnd,O.topKeyPress,O.topTextInput,O.topPaste]},compositionEnd:{phasedRegistrationNames:{bubbled:b({onCompositionEnd:null}),captured:b({onCompositionEndCapture:null})},dependencies:[O.topBlur,O.topCompositionEnd,O.topKeyDown,O.topKeyPress,O.topKeyUp,O.topMouseDown]},compositionStart:{phasedRegistrationNames:{bubbled:b({onCompositionStart:null}),captured:b({onCompositionStartCapture:null})},dependencies:[O.topBlur,O.topCompositionStart,O.topKeyDown,O.topKeyPress,O.topKeyUp,O.topMouseDown]},compositionUpdate:{phasedRegistrationNames:{bubbled:b({onCompositionUpdate:null}),captured:b({onCompositionUpdateCapture:null})},dependencies:[O.topBlur,O.topCompositionUpdate,O.topKeyDown,O.topKeyPress,O.topKeyUp,O.topMouseDown]}},N=!1,j=null,k={eventTypes:S,extractEvents:function(e,t,n,r,o){return[c(e,t,n,r,o),f(e,t,n,r,o)]}};e.exports=k},function(e,t,n){"use strict";function r(e,t,n){var r=t.dispatchConfig.phasedRegistrationNames[n];return y(e,r)}function o(e,t,n){var o=t?g.bubbled:g.captured,i=r(e,n,o);i&&(n._dispatchListeners=v(n._dispatchListeners,i),n._dispatchIDs=v(n._dispatchIDs,e))}function i(e){e&&e.dispatchConfig.phasedRegistrationNames&&d.injection.getInstanceHandle().traverseTwoPhase(e.dispatchMarker,o,e)}function a(e){e&&e.dispatchConfig.phasedRegistrationNames&&d.injection.getInstanceHandle().traverseTwoPhaseSkipTarget(e.dispatchMarker,o,e)}function s(e,t,n){if(n&&n.dispatchConfig.registrationName){var r=n.dispatchConfig.registrationName,o=y(e,r);o&&(n._dispatchListeners=v(n._dispatchListeners,o),n._dispatchIDs=v(n._dispatchIDs,e))}}function u(e){e&&e.dispatchConfig.registrationName&&s(e.dispatchMarker,null,e)}function c(e){m(e,i)}function l(e){m(e,a)}function p(e,t,n,r){d.injection.getInstanceHandle().traverseEnterLeave(n,r,s,e,t)}function f(e){m(e,u)}var h=n(245),d=n(246),v=(n(240),n(250)),m=n(251),g=h.PropagationPhases,y=d.getListener,b={accumulateTwoPhaseDispatches:c,accumulateTwoPhaseDispatchesSkipTarget:l,accumulateDirectDispatches:f,accumulateEnterLeaveDispatches:p};e.exports=b},function(e,t,n){"use strict";function r(e){this._root=e,this._startText=this.getText(),this._fallbackText=null}var o=n(271),i=n(254),a=n(290);i(r.prototype,{destructor:function(){this._root=null,this._startText=null,this._fallbackText=null},getText:function(){return"value"in this._root?this._root.value:this._root[a()]},getData:function(){if(this._fallbackText)return this._fallbackText;var e,t,n=this._startText,r=n.length,o=this.getText(),i=o.length;for(e=0;r>e&&n[e]===o[e];e++);var a=r-e;for(t=1;a>=t&&n[r-t]===o[i-t];t++);var s=t>1?1-t:void 0;return this._fallbackText=o.slice(e,s),this._fallbackText}}),o.addPoolingTo(r),e.exports=r},function(e,t,n){"use strict";function r(){return!i&&o.canUseDOM&&(i="textContent"in document.documentElement?"textContent":"innerText"),i}var o=n(224),i=null;e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(292),i={data:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){this.dispatchConfig=e,this.dispatchMarker=t,this.nativeEvent=n,this.target=r,this.currentTarget=r;var o=this.constructor.Interface;for(var i in o)if(o.hasOwnProperty(i)){var s=o[i];this[i]=s?s(n):n[i]}var u=null!=n.defaultPrevented?n.defaultPrevented:n.returnValue===!1;this.isDefaultPrevented=u?a.thatReturnsTrue:a.thatReturnsFalse,this.isPropagationStopped=a.thatReturnsFalse}var o=n(271),i=n(254),a=n(230),s=(n(240),{type:null,currentTarget:a.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null});i(r.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e&&(e.preventDefault?e.preventDefault():e.returnValue=!1,this.isDefaultPrevented=a.thatReturnsTrue)},stopPropagation:function(){var e=this.nativeEvent;e&&(e.stopPropagation?e.stopPropagation():e.cancelBubble=!0,this.isPropagationStopped=a.thatReturnsTrue)},persist:function(){this.isPersistent=a.thatReturnsTrue},isPersistent:a.thatReturnsFalse,destructor:function(){var e=this.constructor.Interface;for(var t in e)this[t]=null;this.dispatchConfig=null,this.dispatchMarker=null,this.nativeEvent=null}}),r.Interface=s,r.augmentClass=function(e,t){var n=this,r=Object.create(n.prototype);i(r,e.prototype),e.prototype=r,e.prototype.constructor=e,e.Interface=i({},n.Interface,t),e.augmentClass=n.augmentClass,o.addPoolingTo(e,o.fourArgumentPooler)},o.addPoolingTo(r,o.fourArgumentPooler),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(292),i={data:null};o.augmentClass(r,i),e.exports=r},function(e){"use strict";var t=function(e){var t;for(t in e)if(e.hasOwnProperty(t))return t;return null};e.exports=t},function(e,t,n){"use strict";function r(e){var t=e.nodeName&&e.nodeName.toLowerCase();return"select"===t||"input"===t&&"file"===e.type}function o(e){var t=P.getPooled(S.change,j,e,C(e));w.accumulateTwoPhaseDispatches(t),_.batchedUpdates(i,t)}function i(e){b.enqueueEvents(e),b.processEventQueue(!1)}function a(e,t){N=e,j=t,N.attachEvent("onchange",o)}function s(){N&&(N.detachEvent("onchange",o),N=null,j=null)}function u(e,t,n){return e===O.topChange?n:void 0}function c(e,t,n){e===O.topFocus?(s(),a(t,n)):e===O.topBlur&&s()}function l(e,t){N=e,j=t,k=e.value,I=Object.getOwnPropertyDescriptor(e.constructor.prototype,"value"),Object.defineProperty(N,"value",M),N.attachEvent("onpropertychange",f)}function p(){N&&(delete N.value,N.detachEvent("onpropertychange",f),N=null,j=null,k=null,I=null)}function f(e){if("value"===e.propertyName){var t=e.srcElement.value;t!==k&&(k=t,o(e))}}function h(e,t,n){return e===O.topInput?n:void 0}function d(e,t,n){e===O.topFocus?(p(),l(t,n)):e===O.topBlur&&p()}function v(e){return e!==O.topSelectionChange&&e!==O.topKeyUp&&e!==O.topKeyDown||!N||N.value===k?void 0:(k=N.value,j)}function m(e){return e.nodeName&&"input"===e.nodeName.toLowerCase()&&("checkbox"===e.type||"radio"===e.type)}function g(e,t,n){return e===O.topClick?n:void 0}var y=n(245),b=n(246),w=n(288),x=n(224),_=n(269),P=n(292),C=n(296),E=n(255),R=n(297),T=n(294),O=y.topLevelTypes,S={change:{phasedRegistrationNames:{bubbled:T({onChange:null}),captured:T({onChangeCapture:null})},dependencies:[O.topBlur,O.topChange,O.topClick,O.topFocus,O.topInput,O.topKeyDown,O.topKeyUp,O.topSelectionChange]}},N=null,j=null,k=null,I=null,D=!1;x.canUseDOM&&(D=E("change")&&(!("documentMode"in document)||document.documentMode>8));var A=!1;x.canUseDOM&&(A=E("input")&&(!("documentMode"in document)||document.documentMode>9));var M={get:function(){return I.get.call(this)},set:function(e){k=""+e,I.set.call(this,e)}},F={eventTypes:S,extractEvents:function(e,t,n,o,i){var a,s;if(r(t)?D?a=u:s=c:R(t)?A?a=h:(a=v,s=d):m(t)&&(a=g),a){var l=a(e,t,n);if(l){var p=P.getPooled(S.change,l,o,i);return p.type="change",w.accumulateTwoPhaseDispatches(p),p}}s&&s(e,t,n)}};e.exports=F},function(e){"use strict";function t(e){var t=e.target||e.srcElement||window;return 3===t.nodeType?t.parentNode:t}e.exports=t},function(e){"use strict";function t(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&n[e.type]||"textarea"===t)}var n={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};e.exports=t},function(e){"use strict";var t=0,n={createReactRootIndex:function(){return t++}};e.exports=n},function(e,t,n){"use strict";var r=n(294),o=[r({ResponderEventPlugin:null}),r({SimpleEventPlugin:null}),r({ TapEventPlugin:null}),r({EnterLeaveEventPlugin:null}),r({ChangeEventPlugin:null}),r({SelectEventPlugin:null}),r({BeforeInputEventPlugin:null})];e.exports=o},function(e,t,n){"use strict";var r=n(245),o=n(288),i=n(301),a=n(243),s=n(294),u=r.topLevelTypes,c=a.getFirstReactDOM,l={mouseEnter:{registrationName:s({onMouseEnter:null}),dependencies:[u.topMouseOut,u.topMouseOver]},mouseLeave:{registrationName:s({onMouseLeave:null}),dependencies:[u.topMouseOut,u.topMouseOver]}},p=[null,null],f={eventTypes:l,extractEvents:function(e,t,n,r,s){if(e===u.topMouseOver&&(r.relatedTarget||r.fromElement))return null;if(e!==u.topMouseOut&&e!==u.topMouseOver)return null;var f;if(t.window===t)f=t;else{var h=t.ownerDocument;f=h?h.defaultView||h.parentWindow:window}var d,v,m="",g="";if(e===u.topMouseOut?(d=t,m=n,v=c(r.relatedTarget||r.toElement),v?g=a.getID(v):v=f,v=v||f):(d=f,v=t,g=n),d===v)return null;var y=i.getPooled(l.mouseLeave,m,r,s);y.type="mouseleave",y.target=d,y.relatedTarget=v;var b=i.getPooled(l.mouseEnter,g,r,s);return b.type="mouseenter",b.target=v,b.relatedTarget=d,o.accumulateEnterLeaveDispatches(y,b,m,g),p[0]=y,p[1]=b,p}};e.exports=f},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(302),i=n(253),a=n(303),s={screenX:null,screenY:null,clientX:null,clientY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:a,button:function(e){var t=e.button;return"which"in e?t:2===t?2:4===t?1:0},buttons:null,relatedTarget:function(e){return e.relatedTarget||(e.fromElement===e.srcElement?e.toElement:e.fromElement)},pageX:function(e){return"pageX"in e?e.pageX:e.clientX+i.currentScrollLeft},pageY:function(e){return"pageY"in e?e.pageY:e.clientY+i.currentScrollTop}};o.augmentClass(r,s),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(292),i=n(296),a={view:function(e){if(e.view)return e.view;var t=i(e);if(null!=t&&t.window===t)return t;var n=t.ownerDocument;return n?n.defaultView||n.parentWindow:window},detail:function(e){return e.detail||0}};o.augmentClass(r,a),e.exports=r},function(e){"use strict";function t(e){var t=this,n=t.nativeEvent;if(n.getModifierState)return n.getModifierState(e);var o=r[e];return o?!!n[o]:!1}function n(){return t}var r={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};e.exports=n},function(e,t,n){"use strict";var r,o=n(238),i=n(224),a=o.injection.MUST_USE_ATTRIBUTE,s=o.injection.MUST_USE_PROPERTY,u=o.injection.HAS_BOOLEAN_VALUE,c=o.injection.HAS_SIDE_EFFECTS,l=o.injection.HAS_NUMERIC_VALUE,p=o.injection.HAS_POSITIVE_NUMERIC_VALUE,f=o.injection.HAS_OVERLOADED_BOOLEAN_VALUE;if(i.canUseDOM){var h=document.implementation;r=h&&h.hasFeature&&h.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1")}var d={isCustomAttribute:RegExp.prototype.test.bind(/^(data|aria)-[a-z_][a-z\d_.\-]*$/),Properties:{accept:null,acceptCharset:null,accessKey:null,action:null,allowFullScreen:a|u,allowTransparency:a,alt:null,async:u,autoComplete:null,autoPlay:u,capture:a|u,cellPadding:null,cellSpacing:null,charSet:a,challenge:a,checked:s|u,classID:a,className:r?a:s,cols:a|p,colSpan:null,content:null,contentEditable:null,contextMenu:a,controls:s|u,coords:null,crossOrigin:null,data:null,dateTime:a,"default":u,defer:u,dir:null,disabled:a|u,download:f,draggable:null,encType:null,form:a,formAction:a,formEncType:a,formMethod:a,formNoValidate:u,formTarget:a,frameBorder:a,headers:null,height:a,hidden:a|u,high:null,href:null,hrefLang:null,htmlFor:null,httpEquiv:null,icon:null,id:s,inputMode:a,is:a,keyParams:a,keyType:a,kind:null,label:null,lang:null,list:a,loop:s|u,low:null,manifest:a,marginHeight:null,marginWidth:null,max:null,maxLength:a,media:a,mediaGroup:null,method:null,min:null,minLength:a,multiple:s|u,muted:s|u,name:null,noValidate:u,open:u,optimum:null,pattern:null,placeholder:null,poster:null,preload:null,radioGroup:null,readOnly:s|u,rel:null,required:u,role:a,rows:a|p,rowSpan:null,sandbox:null,scope:null,scoped:u,scrolling:null,seamless:a|u,selected:s|u,shape:null,size:a|p,sizes:a,span:p,spellCheck:null,src:null,srcDoc:s,srcLang:null,srcSet:a,start:l,step:null,style:null,summary:null,tabIndex:null,target:null,title:null,type:null,useMap:null,value:s|c,width:a,wmode:a,wrap:null,about:a,datatype:a,inlist:a,prefix:a,property:a,resource:a,"typeof":a,vocab:a,autoCapitalize:null,autoCorrect:null,autoSave:null,color:null,itemProp:a,itemScope:a|u,itemType:a,itemID:a,itemRef:a,results:null,security:a,unselectable:a},DOMAttributeNames:{acceptCharset:"accept-charset",className:"class",htmlFor:"for",httpEquiv:"http-equiv"},DOMPropertyNames:{autoCapitalize:"autocapitalize",autoComplete:"autocomplete",autoCorrect:"autocorrect",autoFocus:"autofocus",autoPlay:"autoplay",autoSave:"autosave",encType:"encoding",hrefLang:"hreflang",radioGroup:"radiogroup",spellCheck:"spellcheck",srcDoc:"srcdoc",srcSet:"srcset"}};e.exports=d},function(e,t,n){"use strict";var r=(n(262),n(306)),o=(n(240),"_getDOMNodeDidWarn"),i={getDOMNode:function(){return this.constructor[o]=!0,r(this)}};e.exports=i},function(e,t,n){"use strict";function r(e){return null==e?null:1===e.nodeType?e:o.has(e)?i.getNodeFromInstance(e):(null!=e.render&&"function"==typeof e.render?a(!1):void 0,void a(!1))}{var o=(n(220),n(262)),i=n(243),a=n(228);n(240)}e.exports=r},function(e,t,n){"use strict";function r(){this.reinitializeTransaction()}var o=n(269),i=n(272),a=n(254),s=n(230),u={initialize:s,close:function(){f.isBatchingUpdates=!1}},c={initialize:s,close:o.flushBatchedUpdates.bind(o)},l=[c,u];a(r.prototype,i.Mixin,{getTransactionWrappers:function(){return l}});var p=new r,f={isBatchingUpdates:!1,batchedUpdates:function(e,t,n,r,o,i){var a=f.isBatchingUpdates;f.isBatchingUpdates=!0,a?e(t,n,r,o,i):p.perform(e,null,t,n,r,o,i)}};e.exports=f},function(e,t,n){"use strict";function r(){return this}function o(){var e=this._reactInternalComponent;return!!e}function i(){}function a(e,t){var n=this._reactInternalComponent;n&&(k.enqueueSetPropsInternal(n,e),t&&k.enqueueCallbackInternal(n,t))}function s(e,t){var n=this._reactInternalComponent;n&&(k.enqueueReplacePropsInternal(n,e),t&&k.enqueueCallbackInternal(n,t))}function u(e,t){t&&(null!=t.dangerouslySetInnerHTML&&(null!=t.children?M(!1):void 0,"object"==typeof t.dangerouslySetInnerHTML&&K in t.dangerouslySetInnerHTML?void 0:M(!1)),null!=t.style&&"object"!=typeof t.style?M(!1):void 0)}function c(e,t,n,r){var o=S.findReactContainerForID(e);if(o){var i=o.nodeType===Q?o.ownerDocument:o;q(t,i)}r.getReactMountReady().enqueue(l,{id:e,registrationName:t,listener:n})}function l(){var e=this;_.putListener(e.id,e.registrationName,e.listener)}function p(){var e=this;e._rootNodeID?void 0:M(!1);var t=S.getNode(e._rootNodeID);switch(t?void 0:M(!1),e._tag){case"iframe":e._wrapperState.listeners=[_.trapBubbledEvent(x.topLevelTypes.topLoad,"load",t)];break;case"video":case"audio":e._wrapperState.listeners=[];for(var n in Y)Y.hasOwnProperty(n)&&e._wrapperState.listeners.push(_.trapBubbledEvent(x.topLevelTypes[n],Y[n],t));break;case"img":e._wrapperState.listeners=[_.trapBubbledEvent(x.topLevelTypes.topError,"error",t),_.trapBubbledEvent(x.topLevelTypes.topLoad,"load",t)];break;case"form":e._wrapperState.listeners=[_.trapBubbledEvent(x.topLevelTypes.topReset,"reset",t),_.trapBubbledEvent(x.topLevelTypes.topSubmit,"submit",t)]}}function f(){E.mountReadyWrapper(this)}function h(){T.postUpdateWrapper(this)}function d(e){X.call(J,e)||($.test(e)?void 0:M(!1),J[e]=!0)}function v(e,t){return e.indexOf("-")>=0||null!=t.is}function m(e){d(e),this._tag=e.toLowerCase(),this._renderedChildren=null,this._previousStyle=null,this._previousStyleCopy=null,this._rootNodeID=null,this._wrapperState=null,this._topLevelWrapper=null,this._nodeWithLegacyProperties=null}var g=n(309),y=n(311),b=n(238),w=n(237),x=n(245),_=n(244),P=n(241),C=n(319),E=n(320),R=n(324),T=n(327),O=n(328),S=n(243),N=n(329),j=n(233),k=n(268),I=n(254),D=n(258),A=n(236),M=n(228),F=(n(255),n(294)),U=n(234),L=n(235),B=(n(332),n(285),n(240),_.deleteListener),q=_.listenTo,H=_.registrationNameModules,V={string:!0,number:!0},W=F({style:null}),K=F({__html:null}),Q=1,Y={topAbort:"abort",topCanPlay:"canplay",topCanPlayThrough:"canplaythrough",topDurationChange:"durationchange",topEmptied:"emptied",topEncrypted:"encrypted",topEnded:"ended",topError:"error",topLoadedData:"loadeddata",topLoadedMetadata:"loadedmetadata",topLoadStart:"loadstart",topPause:"pause",topPlay:"play",topPlaying:"playing",topProgress:"progress",topRateChange:"ratechange",topSeeked:"seeked",topSeeking:"seeking",topStalled:"stalled",topSuspend:"suspend",topTimeUpdate:"timeupdate",topVolumeChange:"volumechange",topWaiting:"waiting"},z={area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0},G={listing:!0,pre:!0,textarea:!0},$=(I({menuitem:!0},z),/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/),J={},X={}.hasOwnProperty;m.displayName="ReactDOMComponent",m.Mixin={construct:function(e){this._currentElement=e},mountComponent:function(e,t,n){this._rootNodeID=e;var r=this._currentElement.props;switch(this._tag){case"iframe":case"img":case"form":case"video":case"audio":this._wrapperState={listeners:null},t.getReactMountReady().enqueue(p,this);break;case"button":r=C.getNativeProps(this,r,n);break;case"input":E.mountWrapper(this,r,n),r=E.getNativeProps(this,r,n);break;case"option":R.mountWrapper(this,r,n),r=R.getNativeProps(this,r,n);break;case"select":T.mountWrapper(this,r,n),r=T.getNativeProps(this,r,n),n=T.processChildContext(this,r,n);break;case"textarea":O.mountWrapper(this,r,n),r=O.getNativeProps(this,r,n)}u(this,r);var o;if(t.useCreateElement){var i=n[S.ownerDocumentContextKey],a=i.createElement(this._currentElement.type);w.setAttributeForID(a,this._rootNodeID),S.getID(a),this._updateDOMProperties({},r,t,a),this._createInitialChildren(t,r,n,a),o=a}else{var s=this._createOpenTagMarkupAndPutListeners(t,r),c=this._createContentMarkup(t,r,n);o=!c&&z[this._tag]?s+"/>":s+">"+c+"</"+this._currentElement.type+">"}switch(this._tag){case"input":t.getReactMountReady().enqueue(f,this);case"button":case"select":case"textarea":r.autoFocus&&t.getReactMountReady().enqueue(g.focusDOMComponent,this)}return o},_createOpenTagMarkupAndPutListeners:function(e,t){var n="<"+this._currentElement.type;for(var r in t)if(t.hasOwnProperty(r)){var o=t[r];if(null!=o)if(H.hasOwnProperty(r))o&&c(this._rootNodeID,r,o,e);else{r===W&&(o&&(o=this._previousStyleCopy=I({},t.style)),o=y.createMarkupForStyles(o));var i=null;i=null!=this._tag&&v(this._tag,t)?w.createMarkupForCustomAttribute(r,o):w.createMarkupForProperty(r,o),i&&(n+=" "+i)}}if(e.renderToStaticMarkup)return n;var a=w.createMarkupForID(this._rootNodeID);return n+" "+a},_createContentMarkup:function(e,t,n){var r="",o=t.dangerouslySetInnerHTML;if(null!=o)null!=o.__html&&(r=o.__html);else{var i=V[typeof t.children]?t.children:null,a=null!=i?null:t.children;if(null!=i)r=A(i);else if(null!=a){var s=this.mountChildren(a,e,n);r=s.join("")}}return G[this._tag]&&"\n"===r.charAt(0)?"\n"+r:r},_createInitialChildren:function(e,t,n,r){var o=t.dangerouslySetInnerHTML;if(null!=o)null!=o.__html&&U(r,o.__html);else{var i=V[typeof t.children]?t.children:null,a=null!=i?null:t.children;if(null!=i)L(r,i);else if(null!=a)for(var s=this.mountChildren(a,e,n),u=0;u<s.length;u++)r.appendChild(s[u])}},receiveComponent:function(e,t,n){var r=this._currentElement;this._currentElement=e,this.updateComponent(t,r,e,n)},updateComponent:function(e,t,n,r){var o=t.props,i=this._currentElement.props;switch(this._tag){case"button":o=C.getNativeProps(this,o),i=C.getNativeProps(this,i);break;case"input":E.updateWrapper(this),o=E.getNativeProps(this,o),i=E.getNativeProps(this,i);break;case"option":o=R.getNativeProps(this,o),i=R.getNativeProps(this,i);break;case"select":o=T.getNativeProps(this,o),i=T.getNativeProps(this,i);break;case"textarea":O.updateWrapper(this),o=O.getNativeProps(this,o),i=O.getNativeProps(this,i)}u(this,i),this._updateDOMProperties(o,i,e,null),this._updateDOMChildren(o,i,e,r),!D&&this._nodeWithLegacyProperties&&(this._nodeWithLegacyProperties.props=i),"select"===this._tag&&e.getReactMountReady().enqueue(h,this)},_updateDOMProperties:function(e,t,n,r){var o,i,a;for(o in e)if(!t.hasOwnProperty(o)&&e.hasOwnProperty(o))if(o===W){var s=this._previousStyleCopy;for(i in s)s.hasOwnProperty(i)&&(a=a||{},a[i]="");this._previousStyleCopy=null}else H.hasOwnProperty(o)?e[o]&&B(this._rootNodeID,o):(b.properties[o]||b.isCustomAttribute(o))&&(r||(r=S.getNode(this._rootNodeID)),w.deleteValueForProperty(r,o));for(o in t){var u=t[o],l=o===W?this._previousStyleCopy:e[o];if(t.hasOwnProperty(o)&&u!==l)if(o===W)if(u?u=this._previousStyleCopy=I({},u):this._previousStyleCopy=null,l){for(i in l)!l.hasOwnProperty(i)||u&&u.hasOwnProperty(i)||(a=a||{},a[i]="");for(i in u)u.hasOwnProperty(i)&&l[i]!==u[i]&&(a=a||{},a[i]=u[i])}else a=u;else H.hasOwnProperty(o)?u?c(this._rootNodeID,o,u,n):l&&B(this._rootNodeID,o):v(this._tag,t)?(r||(r=S.getNode(this._rootNodeID)),w.setValueForAttribute(r,o,u)):(b.properties[o]||b.isCustomAttribute(o))&&(r||(r=S.getNode(this._rootNodeID)),null!=u?w.setValueForProperty(r,o,u):w.deleteValueForProperty(r,o))}a&&(r||(r=S.getNode(this._rootNodeID)),y.setValueForStyles(r,a))},_updateDOMChildren:function(e,t,n,r){var o=V[typeof e.children]?e.children:null,i=V[typeof t.children]?t.children:null,a=e.dangerouslySetInnerHTML&&e.dangerouslySetInnerHTML.__html,s=t.dangerouslySetInnerHTML&&t.dangerouslySetInnerHTML.__html,u=null!=o?null:e.children,c=null!=i?null:t.children,l=null!=o||null!=a,p=null!=i||null!=s;null!=u&&null==c?this.updateChildren(null,n,r):l&&!p&&this.updateTextContent(""),null!=i?o!==i&&this.updateTextContent(""+i):null!=s?a!==s&&this.updateMarkup(""+s):null!=c&&this.updateChildren(c,n,r)},unmountComponent:function(){switch(this._tag){case"iframe":case"img":case"form":case"video":case"audio":var e=this._wrapperState.listeners;if(e)for(var t=0;t<e.length;t++)e[t].remove();break;case"input":E.unmountWrapper(this);break;case"html":case"head":case"body":M(!1)}if(this.unmountChildren(),_.deleteAllListeners(this._rootNodeID),P.unmountIDFromEnvironment(this._rootNodeID),this._rootNodeID=null,this._wrapperState=null,this._nodeWithLegacyProperties){var n=this._nodeWithLegacyProperties;n._reactInternalComponent=null,this._nodeWithLegacyProperties=null}},getPublicInstance:function(){if(!this._nodeWithLegacyProperties){var e=S.getNode(this._rootNodeID);e._reactInternalComponent=this,e.getDOMNode=r,e.isMounted=o,e.setState=i,e.replaceState=i,e.forceUpdate=i,e.setProps=a,e.replaceProps=s,e.props=this._currentElement.props,this._nodeWithLegacyProperties=e}return this._nodeWithLegacyProperties}},j.measureMethods(m,"ReactDOMComponent",{mountComponent:"mountComponent",updateComponent:"updateComponent"}),I(m.prototype,m.Mixin,N.Mixin),e.exports=m},function(e,t,n){"use strict";var r=n(243),o=n(306),i=n(310),a={componentDidMount:function(){this.props.autoFocus&&i(o(this))}},s={Mixin:a,focusDOMComponent:function(){i(r.getNode(this._rootNodeID))}};e.exports=s},function(e){"use strict";function t(e){try{e.focus()}catch(t){}}e.exports=t},function(e,t,n){"use strict";var r=n(312),o=n(224),i=n(233),a=(n(313),n(315)),s=n(316),u=n(318),c=(n(240),u(function(e){return s(e)})),l=!1,p="cssFloat";if(o.canUseDOM){var f=document.createElement("div").style;try{f.font=""}catch(h){l=!0}void 0===document.documentElement.style.cssFloat&&(p="styleFloat")}var d={createMarkupForStyles:function(e){var t="";for(var n in e)if(e.hasOwnProperty(n)){var r=e[n];null!=r&&(t+=c(n)+":",t+=a(n,r)+";")}return t||null},setValueForStyles:function(e,t){var n=e.style;for(var o in t)if(t.hasOwnProperty(o)){var i=a(o,t[o]);if("float"===o&&(o=p),i)n[o]=i;else{var s=l&&r.shorthandPropertyExpansions[o];if(s)for(var u in s)n[u]="";else n[o]=""}}}};i.measureMethods(d,"CSSPropertyOperations",{setValueForStyles:"setValueForStyles"}),e.exports=d},function(e){"use strict";function t(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}var n={animationIterationCount:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,stopOpacity:!0,strokeDashoffset:!0,strokeOpacity:!0,strokeWidth:!0},r=["Webkit","ms","Moz","O"];Object.keys(n).forEach(function(e){r.forEach(function(r){n[t(r,e)]=n[e]})});var o={background:{backgroundAttachment:!0,backgroundColor:!0,backgroundImage:!0,backgroundPositionX:!0,backgroundPositionY:!0,backgroundRepeat:!0},backgroundPosition:{backgroundPositionX:!0,backgroundPositionY:!0},border:{borderWidth:!0,borderStyle:!0,borderColor:!0},borderBottom:{borderBottomWidth:!0,borderBottomStyle:!0,borderBottomColor:!0},borderLeft:{borderLeftWidth:!0,borderLeftStyle:!0,borderLeftColor:!0},borderRight:{borderRightWidth:!0,borderRightStyle:!0,borderRightColor:!0},borderTop:{borderTopWidth:!0,borderTopStyle:!0,borderTopColor:!0},font:{fontStyle:!0,fontVariant:!0,fontWeight:!0,fontSize:!0,lineHeight:!0,fontFamily:!0},outline:{outlineWidth:!0,outlineStyle:!0,outlineColor:!0}},i={isUnitlessNumber:n,shorthandPropertyExpansions:o};e.exports=i},function(e,t,n){"use strict";function r(e){return o(e.replace(i,"ms-"))}var o=n(314),i=/^-ms-/;e.exports=r},function(e){"use strict";function t(e){return e.replace(n,function(e,t){return t.toUpperCase()})}var n=/-(.)/g;e.exports=t},function(e,t,n){"use strict";function r(e,t){var n=null==t||"boolean"==typeof t||""===t;if(n)return"";var r=isNaN(t);return r||0===t||i.hasOwnProperty(e)&&i[e]?""+t:("string"==typeof t&&(t=t.trim()),t+"px")}var o=n(312),i=o.isUnitlessNumber;e.exports=r},function(e,t,n){"use strict";function r(e){return o(e).replace(i,"-ms-")}var o=n(317),i=/^ms-/;e.exports=r},function(e){"use strict";function t(e){return e.replace(n,"-$1").toLowerCase()}var n=/([A-Z])/g;e.exports=t},function(e){"use strict";function t(e){var t={};return function(n){return t.hasOwnProperty(n)||(t[n]=e.call(this,n)),t[n]}}e.exports=t},function(e){"use strict";var t={onClick:!0,onDoubleClick:!0,onMouseDown:!0,onMouseMove:!0,onMouseUp:!0,onClickCapture:!0,onDoubleClickCapture:!0,onMouseDownCapture:!0,onMouseMoveCapture:!0,onMouseUpCapture:!0},n={getNativeProps:function(e,n){if(!n.disabled)return n;var r={};for(var o in n)n.hasOwnProperty(o)&&!t[o]&&(r[o]=n[o]);return r}};e.exports=n},function(e,t,n){"use strict";function r(){this._rootNodeID&&f.updateWrapper(this)}function o(e){var t=this._currentElement.props,n=a.executeOnChange(t,e);u.asap(r,this);var o=t.name;if("radio"===t.type&&null!=o){for(var i=s.getNode(this._rootNodeID),c=i;c.parentNode;)c=c.parentNode;for(var f=c.querySelectorAll("input[name="+JSON.stringify(""+o)+'][type="radio"]'),h=0;h<f.length;h++){var d=f[h];if(d!==i&&d.form===i.form){var v=s.getID(d);v?void 0:l(!1);var m=p[v];m?void 0:l(!1),u.asap(r,m)}}}return n}var i=n(242),a=n(321),s=n(243),u=n(269),c=n(254),l=n(228),p={},f={getNativeProps:function(e,t){var n=a.getValue(t),r=a.getChecked(t),o=c({},t,{defaultChecked:void 0,defaultValue:void 0,value:null!=n?n:e._wrapperState.initialValue,checked:null!=r?r:e._wrapperState.initialChecked,onChange:e._wrapperState.onChange});return o},mountWrapper:function(e,t){var n=t.defaultValue;e._wrapperState={initialChecked:t.defaultChecked||!1,initialValue:null!=n?n:null,onChange:o.bind(e)}},mountReadyWrapper:function(e){p[e._rootNodeID]=e},unmountWrapper:function(e){delete p[e._rootNodeID]},updateWrapper:function(e){var t=e._currentElement.props,n=t.checked;null!=n&&i.updatePropertyByID(e._rootNodeID,"checked",n||!1);var r=a.getValue(t);null!=r&&i.updatePropertyByID(e._rootNodeID,"value",""+r)}};e.exports=f},function(e,t,n){"use strict";function r(e){null!=e.checkedLink&&null!=e.valueLink?c(!1):void 0}function o(e){r(e),null!=e.value||null!=e.onChange?c(!1):void 0}function i(e){r(e),null!=e.checked||null!=e.onChange?c(!1):void 0}function a(e){if(e){var t=e.getName();if(t)return" Check the render method of `"+t+"`."}return""}var s=n(322),u=n(280),c=n(228),l=(n(240),{button:!0,checkbox:!0,image:!0,hidden:!0,radio:!0,reset:!0,submit:!0}),p={value:function(e,t){return!e[t]||l[e.type]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.")},checked:function(e,t){return!e[t]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.")},onChange:s.func},f={},h={checkPropTypes:function(e,t,n){for(var r in p){if(p.hasOwnProperty(r))var o=p[r](t,r,e,u.prop);if(o instanceof Error&&!(o.message in f)){f[o.message]=!0;{a(n)}}}},getValue:function(e){return e.valueLink?(o(e),e.valueLink.value):e.value},getChecked:function(e){return e.checkedLink?(i(e),e.checkedLink.value):e.checked},executeOnChange:function(e,t){return e.valueLink?(o(e),e.valueLink.requestChange(t.target.value)):e.checkedLink?(i(e),e.checkedLink.requestChange(t.target.checked)):e.onChange?e.onChange.call(void 0,t):void 0}};e.exports=h},function(e,t,n){"use strict";function r(e){function t(t,n,r,o,i,a){if(o=o||_,a=a||r,null==n[r]){var s=b[i];return t?new Error("Required "+s+" `"+a+"` was not specified in "+("`"+o+"`.")):null}return e(n,r,o,i,a)}var n=t.bind(null,!1);return n.isRequired=t.bind(null,!0),n}function o(e){function t(t,n,r,o,i){var a=t[n],s=v(a);if(s!==e){var u=b[o],c=m(a);return new Error("Invalid "+u+" `"+i+"` of type "+("`"+c+"` supplied to `"+r+"`, expected ")+("`"+e+"`."))}return null}return r(t)}function i(){return r(w.thatReturns(null))}function a(e){function t(t,n,r,o,i){var a=t[n];if(!Array.isArray(a)){var s=b[o],u=v(a);return new Error("Invalid "+s+" `"+i+"` of type "+("`"+u+"` supplied to `"+r+"`, expected an array."))}for(var c=0;c<a.length;c++){var l=e(a,c,r,o,i+"["+c+"]");if(l instanceof Error)return l}return null}return r(t)}function s(){function e(e,t,n,r,o){if(!y.isValidElement(e[t])){var i=b[r];return new Error("Invalid "+i+" `"+o+"` supplied to "+("`"+n+"`, expected a single ReactElement."))}return null}return r(e)}function u(e){function t(t,n,r,o,i){if(!(t[n]instanceof e)){var a=b[o],s=e.name||_,u=g(t[n]);return new Error("Invalid "+a+" `"+i+"` of type "+("`"+u+"` supplied to `"+r+"`, expected ")+("instance of `"+s+"`."))}return null}return r(t)}function c(e){function t(t,n,r,o,i){for(var a=t[n],s=0;s<e.length;s++)if(a===e[s])return null;var u=b[o],c=JSON.stringify(e);return new Error("Invalid "+u+" `"+i+"` of value `"+a+"` "+("supplied to `"+r+"`, expected one of "+c+"."))}return r(Array.isArray(e)?t:function(){return new Error("Invalid argument supplied to oneOf, expected an instance of array.")})}function l(e){function t(t,n,r,o,i){var a=t[n],s=v(a);if("object"!==s){var u=b[o];return new Error("Invalid "+u+" `"+i+"` of type "+("`"+s+"` supplied to `"+r+"`, expected an object."))}for(var c in a)if(a.hasOwnProperty(c)){var l=e(a,c,r,o,i+"."+c);if(l instanceof Error)return l}return null}return r(t)}function p(e){function t(t,n,r,o,i){for(var a=0;a<e.length;a++){var s=e[a];if(null==s(t,n,r,o,i))return null}var u=b[o];return new Error("Invalid "+u+" `"+i+"` supplied to "+("`"+r+"`."))}return r(Array.isArray(e)?t:function(){return new Error("Invalid argument supplied to oneOfType, expected an instance of array.")})}function f(){function e(e,t,n,r,o){if(!d(e[t])){var i=b[r];return new Error("Invalid "+i+" `"+o+"` supplied to "+("`"+n+"`, expected a ReactNode."))}return null}return r(e)}function h(e){function t(t,n,r,o,i){var a=t[n],s=v(a);if("object"!==s){var u=b[o];return new Error("Invalid "+u+" `"+i+"` of type `"+s+"` "+("supplied to `"+r+"`, expected `object`."))}for(var c in e){var l=e[c];if(l){var p=l(a,c,r,o,i+"."+c);if(p)return p}}return null}return r(t)}function d(e){switch(typeof e){case"number":case"string":case"undefined":return!0;case"boolean":return!e;case"object":if(Array.isArray(e))return e.every(d);if(null===e||y.isValidElement(e))return!0;var t=x(e);if(!t)return!1;var n,r=t.call(e);if(t!==e.entries){for(;!(n=r.next()).done;)if(!d(n.value))return!1}else for(;!(n=r.next()).done;){var o=n.value;if(o&&!d(o[1]))return!1}return!0;default:return!1}}function v(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":t}function m(e){var t=v(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}function g(e){return e.constructor&&e.constructor.name?e.constructor.name:"<<anonymous>>"}var y=n(257),b=n(281),w=n(230),x=n(323),_="<<anonymous>>",P={array:o("array"),bool:o("boolean"),func:o("function"),number:o("number"),object:o("object"),string:o("string"),any:i(),arrayOf:a,element:s(),instanceOf:u,node:f(),objectOf:l,oneOf:c,oneOfType:p,shape:h};e.exports=P},function(e){"use strict";function t(e){var t=e&&(n&&e[n]||e[r]);return"function"==typeof t?t:void 0}var n="function"==typeof Symbol&&Symbol.iterator,r="@@iterator";e.exports=t},function(e,t,n){"use strict";var r=n(325),o=n(327),i=n(254),a=(n(240),o.valueContextKey),s={mountWrapper:function(e,t,n){var r=n[a],o=null;if(null!=r)if(o=!1,Array.isArray(r)){for(var i=0;i<r.length;i++)if(""+r[i]==""+t.value){o=!0;break}}else o=""+r==""+t.value;e._wrapperState={selected:o}},getNativeProps:function(e,t){var n=i({selected:void 0,children:void 0},t);null!=e._wrapperState.selected&&(n.selected=e._wrapperState.selected);var o="";return r.forEach(t.children,function(e){null!=e&&("string"==typeof e||"number"==typeof e)&&(o+=e)}),n.children=o,n}};e.exports=s},function(e,t,n){"use strict";function r(e){return(""+e).replace(w,"//")}function o(e,t){this.func=e,this.context=t,this.count=0}function i(e,t){var n=e.func,r=e.context;n.call(r,t,e.count++)}function a(e,t,n){if(null==e)return e;var r=o.getPooled(t,n);g(e,i,r),o.release(r)}function s(e,t,n,r){this.result=e,this.keyPrefix=t,this.func=n,this.context=r,this.count=0}function u(e,t,n){var o=e.result,i=e.keyPrefix,a=e.func,s=e.context,u=a.call(s,t,e.count++);Array.isArray(u)?c(u,o,n,m.thatReturnsArgument):null!=u&&(v.isValidElement(u)&&(u=v.cloneAndReplaceKey(u,i+(u!==t?r(u.key||"")+"/":"")+n)),o.push(u))}function c(e,t,n,o,i){var a="";null!=n&&(a=r(n)+"/");var c=s.getPooled(t,a,o,i);g(e,u,c),s.release(c)}function l(e,t,n){if(null==e)return e;var r=[];return c(e,r,null,t,n),r}function p(){return null}function f(e){return g(e,p,null)}function h(e){var t=[];return c(e,t,null,m.thatReturnsArgument),t}var d=n(271),v=n(257),m=n(230),g=n(326),y=d.twoArgumentPooler,b=d.fourArgumentPooler,w=/\/(?!\/)/g;o.prototype.destructor=function(){this.func=null,this.context=null,this.count=0},d.addPoolingTo(o,y),s.prototype.destructor=function(){this.result=null,this.keyPrefix=null,this.func=null,this.context=null,this.count=0},d.addPoolingTo(s,b);var x={forEach:a,map:l,mapIntoWithKeyPrefixInternal:c,count:f,toArray:h};e.exports=x},function(e,t,n){"use strict";function r(e){return v[e]}function o(e,t){return e&&null!=e.key?a(e.key):t.toString(36)}function i(e){return(""+e).replace(m,r)}function a(e){return"$"+i(e)}function s(e,t,n,r){var i=typeof e;if(("undefined"===i||"boolean"===i)&&(e=null),null===e||"string"===i||"number"===i||c.isValidElement(e))return n(r,e,""===t?h+o(e,0):t),1;var u,l,v=0,m=""===t?h:t+d;if(Array.isArray(e))for(var g=0;g<e.length;g++)u=e[g],l=m+o(u,g),v+=s(u,l,n,r);else{var y=p(e);if(y){var b,w=y.call(e);if(y!==e.entries)for(var x=0;!(b=w.next()).done;)u=b.value,l=m+o(u,x++),v+=s(u,l,n,r);else for(;!(b=w.next()).done;){var _=b.value;_&&(u=_[1],l=m+a(_[0])+d+o(u,0),v+=s(u,l,n,r))}}else if("object"===i){{String(e)}f(!1)}}return v}function u(e,t,n){return null==e?0:s(e,"",t,n)}var c=(n(220),n(257)),l=n(260),p=n(323),f=n(228),h=(n(240),l.SEPARATOR),d=":",v={"=":"=0",".":"=1",":":"=2"},m=/[=.:]/g;e.exports=u},function(e,t,n){"use strict";function r(){if(this._rootNodeID&&this._wrapperState.pendingUpdate){this._wrapperState.pendingUpdate=!1;var e=this._currentElement.props,t=a.getValue(e);null!=t&&o(this,e,t)}}function o(e,t,n){var r,o,i=s.getNode(e._rootNodeID).options;if(t){for(r={},o=0;o<n.length;o++)r[""+n[o]]=!0;for(o=0;o<i.length;o++){var a=r.hasOwnProperty(i[o].value);i[o].selected!==a&&(i[o].selected=a)}}else{for(r=""+n,o=0;o<i.length;o++)if(i[o].value===r)return void(i[o].selected=!0);i.length&&(i[0].selected=!0)}}function i(e){var t=this._currentElement.props,n=a.executeOnChange(t,e);return this._wrapperState.pendingUpdate=!0,u.asap(r,this),n}var a=n(321),s=n(243),u=n(269),c=n(254),l=(n(240),"__ReactDOMSelect_value$"+Math.random().toString(36).slice(2)),p={valueContextKey:l,getNativeProps:function(e,t){return c({},t,{onChange:e._wrapperState.onChange,value:void 0})},mountWrapper:function(e,t){var n=a.getValue(t);e._wrapperState={pendingUpdate:!1,initialValue:null!=n?n:t.defaultValue,onChange:i.bind(e),wasMultiple:Boolean(t.multiple)}},processChildContext:function(e,t,n){var r=c({},n);return r[l]=e._wrapperState.initialValue,r},postUpdateWrapper:function(e){var t=e._currentElement.props;e._wrapperState.initialValue=void 0;var n=e._wrapperState.wasMultiple;e._wrapperState.wasMultiple=Boolean(t.multiple);var r=a.getValue(t);null!=r?(e._wrapperState.pendingUpdate=!1,o(e,Boolean(t.multiple),r)):n!==Boolean(t.multiple)&&(null!=t.defaultValue?o(e,Boolean(t.multiple),t.defaultValue):o(e,Boolean(t.multiple),t.multiple?[]:""))}};e.exports=p},function(e,t,n){"use strict";function r(){this._rootNodeID&&l.updateWrapper(this)}function o(e){var t=this._currentElement.props,n=i.executeOnChange(t,e);return s.asap(r,this),n}var i=n(321),a=n(242),s=n(269),u=n(254),c=n(228),l=(n(240),{getNativeProps:function(e,t){null!=t.dangerouslySetInnerHTML?c(!1):void 0;var n=u({},t,{defaultValue:void 0,value:void 0,children:e._wrapperState.initialValue,onChange:e._wrapperState.onChange});return n},mountWrapper:function(e,t){var n=t.defaultValue,r=t.children;null!=r&&(null!=n?c(!1):void 0,Array.isArray(r)&&(r.length<=1?void 0:c(!1),r=r[0]),n=""+r),null==n&&(n="");var a=i.getValue(t);e._wrapperState={initialValue:""+(null!=a?a:n),onChange:o.bind(e)}},updateWrapper:function(e){var t=e._currentElement.props,n=i.getValue(t);null!=n&&a.updatePropertyByID(e._rootNodeID,"value",""+n)}});e.exports=l},function(e,t,n){"use strict";function r(e,t,n){m.push({parentID:e,parentNode:null,type:p.INSERT_MARKUP,markupIndex:g.push(t)-1,content:null,fromIndex:null,toIndex:n})}function o(e,t,n){m.push({parentID:e,parentNode:null,type:p.MOVE_EXISTING,markupIndex:null,content:null,fromIndex:t,toIndex:n})}function i(e,t){m.push({parentID:e,parentNode:null,type:p.REMOVE_NODE,markupIndex:null,content:null,fromIndex:t,toIndex:null})}function a(e,t){m.push({parentID:e,parentNode:null,type:p.SET_MARKUP,markupIndex:null,content:t,fromIndex:null,toIndex:null})}function s(e,t){m.push({parentID:e,parentNode:null,type:p.TEXT_CONTENT,markupIndex:null,content:t,fromIndex:null,toIndex:null})}function u(){m.length&&(l.processChildrenUpdates(m,g),c())}function c(){m.length=0,g.length=0}var l=n(279),p=n(231),f=(n(220),n(265)),h=n(330),d=n(331),v=0,m=[],g=[],y={Mixin:{_reconcilerInstantiateChildren:function(e,t,n){return h.instantiateChildren(e,t,n)},_reconcilerUpdateChildren:function(e,t,n,r){var o;return o=d(t),h.updateChildren(e,o,n,r)},mountChildren:function(e,t,n){var r=this._reconcilerInstantiateChildren(e,t,n);this._renderedChildren=r;var o=[],i=0;for(var a in r)if(r.hasOwnProperty(a)){var s=r[a],u=this._rootNodeID+a,c=f.mountComponent(s,u,t,n);s._mountIndex=i++,o.push(c)}return o},updateTextContent:function(e){v++;var t=!0;try{var n=this._renderedChildren;h.unmountChildren(n);for(var r in n)n.hasOwnProperty(r)&&this._unmountChild(n[r]);this.setTextContent(e),t=!1}finally{v--,v||(t?c():u())}},updateMarkup:function(e){v++;var t=!0;try{var n=this._renderedChildren;h.unmountChildren(n); for(var r in n)n.hasOwnProperty(r)&&this._unmountChildByName(n[r],r);this.setMarkup(e),t=!1}finally{v--,v||(t?c():u())}},updateChildren:function(e,t,n){v++;var r=!0;try{this._updateChildren(e,t,n),r=!1}finally{v--,v||(r?c():u())}},_updateChildren:function(e,t,n){var r=this._renderedChildren,o=this._reconcilerUpdateChildren(r,e,t,n);if(this._renderedChildren=o,o||r){var i,a=0,s=0;for(i in o)if(o.hasOwnProperty(i)){var u=r&&r[i],c=o[i];u===c?(this.moveChild(u,s,a),a=Math.max(u._mountIndex,a),u._mountIndex=s):(u&&(a=Math.max(u._mountIndex,a),this._unmountChild(u)),this._mountChildByNameAtIndex(c,i,s,t,n)),s++}for(i in r)!r.hasOwnProperty(i)||o&&o.hasOwnProperty(i)||this._unmountChild(r[i])}},unmountChildren:function(){var e=this._renderedChildren;h.unmountChildren(e),this._renderedChildren=null},moveChild:function(e,t,n){e._mountIndex<n&&o(this._rootNodeID,e._mountIndex,t)},createChild:function(e,t){r(this._rootNodeID,t,e._mountIndex)},removeChild:function(e){i(this._rootNodeID,e._mountIndex)},setTextContent:function(e){s(this._rootNodeID,e)},setMarkup:function(e){a(this._rootNodeID,e)},_mountChildByNameAtIndex:function(e,t,n,r,o){var i=this._rootNodeID+t,a=f.mountComponent(e,i,r,o);e._mountIndex=n,this.createChild(e,a)},_unmountChild:function(e){this.removeChild(e),e._mountIndex=null}}};e.exports=y},function(e,t,n){"use strict";function r(e,t,n){var r=void 0===e[n];null!=t&&r&&(e[n]=i(t,null))}var o=n(265),i=n(277),a=n(282),s=n(326),u=(n(240),{instantiateChildren:function(e){if(null==e)return null;var t={};return s(e,r,t),t},updateChildren:function(e,t,n,r){if(!t&&!e)return null;var s;for(s in t)if(t.hasOwnProperty(s)){var u=e&&e[s],c=u&&u._currentElement,l=t[s];if(null!=u&&a(c,l))o.receiveComponent(u,l,n,r),t[s]=u;else{u&&o.unmountComponent(u,s);var p=i(l,null);t[s]=p}}for(s in e)!e.hasOwnProperty(s)||t&&t.hasOwnProperty(s)||o.unmountComponent(e[s]);return t},unmountChildren:function(e){for(var t in e)if(e.hasOwnProperty(t)){var n=e[t];o.unmountComponent(n)}}});e.exports=u},function(e,t,n){"use strict";function r(e,t,n){var r=e,o=void 0===r[n];o&&null!=t&&(r[n]=t)}function o(e){if(null==e)return e;var t={};return i(e,r,t),t}{var i=n(326);n(240)}e.exports=o},function(e){"use strict";function t(e,t){if(e===t)return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return!1;for(var i=n.bind(t),a=0;a<r.length;a++)if(!i(r[a])||e[r[a]]!==t[r[a]])return!1;return!0}var n=Object.prototype.hasOwnProperty;e.exports=t},function(e,t,n){"use strict";function r(e){var t=f.getID(e),n=p.getReactRootIDFromNodeID(t),r=f.findReactContainerForID(n),o=f.getFirstReactDOM(r);return o}function o(e,t){this.topLevelType=e,this.nativeEvent=t,this.ancestors=[]}function i(e){a(e)}function a(e){for(var t=f.getFirstReactDOM(v(e.nativeEvent))||window,n=t;n;)e.ancestors.push(n),n=r(n);for(var o=0;o<e.ancestors.length;o++){t=e.ancestors[o];var i=f.getID(t)||"";g._handleTopLevel(e.topLevelType,t,i,e.nativeEvent,v(e.nativeEvent))}}function s(e){var t=m(window);e(t)}var u=n(334),c=n(224),l=n(271),p=n(260),f=n(243),h=n(269),d=n(254),v=n(296),m=n(335);d(o.prototype,{destructor:function(){this.topLevelType=null,this.nativeEvent=null,this.ancestors.length=0}}),l.addPoolingTo(o,l.twoArgumentPooler);var g={_enabled:!0,_handleTopLevel:null,WINDOW_HANDLE:c.canUseDOM?window:null,setHandleTopLevel:function(e){g._handleTopLevel=e},setEnabled:function(e){g._enabled=!!e},isEnabled:function(){return g._enabled},trapBubbledEvent:function(e,t,n){var r=n;return r?u.listen(r,t,g.dispatchEvent.bind(null,e)):null},trapCapturedEvent:function(e,t,n){var r=n;return r?u.capture(r,t,g.dispatchEvent.bind(null,e)):null},monitorScrollValue:function(e){var t=s.bind(null,e);u.listen(window,"scroll",t)},dispatchEvent:function(e,t){if(g._enabled){var n=o.getPooled(e,t);try{h.batchedUpdates(i,n)}finally{o.release(n)}}}};e.exports=g},function(e,t,n){"use strict";var r=n(230),o={listen:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!1),{remove:function(){e.removeEventListener(t,n,!1)}}):e.attachEvent?(e.attachEvent("on"+t,n),{remove:function(){e.detachEvent("on"+t,n)}}):void 0},capture:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!0),{remove:function(){e.removeEventListener(t,n,!0)}}):{remove:r}},registerDefault:function(){}};e.exports=o},function(e){"use strict";function t(e){return e===window?{x:window.pageXOffset||document.documentElement.scrollLeft,y:window.pageYOffset||document.documentElement.scrollTop}:{x:e.scrollLeft,y:e.scrollTop}}e.exports=t},function(e,t,n){"use strict";var r=n(238),o=n(246),i=n(279),a=n(337),s=n(283),u=n(244),c=n(284),l=n(233),p=n(261),f=n(269),h={Component:i.injection,Class:a.injection,DOMProperty:r.injection,EmptyComponent:s.injection,EventPluginHub:o.injection,EventEmitter:u.injection,NativeComponent:c.injection,Perf:l.injection,RootIndex:p.injection,Updates:f.injection};e.exports=h},function(e,t,n){"use strict";function r(e,t){var n=_.hasOwnProperty(t)?_[t]:null;C.hasOwnProperty(t)&&(n!==w.OVERRIDE_BASE?m(!1):void 0),e.hasOwnProperty(t)&&(n!==w.DEFINE_MANY&&n!==w.DEFINE_MANY_MERGED?m(!1):void 0)}function o(e,t){if(t){"function"==typeof t?m(!1):void 0,f.isValidElement(t)?m(!1):void 0;var n=e.prototype;t.hasOwnProperty(b)&&P.mixins(e,t.mixins);for(var o in t)if(t.hasOwnProperty(o)&&o!==b){var i=t[o];if(r(n,o),P.hasOwnProperty(o))P[o](e,i);else{var a=_.hasOwnProperty(o),c=n.hasOwnProperty(o),l="function"==typeof i,p=l&&!a&&!c&&t.autobind!==!1;if(p)n.__reactAutoBindMap||(n.__reactAutoBindMap={}),n.__reactAutoBindMap[o]=i,n[o]=i;else if(c){var h=_[o];!a||h!==w.DEFINE_MANY_MERGED&&h!==w.DEFINE_MANY?m(!1):void 0,h===w.DEFINE_MANY_MERGED?n[o]=s(n[o],i):h===w.DEFINE_MANY&&(n[o]=u(n[o],i))}else n[o]=i}}}}function i(e,t){if(t)for(var n in t){var r=t[n];if(t.hasOwnProperty(n)){var o=n in P;o?m(!1):void 0;var i=n in e;i?m(!1):void 0,e[n]=r}}}function a(e,t){e&&t&&"object"==typeof e&&"object"==typeof t?void 0:m(!1);for(var n in t)t.hasOwnProperty(n)&&(void 0!==e[n]?m(!1):void 0,e[n]=t[n]);return e}function s(e,t){return function(){var n=e.apply(this,arguments),r=t.apply(this,arguments);if(null==n)return r;if(null==r)return n;var o={};return a(o,n),a(o,r),o}}function u(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}function c(e,t){var n=t.bind(e);return n}function l(e){for(var t in e.__reactAutoBindMap)if(e.__reactAutoBindMap.hasOwnProperty(t)){var n=e.__reactAutoBindMap[t];e[t]=c(e,n)}}var p=n(338),f=n(257),h=(n(280),n(281),n(339)),d=n(254),v=n(273),m=n(228),g=n(232),y=n(294),b=(n(240),y({mixins:null})),w=g({DEFINE_ONCE:null,DEFINE_MANY:null,OVERRIDE_BASE:null,DEFINE_MANY_MERGED:null}),x=[],_={mixins:w.DEFINE_MANY,statics:w.DEFINE_MANY,propTypes:w.DEFINE_MANY,contextTypes:w.DEFINE_MANY,childContextTypes:w.DEFINE_MANY,getDefaultProps:w.DEFINE_MANY_MERGED,getInitialState:w.DEFINE_MANY_MERGED,getChildContext:w.DEFINE_MANY_MERGED,render:w.DEFINE_ONCE,componentWillMount:w.DEFINE_MANY,componentDidMount:w.DEFINE_MANY,componentWillReceiveProps:w.DEFINE_MANY,shouldComponentUpdate:w.DEFINE_ONCE,componentWillUpdate:w.DEFINE_MANY,componentDidUpdate:w.DEFINE_MANY,componentWillUnmount:w.DEFINE_MANY,updateComponent:w.OVERRIDE_BASE},P={displayName:function(e,t){e.displayName=t},mixins:function(e,t){if(t)for(var n=0;n<t.length;n++)o(e,t[n])},childContextTypes:function(e,t){e.childContextTypes=d({},e.childContextTypes,t)},contextTypes:function(e,t){e.contextTypes=d({},e.contextTypes,t)},getDefaultProps:function(e,t){e.getDefaultProps=e.getDefaultProps?s(e.getDefaultProps,t):t},propTypes:function(e,t){e.propTypes=d({},e.propTypes,t)},statics:function(e,t){i(e,t)},autobind:function(){}},C={replaceState:function(e,t){this.updater.enqueueReplaceState(this,e),t&&this.updater.enqueueCallback(this,t)},isMounted:function(){return this.updater.isMounted(this)},setProps:function(e,t){this.updater.enqueueSetProps(this,e),t&&this.updater.enqueueCallback(this,t)},replaceProps:function(e,t){this.updater.enqueueReplaceProps(this,e),t&&this.updater.enqueueCallback(this,t)}},E=function(){};d(E.prototype,p.prototype,C);var R={createClass:function(e){var t=function(e,t,n){this.__reactAutoBindMap&&l(this),this.props=e,this.context=t,this.refs=v,this.updater=n||h,this.state=null;var r=this.getInitialState?this.getInitialState():null;"object"!=typeof r||Array.isArray(r)?m(!1):void 0,this.state=r};t.prototype=new E,t.prototype.constructor=t,x.forEach(o.bind(null,t)),o(t,e),t.getDefaultProps&&(t.defaultProps=t.getDefaultProps()),t.prototype.render?void 0:m(!1);for(var n in _)t.prototype[n]||(t.prototype[n]=null);return t},injection:{injectMixin:function(e){x.push(e)}}};e.exports=R},function(e,t,n){"use strict";function r(e,t,n){this.props=e,this.context=t,this.refs=i,this.updater=n||o}{var o=n(339),i=(n(258),n(273)),a=n(228);n(240)}r.prototype.isReactComponent={},r.prototype.setState=function(e,t){"object"!=typeof e&&"function"!=typeof e&&null!=e?a(!1):void 0,this.updater.enqueueSetState(this,e),t&&this.updater.enqueueCallback(this,t)},r.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this),e&&this.updater.enqueueCallback(this,e)};e.exports=r},function(e,t,n){"use strict";function r(e,t){}var o=(n(240),{isMounted:function(){return!1},enqueueCallback:function(){},enqueueForceUpdate:function(e){r(e,"forceUpdate")},enqueueReplaceState:function(e){r(e,"replaceState")},enqueueSetState:function(e){r(e,"setState")},enqueueSetProps:function(e){r(e,"setProps")},enqueueReplaceProps:function(e){r(e,"replaceProps")}});e.exports=o},function(e,t,n){"use strict";function r(e){this.reinitializeTransaction(),this.renderToStaticMarkup=!1,this.reactMountReady=o.getPooled(null),this.useCreateElement=!e&&s.useCreateElement}var o=n(270),i=n(271),a=n(244),s=n(256),u=n(341),c=n(272),l=n(254),p={initialize:u.getSelectionInformation,close:u.restoreSelection},f={initialize:function(){var e=a.isEnabled();return a.setEnabled(!1),e},close:function(e){a.setEnabled(e)}},h={initialize:function(){this.reactMountReady.reset()},close:function(){this.reactMountReady.notifyAll()}},d=[p,f,h],v={getTransactionWrappers:function(){return d},getReactMountReady:function(){return this.reactMountReady},destructor:function(){o.release(this.reactMountReady),this.reactMountReady=null}};l(r.prototype,c.Mixin,v),i.addPoolingTo(r),e.exports=r},function(e,t,n){"use strict";function r(e){return i(document.documentElement,e)}var o=n(342),i=n(274),a=n(310),s=n(344),u={hasSelectionCapabilities:function(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&"text"===e.type||"textarea"===t||"true"===e.contentEditable)},getSelectionInformation:function(){var e=s();return{focusedElem:e,selectionRange:u.hasSelectionCapabilities(e)?u.getSelection(e):null}},restoreSelection:function(e){var t=s(),n=e.focusedElem,o=e.selectionRange;t!==n&&r(n)&&(u.hasSelectionCapabilities(n)&&u.setSelection(n,o),a(n))},getSelection:function(e){var t;if("selectionStart"in e)t={start:e.selectionStart,end:e.selectionEnd};else if(document.selection&&e.nodeName&&"input"===e.nodeName.toLowerCase()){var n=document.selection.createRange();n.parentElement()===e&&(t={start:-n.moveStart("character",-e.value.length),end:-n.moveEnd("character",-e.value.length)})}else t=o.getOffsets(e);return t||{start:0,end:0}},setSelection:function(e,t){var n=t.start,r=t.end;if("undefined"==typeof r&&(r=n),"selectionStart"in e)e.selectionStart=n,e.selectionEnd=Math.min(r,e.value.length);else if(document.selection&&e.nodeName&&"input"===e.nodeName.toLowerCase()){var i=e.createTextRange();i.collapse(!0),i.moveStart("character",n),i.moveEnd("character",r-n),i.select()}else o.setOffsets(e,t)}};e.exports=u},function(e,t,n){"use strict";function r(e,t,n,r){return e===n&&t===r}function o(e){var t=document.selection,n=t.createRange(),r=n.text.length,o=n.duplicate();o.moveToElementText(e),o.setEndPoint("EndToStart",n);var i=o.text.length,a=i+r;return{start:i,end:a}}function i(e){var t=window.getSelection&&window.getSelection();if(!t||0===t.rangeCount)return null;var n=t.anchorNode,o=t.anchorOffset,i=t.focusNode,a=t.focusOffset,s=t.getRangeAt(0);try{s.startContainer.nodeType,s.endContainer.nodeType}catch(u){return null}var c=r(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset),l=c?0:s.toString().length,p=s.cloneRange();p.selectNodeContents(e),p.setEnd(s.startContainer,s.startOffset);var f=r(p.startContainer,p.startOffset,p.endContainer,p.endOffset),h=f?0:p.toString().length,d=h+l,v=document.createRange();v.setStart(n,o),v.setEnd(i,a);var m=v.collapsed;return{start:m?d:h,end:m?h:d}}function a(e,t){var n,r,o=document.selection.createRange().duplicate();"undefined"==typeof t.end?(n=t.start,r=n):t.start>t.end?(n=t.end,r=t.start):(n=t.start,r=t.end),o.moveToElementText(e),o.moveStart("character",n),o.setEndPoint("EndToStart",o),o.moveEnd("character",r-n),o.select()}function s(e,t){if(window.getSelection){var n=window.getSelection(),r=e[l()].length,o=Math.min(t.start,r),i="undefined"==typeof t.end?o:Math.min(t.end,r);if(!n.extend&&o>i){var a=i;i=o,o=a}var s=c(e,o),u=c(e,i);if(s&&u){var p=document.createRange();p.setStart(s.node,s.offset),n.removeAllRanges(),o>i?(n.addRange(p),n.extend(u.node,u.offset)):(p.setEnd(u.node,u.offset),n.addRange(p))}}}var u=n(224),c=n(343),l=n(290),p=u.canUseDOM&&"selection"in document&&!("getSelection"in window),f={getOffsets:p?o:i,setOffsets:p?a:s};e.exports=f},function(e){"use strict";function t(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function n(e){for(;e;){if(e.nextSibling)return e.nextSibling;e=e.parentNode}}function r(e,r){for(var o=t(e),i=0,a=0;o;){if(3===o.nodeType){if(a=i+o.textContent.length,r>=i&&a>=r)return{node:o,offset:r-i};i=a}o=t(n(o))}}e.exports=r},function(e){"use strict";function t(){if("undefined"==typeof document)return null;try{return document.activeElement||document.body}catch(e){return document.body}}e.exports=t},function(e,t,n){"use strict";function r(e){if("selectionStart"in e&&u.hasSelectionCapabilities(e))return{start:e.selectionStart,end:e.selectionEnd};if(window.getSelection){var t=window.getSelection();return{anchorNode:t.anchorNode,anchorOffset:t.anchorOffset,focusNode:t.focusNode,focusOffset:t.focusOffset}}if(document.selection){var n=document.selection.createRange();return{parentElement:n.parentElement(),text:n.text,top:n.boundingTop,left:n.boundingLeft}}}function o(e,t){if(w||null==g||g!==l())return null;var n=r(g);if(!b||!h(b,n)){b=n;var o=c.getPooled(m.select,y,e,t);return o.type="select",o.target=g,a.accumulateTwoPhaseDispatches(o),o}return null}var i=n(245),a=n(288),s=n(224),u=n(341),c=n(292),l=n(344),p=n(297),f=n(294),h=n(332),d=i.topLevelTypes,v=s.canUseDOM&&"documentMode"in document&&document.documentMode<=11,m={select:{phasedRegistrationNames:{bubbled:f({onSelect:null}),captured:f({onSelectCapture:null})},dependencies:[d.topBlur,d.topContextMenu,d.topFocus,d.topKeyDown,d.topMouseDown,d.topMouseUp,d.topSelectionChange]}},g=null,y=null,b=null,w=!1,x=!1,_=f({onSelect:null}),P={eventTypes:m,extractEvents:function(e,t,n,r,i){if(!x)return null;switch(e){case d.topFocus:(p(t)||"true"===t.contentEditable)&&(g=t,y=n,b=null);break;case d.topBlur:g=null,y=null,b=null;break;case d.topMouseDown:w=!0;break;case d.topContextMenu:case d.topMouseUp:return w=!1,o(r,i);case d.topSelectionChange:if(v)break;case d.topKeyDown:case d.topKeyUp:return o(r,i)}return null},didPutListener:function(e,t){t===_&&(x=!0)}};e.exports=P},function(e){"use strict";var t=Math.pow(2,53),n={createReactRootIndex:function(){return Math.ceil(Math.random()*t)}};e.exports=n},function(e,t,n){"use strict";var r=n(245),o=n(334),i=n(288),a=n(243),s=n(348),u=n(292),c=n(349),l=n(350),p=n(301),f=n(353),h=n(354),d=n(302),v=n(355),m=n(230),g=n(351),y=n(228),b=n(294),w=r.topLevelTypes,x={abort:{phasedRegistrationNames:{bubbled:b({onAbort:!0}),captured:b({onAbortCapture:!0})}},blur:{phasedRegistrationNames:{bubbled:b({onBlur:!0}),captured:b({onBlurCapture:!0})}},canPlay:{phasedRegistrationNames:{bubbled:b({onCanPlay:!0}),captured:b({onCanPlayCapture:!0})}},canPlayThrough:{phasedRegistrationNames:{bubbled:b({onCanPlayThrough:!0}),captured:b({onCanPlayThroughCapture:!0})}},click:{phasedRegistrationNames:{bubbled:b({onClick:!0}),captured:b({onClickCapture:!0})}},contextMenu:{phasedRegistrationNames:{bubbled:b({onContextMenu:!0}),captured:b({onContextMenuCapture:!0})}},copy:{phasedRegistrationNames:{bubbled:b({onCopy:!0}),captured:b({onCopyCapture:!0})}},cut:{phasedRegistrationNames:{bubbled:b({onCut:!0}),captured:b({onCutCapture:!0})}},doubleClick:{phasedRegistrationNames:{bubbled:b({onDoubleClick:!0}),captured:b({onDoubleClickCapture:!0})}},drag:{phasedRegistrationNames:{bubbled:b({onDrag:!0}),captured:b({onDragCapture:!0})}},dragEnd:{phasedRegistrationNames:{bubbled:b({onDragEnd:!0}),captured:b({onDragEndCapture:!0})}},dragEnter:{phasedRegistrationNames:{bubbled:b({onDragEnter:!0}),captured:b({onDragEnterCapture:!0})}},dragExit:{phasedRegistrationNames:{bubbled:b({onDragExit:!0}),captured:b({onDragExitCapture:!0})}},dragLeave:{phasedRegistrationNames:{bubbled:b({onDragLeave:!0}),captured:b({onDragLeaveCapture:!0})}},dragOver:{phasedRegistrationNames:{bubbled:b({onDragOver:!0}),captured:b({onDragOverCapture:!0})}},dragStart:{phasedRegistrationNames:{bubbled:b({onDragStart:!0}),captured:b({onDragStartCapture:!0})}},drop:{phasedRegistrationNames:{bubbled:b({onDrop:!0}),captured:b({onDropCapture:!0})}},durationChange:{phasedRegistrationNames:{bubbled:b({onDurationChange:!0}),captured:b({onDurationChangeCapture:!0})}},emptied:{phasedRegistrationNames:{bubbled:b({onEmptied:!0}),captured:b({onEmptiedCapture:!0})}},encrypted:{phasedRegistrationNames:{bubbled:b({onEncrypted:!0}),captured:b({onEncryptedCapture:!0})}},ended:{phasedRegistrationNames:{bubbled:b({onEnded:!0}),captured:b({onEndedCapture:!0})}},error:{phasedRegistrationNames:{bubbled:b({onError:!0}),captured:b({onErrorCapture:!0})}},focus:{phasedRegistrationNames:{bubbled:b({onFocus:!0}),captured:b({onFocusCapture:!0})}},input:{phasedRegistrationNames:{bubbled:b({onInput:!0}),captured:b({onInputCapture:!0})}},keyDown:{phasedRegistrationNames:{bubbled:b({onKeyDown:!0}),captured:b({onKeyDownCapture:!0})}},keyPress:{phasedRegistrationNames:{bubbled:b({onKeyPress:!0}),captured:b({onKeyPressCapture:!0})}},keyUp:{phasedRegistrationNames:{bubbled:b({onKeyUp:!0}),captured:b({onKeyUpCapture:!0})}},load:{phasedRegistrationNames:{bubbled:b({onLoad:!0}),captured:b({onLoadCapture:!0})}},loadedData:{phasedRegistrationNames:{bubbled:b({onLoadedData:!0}),captured:b({onLoadedDataCapture:!0})}},loadedMetadata:{phasedRegistrationNames:{bubbled:b({onLoadedMetadata:!0}),captured:b({onLoadedMetadataCapture:!0})}},loadStart:{phasedRegistrationNames:{bubbled:b({onLoadStart:!0}),captured:b({onLoadStartCapture:!0})}},mouseDown:{phasedRegistrationNames:{bubbled:b({onMouseDown:!0}),captured:b({onMouseDownCapture:!0})}},mouseMove:{phasedRegistrationNames:{bubbled:b({onMouseMove:!0}),captured:b({onMouseMoveCapture:!0})}},mouseOut:{phasedRegistrationNames:{bubbled:b({onMouseOut:!0}),captured:b({onMouseOutCapture:!0})}},mouseOver:{phasedRegistrationNames:{bubbled:b({onMouseOver:!0}),captured:b({onMouseOverCapture:!0})}},mouseUp:{phasedRegistrationNames:{bubbled:b({onMouseUp:!0}),captured:b({onMouseUpCapture:!0})}},paste:{phasedRegistrationNames:{bubbled:b({onPaste:!0}),captured:b({onPasteCapture:!0})}},pause:{phasedRegistrationNames:{bubbled:b({onPause:!0}),captured:b({onPauseCapture:!0})}},play:{phasedRegistrationNames:{bubbled:b({onPlay:!0}),captured:b({onPlayCapture:!0})}},playing:{phasedRegistrationNames:{bubbled:b({onPlaying:!0}),captured:b({onPlayingCapture:!0})}},progress:{phasedRegistrationNames:{bubbled:b({onProgress:!0}),captured:b({onProgressCapture:!0})}},rateChange:{phasedRegistrationNames:{bubbled:b({onRateChange:!0}),captured:b({onRateChangeCapture:!0})}},reset:{phasedRegistrationNames:{bubbled:b({onReset:!0}),captured:b({onResetCapture:!0})}},scroll:{phasedRegistrationNames:{bubbled:b({onScroll:!0}),captured:b({onScrollCapture:!0})}},seeked:{phasedRegistrationNames:{bubbled:b({onSeeked:!0}),captured:b({onSeekedCapture:!0})}},seeking:{phasedRegistrationNames:{bubbled:b({onSeeking:!0}),captured:b({onSeekingCapture:!0})}},stalled:{phasedRegistrationNames:{bubbled:b({onStalled:!0}),captured:b({onStalledCapture:!0})}},submit:{phasedRegistrationNames:{bubbled:b({onSubmit:!0}),captured:b({onSubmitCapture:!0})}},suspend:{phasedRegistrationNames:{bubbled:b({onSuspend:!0}),captured:b({onSuspendCapture:!0})}},timeUpdate:{phasedRegistrationNames:{bubbled:b({onTimeUpdate:!0}),captured:b({onTimeUpdateCapture:!0})}},touchCancel:{phasedRegistrationNames:{bubbled:b({onTouchCancel:!0}),captured:b({onTouchCancelCapture:!0})}},touchEnd:{phasedRegistrationNames:{bubbled:b({onTouchEnd:!0}),captured:b({onTouchEndCapture:!0})}},touchMove:{phasedRegistrationNames:{bubbled:b({onTouchMove:!0}),captured:b({onTouchMoveCapture:!0})}},touchStart:{phasedRegistrationNames:{bubbled:b({onTouchStart:!0}),captured:b({onTouchStartCapture:!0})}},volumeChange:{phasedRegistrationNames:{bubbled:b({onVolumeChange:!0}),captured:b({onVolumeChangeCapture:!0})}},waiting:{phasedRegistrationNames:{bubbled:b({onWaiting:!0}),captured:b({onWaitingCapture:!0})}},wheel:{phasedRegistrationNames:{bubbled:b({onWheel:!0}),captured:b({onWheelCapture:!0})}}},_={topAbort:x.abort,topBlur:x.blur,topCanPlay:x.canPlay,topCanPlayThrough:x.canPlayThrough,topClick:x.click,topContextMenu:x.contextMenu,topCopy:x.copy,topCut:x.cut,topDoubleClick:x.doubleClick,topDrag:x.drag,topDragEnd:x.dragEnd,topDragEnter:x.dragEnter,topDragExit:x.dragExit,topDragLeave:x.dragLeave,topDragOver:x.dragOver,topDragStart:x.dragStart,topDrop:x.drop,topDurationChange:x.durationChange,topEmptied:x.emptied,topEncrypted:x.encrypted,topEnded:x.ended,topError:x.error,topFocus:x.focus,topInput:x.input,topKeyDown:x.keyDown,topKeyPress:x.keyPress,topKeyUp:x.keyUp,topLoad:x.load,topLoadedData:x.loadedData,topLoadedMetadata:x.loadedMetadata,topLoadStart:x.loadStart,topMouseDown:x.mouseDown,topMouseMove:x.mouseMove,topMouseOut:x.mouseOut,topMouseOver:x.mouseOver,topMouseUp:x.mouseUp,topPaste:x.paste,topPause:x.pause,topPlay:x.play,topPlaying:x.playing,topProgress:x.progress,topRateChange:x.rateChange,topReset:x.reset,topScroll:x.scroll,topSeeked:x.seeked,topSeeking:x.seeking,topStalled:x.stalled,topSubmit:x.submit,topSuspend:x.suspend,topTimeUpdate:x.timeUpdate,topTouchCancel:x.touchCancel,topTouchEnd:x.touchEnd,topTouchMove:x.touchMove,topTouchStart:x.touchStart,topVolumeChange:x.volumeChange,topWaiting:x.waiting,topWheel:x.wheel};for(var P in _)_[P].dependencies=[P];var C=b({onClick:null}),E={},R={eventTypes:x,extractEvents:function(e,t,n,r,o){var a=_[e];if(!a)return null;var m;switch(e){case w.topAbort:case w.topCanPlay:case w.topCanPlayThrough:case w.topDurationChange:case w.topEmptied:case w.topEncrypted:case w.topEnded:case w.topError:case w.topInput:case w.topLoad:case w.topLoadedData:case w.topLoadedMetadata:case w.topLoadStart:case w.topPause:case w.topPlay:case w.topPlaying:case w.topProgress:case w.topRateChange:case w.topReset:case w.topSeeked:case w.topSeeking:case w.topStalled:case w.topSubmit:case w.topSuspend:case w.topTimeUpdate:case w.topVolumeChange:case w.topWaiting:m=u;break;case w.topKeyPress:if(0===g(r))return null;case w.topKeyDown:case w.topKeyUp:m=l;break;case w.topBlur:case w.topFocus:m=c;break;case w.topClick:if(2===r.button)return null;case w.topContextMenu:case w.topDoubleClick:case w.topMouseDown:case w.topMouseMove:case w.topMouseOut:case w.topMouseOver:case w.topMouseUp:m=p;break;case w.topDrag:case w.topDragEnd:case w.topDragEnter:case w.topDragExit:case w.topDragLeave:case w.topDragOver:case w.topDragStart:case w.topDrop:m=f;break;case w.topTouchCancel:case w.topTouchEnd:case w.topTouchMove:case w.topTouchStart:m=h;break;case w.topScroll:m=d;break;case w.topWheel:m=v;break;case w.topCopy:case w.topCut:case w.topPaste:m=s}m?void 0:y(!1);var b=m.getPooled(a,n,r,o);return i.accumulateTwoPhaseDispatches(b),b},didPutListener:function(e,t){if(t===C){var n=a.getNode(e);E[e]||(E[e]=o.listen(n,"click",m))}},willDeleteListener:function(e,t){t===C&&(E[e].remove(),delete E[e])}};e.exports=R},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(292),i={clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(302),i={relatedTarget:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(302),i=n(351),a=n(352),s=n(303),u={key:a,location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:s,charCode:function(e){return"keypress"===e.type?i(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?i(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}};o.augmentClass(r,u),e.exports=r},function(e){"use strict";function t(e){var t,n=e.keyCode;return"charCode"in e?(t=e.charCode,0===t&&13===n&&(t=13)):t=n,t>=32||13===t?t:0}e.exports=t},function(e,t,n){"use strict";function r(e){if(e.key){var t=i[e.key]||e.key;if("Unidentified"!==t)return t}if("keypress"===e.type){var n=o(e);return 13===n?"Enter":String.fromCharCode(n)}return"keydown"===e.type||"keyup"===e.type?a[e.keyCode]||"Unidentified":""}var o=n(351),i={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},a={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"};e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(301),i={dataTransfer:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(302),i=n(303),a={touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:i};o.augmentClass(r,a),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(301),i={deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:null,deltaMode:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";var r=n(238),o=r.injection.MUST_USE_ATTRIBUTE,i={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"},a={Properties:{clipPath:o,cx:o,cy:o,d:o,dx:o,dy:o,fill:o,fillOpacity:o,fontFamily:o,fontSize:o,fx:o,fy:o,gradientTransform:o,gradientUnits:o,markerEnd:o,markerMid:o,markerStart:o,offset:o,opacity:o,patternContentUnits:o,patternUnits:o,points:o,preserveAspectRatio:o,r:o,rx:o,ry:o,spreadMethod:o,stopColor:o,stopOpacity:o,stroke:o,strokeDasharray:o,strokeLinecap:o,strokeOpacity:o,strokeWidth:o,textAnchor:o,transform:o,version:o,viewBox:o,x1:o,x2:o,x:o,xlinkActuate:o,xlinkArcrole:o,xlinkHref:o,xlinkRole:o,xlinkShow:o,xlinkTitle:o,xlinkType:o,xmlBase:o,xmlLang:o,xmlSpace:o,y1:o,y2:o,y:o},DOMAttributeNamespaces:{xlinkActuate:i.xlink,xlinkArcrole:i.xlink,xlinkHref:i.xlink,xlinkRole:i.xlink,xlinkShow:i.xlink,xlinkTitle:i.xlink,xlinkType:i.xlink,xmlBase:i.xml,xmlLang:i.xml,xmlSpace:i.xml},DOMAttributeNames:{clipPath:"clip-path",fillOpacity:"fill-opacity",fontFamily:"font-family",fontSize:"font-size",gradientTransform:"gradientTransform",gradientUnits:"gradientUnits",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",patternContentUnits:"patternContentUnits",patternUnits:"patternUnits",preserveAspectRatio:"preserveAspectRatio",spreadMethod:"spreadMethod",stopColor:"stop-color",stopOpacity:"stop-opacity",strokeDasharray:"stroke-dasharray",strokeLinecap:"stroke-linecap",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",textAnchor:"text-anchor",viewBox:"viewBox",xlinkActuate:"xlink:actuate",xlinkArcrole:"xlink:arcrole",xlinkHref:"xlink:href",xlinkRole:"xlink:role",xlinkShow:"xlink:show",xlinkTitle:"xlink:title",xlinkType:"xlink:type",xmlBase:"xml:base",xmlLang:"xml:lang",xmlSpace:"xml:space"}};e.exports=a},function(e){"use strict";e.exports="0.14.1"},function(e,t,n){"use strict";var r=n(243);e.exports=r.renderSubtreeIntoContainer},function(e,t,n){"use strict";var r=n(286),o=n(360),i=n(357);r.inject();var a={renderToString:o.renderToString,renderToStaticMarkup:o.renderToStaticMarkup,version:i};e.exports=a},function(e,t,n){"use strict";function r(e){a.isValidElement(e)?void 0:d(!1);var t;try{p.injection.injectBatchingStrategy(c);var n=s.createReactRootID();return t=l.getPooled(!1),t.perform(function(){var r=h(e,null),o=r.mountComponent(n,t,f);return u.addChecksumToMarkup(o)},null)}finally{l.release(t),p.injection.injectBatchingStrategy(i)}}function o(e){a.isValidElement(e)?void 0:d(!1);var t;try{p.injection.injectBatchingStrategy(c);var n=s.createReactRootID();return t=l.getPooled(!0),t.perform(function(){var r=h(e,null);return r.mountComponent(n,t,f)},null)}finally{l.release(t),p.injection.injectBatchingStrategy(i)}}var i=n(307),a=n(257),s=n(260),u=n(263),c=n(361),l=n(362),p=n(269),f=n(273),h=n(277),d=n(228);e.exports={renderToString:r,renderToStaticMarkup:o}},function(e){"use strict";var t={isBatchingUpdates:!1,batchedUpdates:function(){}};e.exports=t},function(e,t,n){"use strict";function r(e){this.reinitializeTransaction(),this.renderToStaticMarkup=e,this.reactMountReady=i.getPooled(null),this.useCreateElement=!1}var o=n(271),i=n(270),a=n(272),s=n(254),u=n(230),c={initialize:function(){this.reactMountReady.reset()},close:u},l=[c],p={getTransactionWrappers:function(){return l},getReactMountReady:function(){return this.reactMountReady},destructor:function(){i.release(this.reactMountReady),this.reactMountReady=null}};s(r.prototype,a.Mixin,p),o.addPoolingTo(r),e.exports=r},function(e,t,n){"use strict";var r=n(325),o=n(338),i=n(337),a=n(364),s=n(257),u=(n(365),n(322)),c=n(357),l=n(254),p=n(367),f=s.createElement,h=s.createFactory,d=s.cloneElement,v={Children:{map:r.map,forEach:r.forEach,count:r.count,toArray:r.toArray,only:p},Component:o,createElement:f,cloneElement:d,isValidElement:s.isValidElement,PropTypes:u,createClass:i.createClass,createFactory:h,createMixin:function(e){return e},DOM:a,version:c,__spread:l};e.exports=v},function(e,t,n){"use strict";function r(e){return o.createFactory(e)}var o=n(257),i=(n(365),n(366)),a=i({a:"a",abbr:"abbr",address:"address",area:"area",article:"article",aside:"aside",audio:"audio",b:"b",base:"base",bdi:"bdi",bdo:"bdo",big:"big",blockquote:"blockquote",body:"body",br:"br",button:"button",canvas:"canvas",caption:"caption",cite:"cite",code:"code",col:"col",colgroup:"colgroup",data:"data",datalist:"datalist",dd:"dd",del:"del",details:"details",dfn:"dfn",dialog:"dialog",div:"div",dl:"dl",dt:"dt",em:"em",embed:"embed",fieldset:"fieldset",figcaption:"figcaption",figure:"figure",footer:"footer",form:"form",h1:"h1",h2:"h2",h3:"h3",h4:"h4",h5:"h5",h6:"h6",head:"head",header:"header",hgroup:"hgroup",hr:"hr",html:"html",i:"i",iframe:"iframe",img:"img",input:"input",ins:"ins",kbd:"kbd",keygen:"keygen",label:"label",legend:"legend",li:"li",link:"link",main:"main",map:"map",mark:"mark",menu:"menu",menuitem:"menuitem",meta:"meta",meter:"meter",nav:"nav",noscript:"noscript",object:"object",ol:"ol",optgroup:"optgroup",option:"option",output:"output",p:"p",param:"param",picture:"picture",pre:"pre",progress:"progress",q:"q",rp:"rp",rt:"rt",ruby:"ruby",s:"s",samp:"samp",script:"script", section:"section",select:"select",small:"small",source:"source",span:"span",strong:"strong",style:"style",sub:"sub",summary:"summary",sup:"sup",table:"table",tbody:"tbody",td:"td",textarea:"textarea",tfoot:"tfoot",th:"th",thead:"thead",time:"time",title:"title",tr:"tr",track:"track",u:"u",ul:"ul","var":"var",video:"video",wbr:"wbr",circle:"circle",clipPath:"clipPath",defs:"defs",ellipse:"ellipse",g:"g",image:"image",line:"line",linearGradient:"linearGradient",mask:"mask",path:"path",pattern:"pattern",polygon:"polygon",polyline:"polyline",radialGradient:"radialGradient",rect:"rect",stop:"stop",svg:"svg",text:"text",tspan:"tspan"},r);e.exports=a},function(e,t,n){"use strict";function r(){if(p.current){var e=p.current.getName();if(e)return" Check the render method of `"+e+"`."}return""}function o(e,t){if(e._store&&!e._store.validated&&null==e.key){e._store.validated=!0;{i("uniqueKey",e,t)}}}function i(e,t,n){var o=r();if(!o){var i="string"==typeof n?n:n.displayName||n.name;i&&(o=" Check the top-level render call using <"+i+">.")}var a=d[e]||(d[e]={});if(a[o])return null;a[o]=!0;var s={parentOrOwner:o,url:" See https://fb.me/react-warning-keys for more information.",childOwner:null};return t&&t._owner&&t._owner!==p.current&&(s.childOwner=" It was passed a child from "+t._owner.getName()+"."),s}function a(e,t){if("object"==typeof e)if(Array.isArray(e))for(var n=0;n<e.length;n++){var r=e[n];c.isValidElement(r)&&o(r,t)}else if(c.isValidElement(e))e._store&&(e._store.validated=!0);else if(e){var i=f(e);if(i&&i!==e.entries)for(var a,s=i.call(e);!(a=s.next()).done;)c.isValidElement(a.value)&&o(a.value,t)}}function s(e,t,n,o){for(var i in t)if(t.hasOwnProperty(i)){var a;try{"function"!=typeof t[i]?h(!1):void 0,a=t[i](n,i,e,o)}catch(s){a=s}if(a instanceof Error&&!(a.message in v)){v[a.message]=!0;{r()}}}}function u(e){var t=e.type;if("function"==typeof t){var n=t.displayName||t.name;t.propTypes&&s(n,t.propTypes,e.props,l.prop),"function"==typeof t.getDefaultProps}}var c=n(257),l=n(280),p=(n(281),n(220)),f=(n(258),n(323)),h=n(228),d=(n(240),{}),v={},m={createElement:function(e){var t="string"==typeof e||"function"==typeof e,n=c.createElement.apply(this,arguments);if(null==n)return n;if(t)for(var r=2;r<arguments.length;r++)a(arguments[r],e);return u(n),n},createFactory:function(e){var t=m.createElement.bind(null,e);return t.type=e,t},cloneElement:function(){for(var e=c.cloneElement.apply(this,arguments),t=2;t<arguments.length;t++)a(arguments[t],e.type);return u(e),e}};e.exports=m},function(e){"use strict";function t(e,t,r){if(!e)return null;var o={};for(var i in e)n.call(e,i)&&(o[i]=t.call(r,e[i],i,e));return o}var n=Object.prototype.hasOwnProperty;e.exports=t},function(e,t,n){"use strict";function r(e){return o.isValidElement(e)?void 0:i(!1),e}var o=n(257),i=n(228);e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r,o){return o}n(254),n(240);e.exports=r},function(e,t,n){"use strict";e.exports=n(219)},function(e,t,n){"use strict";function r(e){var t="string"==typeof e,n=void 0;if(n=t?document.querySelector(e):e,!o(n)){var r="Container must be `string` or `HTMLElement`.";throw t&&(r+=" Unable to find "+e),new Error(r)}return n}function o(e){return e instanceof HTMLElement||!!e&&e.nodeType>0}function i(e){return e.altKey||e.ctrlKey||e.metaKey||e.shiftKey}function a(e){return function(t,n){return t||n?t&&!n?e+"--"+t:t&&n?e+"--"+t+"__"+n:!t&&n?e+"__"+n:void 0:e}}function s(e){var t=e.transformData,n=e.defaultTemplates,r=e.templates,o=e.templatesConfig,i=u(n,r);return c({transformData:t,templatesConfig:o},i)}function u(e,t){return l(e,function(e,n,r){var o=t&&void 0!==t[r]&&t[r]!==n;return o?(e.templates[r]=t[r],e.useCustomCompileOptions[r]=!0):(e.templates[r]=n,e.useCustomCompileOptions[r]=!1),e},{templates:{},useCustomCompileOptions:{}})}var c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l=n(111),p={getContainerNode:r,bemHelper:a,prepareTemplateProps:s,isSpecialClick:i,isDomElement:o};e.exports=p},function(e,t,n){var r;!function(){"use strict";function o(){for(var e="",t=0;t<arguments.length;t++){var n=arguments[t];if(n){var r=typeof n;if("string"===r||"number"===r)e+=" "+n;else if(Array.isArray(n))e+=" "+o.apply(null,n);else if("object"===r)for(var a in n)i.call(n,a)&&n[a]&&(e+=" "+a)}}return e.substr(1)}var i={}.hasOwnProperty;"undefined"!=typeof e&&e.exports?e.exports=o:(r=function(){return o}.call(t,n,t,e),!(void 0!==r&&(e.exports=r)))}()},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function i(e){var t=function(t){function n(){r(this,n),s(Object.getPrototypeOf(n.prototype),"constructor",this).apply(this,arguments)}return o(n,t),a(n,[{key:"componentDidMount",value:function(){this._hideOrShowContainer(this.props)}},{key:"componentWillReceiveProps",value:function(e){this._hideOrShowContainer(e)}},{key:"_hideOrShowContainer",value:function(e){var t=c.findDOMNode(this).parentNode;t.style.display=e.shouldAutoHideContainer===!0?"none":""}},{key:"render",value:function(){return this.props.shouldAutoHideContainer===!0?u.createElement("div",null):u.createElement(e,this.props)}}]),n}(u.Component);return t.propTypes={shouldAutoHideContainer:u.PropTypes.bool.isRequired},t.displayName=e.name+"-AutoHide",t}var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;return void 0===u?void 0:u.call(a)}var c=Object.getPrototypeOf(o);if(null===c)return void 0;e=c,t=i,n=a,r=!0,s=c=void 0}},u=n(217),c=n(369);e.exports=i},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function i(e){var t=function(t){function n(){r(this,n),u(Object.getPrototypeOf(n.prototype),"constructor",this).apply(this,arguments)}return o(n,t),s(n,[{key:"getTemplate",value:function(e){var t=this.props.templateProps.templates;if(!t||!t[e])return null;var n=l(this.props.cssClasses[e],"ais-"+e);return c.createElement(p,a({},this.props.templateProps,{cssClass:n,templateKey:e,transformData:null}))}},{key:"render",value:function(){var t={root:l(this.props.cssClasses.root),body:l(this.props.cssClasses.body)},n=this.getTemplate("header"),r=this.getTemplate("footer");return c.createElement("div",{className:t.root},n,c.createElement("div",{className:t.body},c.createElement(e,this.props)),r)}}]),n}(c.Component);return t.propTypes={cssClasses:c.PropTypes.shape({root:c.PropTypes.string,header:c.PropTypes.string,body:c.PropTypes.string,footer:c.PropTypes.string}),templateProps:c.PropTypes.object},t.defaultProps={cssClasses:{}},t.displayName=e.name+"-HeaderFooter",t}var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),u=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;return void 0===u?void 0:u.call(a)}var c=Object.getPrototypeOf(o);if(null===c)return void 0;e=c,t=i,n=a,r=!0,s=c=void 0}},c=n(217),l=n(371),p=n(374);e.exports=i},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function i(e,t,n){if(!e)return n;var r=void 0;if("function"==typeof e)r=e(n);else{if("object"!=typeof e)throw new Error("`transformData` must be a function or an object");r=e[t]?e[t](n):n}var o=typeof r,i=typeof n;if(o!==i)throw new Error("`transformData` must return a `"+i+"`, got `"+o+"`.");return r}function a(e){var t=e.template,n=e.compileOptions,r=e.helpers,o=e.data,i="string"==typeof t,a="function"==typeof t;if(i||a){if(a)return t(o);var c=s(r,n,o),l=u({},o,{helpers:c});return d.compile(t,n).render(l)}throw new Error("Template must be `string` or `function`")}function s(e,t,n){return f(e,function(e){return h(function(r){var o=this,i=function(e){return d.compile(e,t).render(o)};return e.call(n,r,i)})})}var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},c=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),l=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;return void 0===u?void 0:u.call(a)}var c=Object.getPrototypeOf(o);if(null===c)return void 0;e=c,t=i,n=a,r=!0,s=c=void 0}},p=n(217),f=n(209),h=n(375),d=n(377),v=function(e){function t(){r(this,t),l(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return o(t,e),c(t,[{key:"render",value:function(){var e=this.props.useCustomCompileOptions[this.props.templateKey]?this.props.templatesConfig.compileOptions:{},t=a({template:this.props.templates[this.props.templateKey],compileOptions:e,helpers:this.props.templatesConfig.helpers,data:i(this.props.transformData,this.props.templateKey,this.props.data)});return null===t?null:p.createElement("div",{className:this.props.cssClass,dangerouslySetInnerHTML:{__html:t}})}}]),t}(p.Component);v.propTypes={cssClass:p.PropTypes.string,data:p.PropTypes.object,templateKey:p.PropTypes.string,templates:p.PropTypes.objectOf(p.PropTypes.oneOfType([p.PropTypes.string,p.PropTypes.func])),templatesConfig:p.PropTypes.shape({helpers:p.PropTypes.objectOf(p.PropTypes.func),compileOptions:p.PropTypes.shape({asString:p.PropTypes.bool,sectionTags:p.PropTypes.arrayOf(p.PropTypes.shape({o:p.PropTypes.string,c:p.PropTypes.string})),delimiters:p.PropTypes.string,disableLambda:p.PropTypes.bool})}),transformData:p.PropTypes.oneOfType([p.PropTypes.func,p.PropTypes.objectOf(p.PropTypes.func)]),useCustomCompileOptions:p.PropTypes.objectOf(p.PropTypes.bool)},v.defaultProps={data:{},useCustomCompileOptions:{},templates:{},templatesConfig:{}},e.exports=v},function(e,t,n){var r=n(376),o=8,i=r(o);i.placeholder={},e.exports=i},function(e,t,n){function r(e){function t(n,r,a){a&&i(n,r,a)&&(r=void 0);var s=o(n,e,void 0,void 0,void 0,void 0,void 0,r);return s.placeholder=t.placeholder,s}return t}var o=n(160),i=n(52);e.exports=r},function(e,t,n){var r=n(378);r.Template=n(379).Template,r.template=r.Template,e.exports=r},function(e,t){!function(e){function t(e){"}"===e.n.substr(e.n.length-1)&&(e.n=e.n.substring(0,e.n.length-1))}function n(e){return e.trim?e.trim():e.replace(/^\s*|\s*$/g,"")}function r(e,t,n){if(t.charAt(n)!=e.charAt(0))return!1;for(var r=1,o=e.length;o>r;r++)if(t.charAt(n+r)!=e.charAt(r))return!1;return!0}function o(t,n,r,s){var u=[],c=null,l=null,p=null;for(l=r[r.length-1];t.length>0;){if(p=t.shift(),l&&"<"==l.tag&&!(p.tag in x))throw new Error("Illegal content in < super tag.");if(e.tags[p.tag]<=e.tags.$||i(p,s))r.push(p),p.nodes=o(t,p.tag,r,s);else{if("/"==p.tag){if(0===r.length)throw new Error("Closing tag without opener: /"+p.n);if(c=r.pop(),p.n!=c.n&&!a(p.n,c.n,s))throw new Error("Nesting error: "+c.n+" vs. "+p.n);return c.end=p.i,u}"\n"==p.tag&&(p.last=0==t.length||"\n"==t[0].tag)}u.push(p)}if(r.length>0)throw new Error("missing closing tag: "+r.pop().n);return u}function i(e,t){for(var n=0,r=t.length;r>n;n++)if(t[n].o==e.n)return e.tag="#",!0}function a(e,t,n){for(var r=0,o=n.length;o>r;r++)if(n[r].c==e&&n[r].o==t)return!0}function s(e){var t=[];for(var n in e)t.push('"'+c(n)+'": function(c,p,t,i) {'+e[n]+"}");return"{ "+t.join(",")+" }"}function u(e){var t=[];for(var n in e.partials)t.push('"'+c(n)+'":{name:"'+c(e.partials[n].name)+'", '+u(e.partials[n])+"}");return"partials: {"+t.join(",")+"}, subs: "+s(e.subs)}function c(e){return e.replace(y,"\\\\").replace(v,'\\"').replace(m,"\\n").replace(g,"\\r").replace(b,"\\u2028").replace(w,"\\u2029")}function l(e){return~e.indexOf(".")?"d":"f"}function p(e,t){var n="<"+(t.prefix||""),r=n+e.n+_++;return t.partials[r]={name:e.n,partials:{}},t.code+='t.b(t.rp("'+c(r)+'",c,p,"'+(e.indent||"")+'"));',r}function f(e,t){t.code+="t.b(t.t(t."+l(e.n)+'("'+c(e.n)+'",c,p,0)));'}function h(e){return"t.b("+e+");"}var d=/\S/,v=/\"/g,m=/\n/g,g=/\r/g,y=/\\/g,b=/\u2028/,w=/\u2029/;e.tags={"#":1,"^":2,"<":3,$:4,"/":5,"!":6,">":7,"=":8,_v:9,"{":10,"&":11,_t:12},e.scan=function(o,i){function a(){y.length>0&&(b.push({tag:"_t",text:new String(y)}),y="")}function s(){for(var t=!0,n=_;n<b.length;n++)if(t=e.tags[b[n].tag]<e.tags._v||"_t"==b[n].tag&&null===b[n].text.match(d),!t)return!1;return t}function u(e,t){if(a(),e&&s())for(var n,r=_;r<b.length;r++)b[r].text&&((n=b[r+1])&&">"==n.tag&&(n.indent=b[r].text.toString()),b.splice(r,1));else t||b.push({tag:"\n"});w=!1,_=b.length}function c(e,t){var r="="+C,o=e.indexOf(r,t),i=n(e.substring(e.indexOf("=",t)+1,o)).split(" ");return P=i[0],C=i[i.length-1],o+r.length-1}var l=o.length,p=0,f=1,h=2,v=p,m=null,g=null,y="",b=[],w=!1,x=0,_=0,P="{{",C="}}";for(i&&(i=i.split(" "),P=i[0],C=i[1]),x=0;l>x;x++)v==p?r(P,o,x)?(--x,a(),v=f):"\n"==o.charAt(x)?u(w):y+=o.charAt(x):v==f?(x+=P.length-1,g=e.tags[o.charAt(x+1)],m=g?o.charAt(x+1):"_v","="==m?(x=c(o,x),v=p):(g&&x++,v=h),w=x):r(C,o,x)?(b.push({tag:m,n:n(y),otag:P,ctag:C,i:"/"==m?w-P.length:x+C.length}),y="",x+=C.length-1,v=p,"{"==m&&("}}"==C?x++:t(b[b.length-1]))):y+=o.charAt(x);return u(w,!0),b};var x={_t:!0,"\n":!0,$:!0,"/":!0};e.stringify=function(t){return"{code: function (c,p,i) { "+e.wrapMain(t.code)+" },"+u(t)+"}"};var _=0;e.generate=function(t,n,r){_=0;var o={code:"",subs:{},partials:{}};return e.walk(t,o),r.asString?this.stringify(o,n,r):this.makeTemplate(o,n,r)},e.wrapMain=function(e){return'var t=this;t.b(i=i||"");'+e+"return t.fl();"},e.template=e.Template,e.makeTemplate=function(e,t,n){var r=this.makePartials(e);return r.code=new Function("c","p","i",this.wrapMain(e.code)),new this.template(r,t,this,n)},e.makePartials=function(e){var t,n={subs:{},partials:e.partials,name:e.name};for(t in n.partials)n.partials[t]=this.makePartials(n.partials[t]);for(t in e.subs)n.subs[t]=new Function("c","p","t","i",e.subs[t]);return n},e.codegen={"#":function(t,n){n.code+="if(t.s(t."+l(t.n)+'("'+c(t.n)+'",c,p,1),c,p,0,'+t.i+","+t.end+',"'+t.otag+" "+t.ctag+'")){t.rs(c,p,function(c,p,t){',e.walk(t.nodes,n),n.code+="});c.pop();}"},"^":function(t,n){n.code+="if(!t.s(t."+l(t.n)+'("'+c(t.n)+'",c,p,1),c,p,1,0,0,"")){',e.walk(t.nodes,n),n.code+="};"},">":p,"<":function(t,n){var r={partials:{},code:"",subs:{},inPartial:!0};e.walk(t.nodes,r);var o=n.partials[p(t,n)];o.subs=r.subs,o.partials=r.partials},$:function(t,n){var r={subs:{},code:"",partials:n.partials,prefix:t.n};e.walk(t.nodes,r),n.subs[t.n]=r.code,n.inPartial||(n.code+='t.sub("'+c(t.n)+'",c,p,i);')},"\n":function(e,t){t.code+=h('"\\n"'+(e.last?"":" + i"))},_v:function(e,t){t.code+="t.b(t.v(t."+l(e.n)+'("'+c(e.n)+'",c,p,0)));'},_t:function(e,t){t.code+=h('"'+c(e.text)+'"')},"{":f,"&":f},e.walk=function(t,n){for(var r,o=0,i=t.length;i>o;o++)r=e.codegen[t[o].tag],r&&r(t[o],n);return n},e.parse=function(e,t,n){return n=n||{},o(e,"",[],n.sectionTags||[])},e.cache={},e.cacheKey=function(e,t){return[e,!!t.asString,!!t.disableLambda,t.delimiters,!!t.modelGet].join("||")},e.compile=function(t,n){n=n||{};var r=e.cacheKey(t,n),o=this.cache[r];if(o){var i=o.partials;for(var a in i)delete i[a].instance;return o}return o=this.generate(this.parse(this.scan(t,n.delimiters),t,n),t,n),this.cache[r]=o}}(t)},function(e,t){!function(e){function t(e,t,n){var r;return t&&"object"==typeof t&&(void 0!==t[e]?r=t[e]:n&&t.get&&"function"==typeof t.get&&(r=t.get(e))),r}function n(e,t,n,r,o,i){function a(){}function s(){}a.prototype=e,s.prototype=e.subs;var u,c=new a;c.subs=new s,c.subsText={},c.buf="",r=r||{},c.stackSubs=r,c.subsText=i;for(u in t)r[u]||(r[u]=t[u]);for(u in r)c.subs[u]=r[u];o=o||{},c.stackPartials=o;for(u in n)o[u]||(o[u]=n[u]);for(u in o)c.partials[u]=o[u];return c}function r(e){return String(null===e||void 0===e?"":e)}function o(e){return e=r(e),l.test(e)?e.replace(i,"&amp;").replace(a,"&lt;").replace(s,"&gt;").replace(u,"&#39;").replace(c,"&quot;"):e}e.Template=function(e,t,n,r){e=e||{},this.r=e.code||this.r,this.c=n,this.options=r||{},this.text=t||"",this.partials=e.partials||{},this.subs=e.subs||{},this.buf=""},e.Template.prototype={r:function(){return""},v:o,t:r,render:function(e,t,n){return this.ri([e],t||{},n)},ri:function(e,t,n){return this.r(e,t,n)},ep:function(e,t){var r=this.partials[e],o=t[r.name];if(r.instance&&r.base==o)return r.instance;if("string"==typeof o){if(!this.c)throw new Error("No compiler available.");o=this.c.compile(o,this.options)}if(!o)return null;if(this.partials[e].base=o,r.subs){t.stackText||(t.stackText={});for(key in r.subs)t.stackText[key]||(t.stackText[key]=void 0!==this.activeSub&&t.stackText[this.activeSub]?t.stackText[this.activeSub]:this.text);o=n(o,r.subs,r.partials,this.stackSubs,this.stackPartials,t.stackText)}return this.partials[e].instance=o,o},rp:function(e,t,n,r){var o=this.ep(e,n);return o?o.ri(t,n,r):""},rs:function(e,t,n){var r=e[e.length-1];if(!p(r))return void n(e,t,this);for(var o=0;o<r.length;o++)e.push(r[o]),n(e,t,this),e.pop()},s:function(e,t,n,r,o,i,a){var s;return p(e)&&0===e.length?!1:("function"==typeof e&&(e=this.ms(e,t,n,r,o,i,a)),s=!!e,!r&&s&&t&&t.push("object"==typeof e?e:t[t.length-1]),s)},d:function(e,n,r,o){var i,a=e.split("."),s=this.f(a[0],n,r,o),u=this.options.modelGet,c=null;if("."===e&&p(n[n.length-2]))s=n[n.length-1];else for(var l=1;l<a.length;l++)i=t(a[l],s,u),void 0!==i?(c=s,s=i):s="";return o&&!s?!1:(o||"function"!=typeof s||(n.push(c),s=this.mv(s,n,r),n.pop()),s)},f:function(e,n,r,o){for(var i=!1,a=null,s=!1,u=this.options.modelGet,c=n.length-1;c>=0;c--)if(a=n[c],i=t(e,a,u),void 0!==i){s=!0;break}return s?(o||"function"!=typeof i||(i=this.mv(i,n,r)),i):o?!1:""},ls:function(e,t,n,o,i){var a=this.options.delimiters;return this.options.delimiters=i,this.b(this.ct(r(e.call(t,o)),t,n)),this.options.delimiters=a,!1},ct:function(e,t,n){if(this.options.disableLambda)throw new Error("Lambda features disabled.");return this.c.compile(e,this.options).render(t,n)},b:function(e){this.buf+=e},fl:function(){var e=this.buf;return this.buf="",e},ms:function(e,t,n,r,o,i,a){var s,u=t[t.length-1],c=e.call(u);return"function"==typeof c?r?!0:(s=this.activeSub&&this.subsText&&this.subsText[this.activeSub]?this.subsText[this.activeSub]:this.text,this.ls(c,u,n,s.substring(o,i),a)):c},mv:function(e,t,n){var o=t[t.length-1],i=e.call(o);return"function"==typeof i?this.ct(r(i.call(o)),o,n):i},sub:function(e,t,n,r){var o=this.subs[e];o&&(this.activeSub=e,o(t,n,this,r),this.activeSub=!1)}};var i=/&/g,a=/</g,s=/>/g,u=/\'/g,c=/\"/g,l=/[&<>\"\']/,p=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}}(t)},function(e){"use strict";e.exports={header:"",item:'<a class="{{cssClasses.link}}" href="{{url}}">{{name}} <span class="{{cssClasses.count}}">{{count}}</span></a>',footer:""}},function(e,t,n){"use strict";function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),u=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;return void 0===u?void 0:u.call(a)}var c=Object.getPrototypeOf(o);if(null===c)return void 0;e=c,t=i,n=a,r=!0,s=c=void 0}},c=n(217),l=n(371),p=n(374),f=n(370),h=f.isSpecialClick,d=function(e){function t(){o(this,t),u(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return i(t,e),s(t,[{key:"refine",value:function(e){this.props.toggleRefinement(e)}},{key:"_generateFacetItem",value:function(e){var n=void 0,o=e.data&&e.data.length>0;o&&(n=c.createElement(t,a({},this.props,{depth:this.props.depth+1,facetValues:e.data})));var i=e;this.props.createURL&&(i.url=this.props.createURL(e[this.props.facetNameKey]));var s=a({},e,{cssClasses:this.props.cssClasses}),u=l(this.props.cssClasses.item,r({},this.props.cssClasses.active,e.isRefined)),f=e[this.props.facetNameKey]+"/"+e.isRefined+"/"+e.count;return c.createElement("div",{className:u,key:f,onClick:this.handleClick.bind(this,e[this.props.facetNameKey])},c.createElement(p,a({data:s,templateKey:"item"},this.props.templateProps)),n)}},{key:"handleClick",value:function(e,t){if(!h(t)){if("INPUT"===t.target.tagName)return void this.refine(e);for(var n=t.target;n!==t.currentTarget;){if("LABEL"===n.tagName&&n.querySelector('input[type="checkbox"]'))return;"A"===n.tagName&&n.href&&t.preventDefault(),n=n.parentNode}t.stopPropagation(),this.refine(e)}}},{key:"render",value:function(){var e=[this.props.cssClasses.list];return this.props.cssClasses.depth&&e.push(""+this.props.cssClasses.depth+this.props.depth),c.createElement("div",{className:l(e)},this.props.facetValues.map(this._generateFacetItem,this))}}]),t}(c.Component);d.propTypes={Template:c.PropTypes.func,createURL:c.PropTypes.func.isRequired,cssClasses:c.PropTypes.shape({active:c.PropTypes.string,depth:c.PropTypes.string,item:c.PropTypes.string,list:c.PropTypes.string}),depth:c.PropTypes.number,facetNameKey:c.PropTypes.string,facetValues:c.PropTypes.array,templateProps:c.PropTypes.object.isRequired,toggleRefinement:c.PropTypes.func.isRequired},d.defaultProps={cssClasses:{},depth:0,facetNameKey:"name"},e.exports=d},function(e,t,n){"use strict";function r(e){var t=e.container,n=e.cssClasses,r=void 0===n?{}:n,p=e.templates,f=void 0===p?l:p,h=e.transformData,d=e.hitsPerPage,v=void 0===d?20:d,m=a.getContainerNode(t),g="Usage: hits({container, [cssClasses.{root,empty,item}, templates.{empty,item}, transformData.{empty,item}, hitsPerPage])";if(null===t)throw new Error(g);var y={root:u(s(null),r.root),item:u(s("item"),r.item),empty:u(s(null,"empty"),r.empty)};return{getConfiguration:function(){return{hitsPerPage:v}},render:function(e){var t=e.results,n=e.templatesConfig,r=a.prepareTemplateProps({transformData:h,defaultTemplates:l,templatesConfig:n,templates:f});i.render(o.createElement(c,{cssClasses:y,hits:t.hits,results:t,templateProps:r}),m)}}}var o=n(217),i=n(369),a=n(370),s=a.bemHelper("ais-hits"),u=n(371),c=n(383),l=n(384);e.exports=r},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;return void 0===u?void 0:u.call(a)}var c=Object.getPrototypeOf(o);if(null===c)return void 0;e=c,t=i,n=a,r=!0,s=c=void 0}},u=n(217),c=n(108),l=n(374),p=function(e){function t(){r(this,t),s(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return o(t,e),a(t,[{key:"renderWithResults",value:function(){var e=this,t=c(this.props.results.hits,function(t){return u.createElement(l,i({cssClass:e.props.cssClasses.item,data:t,key:t.objectID,templateKey:"item"},e.props.templateProps))});return u.createElement("div",{className:this.props.cssClasses.root},t)}},{key:"renderNoResults",value:function(){var e=this.props.cssClasses.root+" "+this.props.cssClasses.empty;return u.createElement(l,i({cssClass:e,data:this.props.results,templateKey:"empty"},this.props.templateProps))}},{key:"render",value:function(){return this.props.results.hits.length>0?this.renderWithResults():this.renderNoResults()}}]),t}(u.Component);p.propTypes={cssClasses:u.PropTypes.shape({root:u.PropTypes.string,item:u.PropTypes.string,empty:u.PropTypes.string}),results:u.PropTypes.object,templateProps:u.PropTypes.object.isRequired},p.defaultProps={results:{hits:[]}},e.exports=p},function(e){"use strict";e.exports={empty:"No results",item:function(e){return JSON.stringify(e,null,2)}}},function(e,t,n){"use strict";function r(e){var t=e.container,r=e.options,p=e.cssClasses,f=void 0===p?{}:p,h=e.hideContainerWhenNoResults,d=void 0===h?!1:h,v=a.getContainerNode(t),m="Usage: hitsPerPageSelector({container, options[, cssClasses.{root,item}, hideContainerWhenNoResults]})",g=n(386);if(d===!0&&(g=l(g)),!t||!r)throw new Error(m);return{init:function(e){var t=s(r,function(t,n){return t||+e.hitsPerPage===+n.value},!1);if(!t)throw new Error("[hitsPerPageSelector]: No option in `options` with `value: "+e.hitsPerPage+"`")},setHitsPerPage:function(e,t){e.setQueryParameter("hitsPerPage",+t),e.search()},render:function(e){var t=e.helper,n=e.state,a=e.results,s=n.hitsPerPage,l=0===a.nbHits,p=this.setHitsPerPage.bind(this,t),h={root:c(u(null),f.root),item:c(u("item"),f.item)};i.render(o.createElement(g,{cssClasses:h,currentValue:s,options:r,setValue:p,shouldAutoHideContainer:l}),v)}}}var o=n(217),i=n(369),a=n(370),s=n(111),u=a.bemHelper("ais-hits-per-page-selector"),c=n(371),l=n(372);e.exports=r},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),a=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;return void 0===u?void 0:u.call(a)}var c=Object.getPrototypeOf(o);if(null===c)return void 0;e=c,t=i,n=a,r=!0,s=c=void 0}},s=n(217),u=function(e){function t(){r(this,t),a(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return o(t,e),i(t,[{key:"handleChange",value:function(e){this.props.setValue(e.target.value)}},{key:"render",value:function(){var e=this,t=this.props,n=t.currentValue,r=t.options,o=this.handleChange.bind(this);return s.createElement("select",{className:this.props.cssClasses.root,onChange:o,value:n},r.map(function(t){return s.createElement("option",{className:e.props.cssClasses.item,key:t.value,value:t.value},t.label)}))}}]),t}(s.Component);u.propTypes={cssClasses:s.PropTypes.shape({root:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.arrayOf(s.PropTypes.string)]),item:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.arrayOf(s.PropTypes.string)])}),currentValue:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.number]).isRequired,options:s.PropTypes.arrayOf(s.PropTypes.shape({value:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.number]).isRequired,label:s.PropTypes.string.isRequired})).isRequired,setValue:s.PropTypes.func.isRequired},e.exports=u},function(e,t,n){"use strict";function r(e){var t=e.container,r=e.indices,f=e.cssClasses,h=void 0===f?{}:f,d=e.hideContainerWhenNoResults,v=void 0===d?!1:d,m=u.getContainerNode(t),g="Usage: indexSelector({container, indices[, cssClasses.{root,item}, hideContainerWhenNoResults]})",y=n(386);if(v===!0&&(y=p(y)),!t||!r)throw new Error(g);var b=s(r,function(e){return{label:e.label,value:e.name}});return{init:function(e,t){var n=t.getIndex(),o=-1!==a(r,{name:n});if(!o)throw new Error("[indexSelector]: Index "+n+" not present in `indices`")},setIndex:function(e,t){e.setIndex(t),e.search()},render:function(e){var t=e.helper,n=e.results,r=t.getIndex(),a=0===n.nbHits,s=this.setIndex.bind(this,t),u={root:l(c(null),h.root),item:l(c("item"),h.item)};i.render(o.createElement(y,{cssClasses:u,currentValue:r,options:b,setValue:s,shouldAutoHideContainer:a}),m)}}}var o=n(217),i=n(369),a=n(143),s=n(108),u=n(370),c=u.bemHelper("ais-index-selector"),l=n(371),p=n(372);e.exports=r},function(e,t,n){"use strict";function r(e){var t=e.container,r=e.facetName,d=e.sortBy,v=void 0===d?["count:desc"]:d,m=e.limit,g=void 0===m?100:m,y=e.cssClasses,b=void 0===y?{}:y,w=e.templates,x=void 0===w?h:w,_=e.transformData,P=e.hideContainerWhenNoResults,C=void 0===P?!0:P,E=u.getContainerNode(t),R="Usage: menu({container, facetName, [sortBy, limit, cssClasses.{root,list,item}, templates.{header,item,footer}, transformData, hideContainerWhenNoResults]})",T=f(n(381));if(C===!0&&(T=p(T)),!t||!r)throw new Error(R);var O=r;return{getConfiguration:function(){return{hierarchicalFacets:[{name:O,attributes:[r]}]}},render:function(e){var t=e.results,n=e.helper,r=e.templatesConfig,p=e.state,f=e.createURL,d=i(t,O,v,g),m=0===d.length,y=u.prepareTemplateProps({transformData:_,defaultTemplates:h,templatesConfig:r,templates:x}),w={root:l(c(null),b.root),header:l(c("header"),b.header), body:l(c("body"),b.body),footer:l(c("footer"),b.footer),list:l(c("list"),b.list),item:l(c("item"),b.item),active:l(c("item","active"),b.active),link:l(c("link"),b.link),count:l(c("count"),b.count)};s.render(a.createElement(T,{createURL:function(e){return f(p.toggleRefinement(O,e))},cssClasses:w,facetValues:d,shouldAutoHideContainer:m,templateProps:y,toggleRefinement:o.bind(null,n,O)}),E)}}}function o(e,t,n){e.toggleRefinement(t,n).search()}function i(e,t,n,r){var o=e.getFacetValues(t,{sortBy:n});return o.data&&o.data.slice(0,r)||[]}var a=n(217),s=n(369),u=n(370),c=u.bemHelper("ais-menu"),l=n(371),p=n(372),f=n(373),h=n(389);e.exports=r},function(e){"use strict";e.exports={header:"",item:'<a class="{{cssClasses.link}}" href="{{url}}">{{name}} <span class="{{cssClasses.count}}">{{count}}</span></a>',footer:""}},function(e,t,n){"use strict";function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e){var t=e.container,o=e.facetName,d=e.operator,v=void 0===d?"or":d,m=e.sortBy,g=void 0===m?["count:desc"]:m,y=e.limit,b=void 0===y?1e3:y,w=e.cssClasses,x=void 0===w?{}:w,_=e.templates,P=void 0===_?h:_,C=e.transformData,E=e.hideContainerWhenNoResults,R=void 0===E?!0:E,T=u.getContainerNode(t),O="Usage: refinementList({container, facetName, [operator, sortBy, limit, cssClasses.{root,header,body,footer,list,item,active,label,checkbox,count}, templates.{header,item,footer}, transformData, hideContainerWhenNoResults]})",S=f(n(381));if(R===!0&&(S=p(S)),!t||!o)throw new Error(O);if(v&&(v=v.toLowerCase(),"and"!==v&&"or"!==v))throw new Error(O);return{getConfiguration:function(e){var t=r({},"and"===v?"facets":"disjunctiveFacets",[o]);return(!e.maxValuesPerFacet||b>e.maxValuesPerFacet)&&(t.maxValuesPerFacet=b),t},render:function(e){var t=e.results,n=e.helper,r=e.templatesConfig,p=e.state,f=e.createURL,d=u.prepareTemplateProps({transformData:C,defaultTemplates:h,templatesConfig:r,templates:P}),v=t.getFacetValues(o,{sortBy:g}).slice(0,b),m=0===v.length,y={root:l(c(null),x.root),header:l(c("header"),x.header),body:l(c("body"),x.body),footer:l(c("footer"),x.footer),list:l(c("list"),x.list),item:l(c("item"),x.item),active:l(c("item","active"),x.active),label:l(c("label"),x.label),checkbox:l(c("checkbox"),x.checkbox),count:l(c("count"),x.count)};s.render(a.createElement(S,{createURL:function(e){return f(p.toggleRefinement(o,e))},cssClasses:y,facetValues:v,shouldAutoHideContainer:m,templateProps:d,toggleRefinement:i.bind(null,n,o)}),T)}}}function i(e,t,n){e.toggleRefinement(t,n).search()}var a=n(217),s=n(369),u=n(370),c=u.bemHelper("ais-refinement-list"),l=n(371),p=n(372),f=n(373),h=n(391);e.exports=o},function(e){"use strict";e.exports={header:"",item:'<label class="{{cssClasses.label}}">\n <input type="checkbox" class="{{cssClasses.checkbox}}" value="{{name}}" {{#isRefined}}checked{{/isRefined}} />{{name}}\n <span class="{{cssClasses.count}}">{{count}}</span>\n</label>',footer:""}},function(e,t,n){"use strict";function r(e){var t=e.container,r=e.cssClasses,f=void 0===r?{}:r,h=e.labels,d=void 0===h?{}:h,v=e.maxPages,m=void 0===v?20:v,g=e.padding,y=void 0===g?3:g,b=e.showFirstLast,w=void 0===b?!0:b,x=e.hideContainerWhenNoResults,_=void 0===x?!0:x,P=e.scrollTo,C=void 0===P?"body":P;C===!0&&(C="body");var E=u.getContainerNode(t),R=C!==!1?u.getContainerNode(C):!1,T=n(393);if(_===!0&&(T=l(T)),!t)throw new Error("Usage: pagination({container[, cssClasses.{root,item,page,previous,next,first,last,active,disabled}, labels.{previous,next,first,last}, maxPages, showFirstLast, hideContainerWhenNoResults]})");return d=a(d,p),{setCurrentPage:function(e,t){e.setCurrentPage(t),R!==!1&&R.scrollIntoView(),e.search()},render:function(e){var t=e.results,n=e.helper,r=e.createURL,a=e.state,u=t.page,l=t.nbPages,p=t.nbHits,h=0===p,v={root:s(c(null),f.root),item:s(c("item"),f.item),page:s(c("item"),c("item-page"),f.page),previous:s(c("item"),c("item-previous"),f.previous),next:s(c("item"),c("item-next"),f.next),first:s(c("item"),c("item-first"),f.first),last:s(c("item"),c("item-last"),f.last),active:s(c("item"),c("item-page"),c("item-page","active"),f.active),disabled:s(c("item"),c("item","disabled"),f.disabled)};void 0!==m&&(l=Math.min(m,t.nbPages)),i.render(o.createElement(T,{createURL:function(e){return r(a.setPage(e))},cssClasses:v,currentPage:u,labels:d,nbHits:p,nbPages:l,padding:y,setCurrentPage:this.setCurrentPage.bind(this,n),shouldAutoHideContainer:h,showFirstLast:w}),E)}}}var o=n(217),i=n(369),a=n(133),s=n(371),u=n(370),c=u.bemHelper("ais-pagination"),l=n(372),p={previous:"‹",next:"›",first:"«",last:"»"};e.exports=r},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),a=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;return void 0===u?void 0:u.call(a)}var c=Object.getPrototypeOf(o);if(null===c)return void 0;e=c,t=i,n=a,r=!0,s=c=void 0}},s=n(217),u=n(17),c=n(394),l=n(370),p=l.isSpecialClick,f=n(396),h=n(398),d=n(371),v=function(e){function t(e){r(this,t),a(Object.getPrototypeOf(t.prototype),"constructor",this).call(this,c(e,t.defaultProps))}return o(t,e),i(t,[{key:"handleClick",value:function(e,t){p(t)||(t.preventDefault(),this.props.setCurrentPage(e))}},{key:"pageLink",value:function(e){var t=e.label,n=e.ariaLabel,r=e.pageNumber,o=e.className,i=void 0===o?null:o,a=e.isDisabled,u=void 0===a?!1:a,c=e.isActive,l=void 0===c?!1:c,p=e.createURL,f=this.handleClick.bind(this,r);u?i=d(this.props.cssClasses.disabled,i):l&&(i=d(this.props.cssClasses.active,i));var v=p&&!u?p(r):"#";return s.createElement(h,{ariaLabel:n,className:i,handleClick:f,key:t,label:t,url:v})}},{key:"previousPageLink",value:function(e,t){return this.pageLink({ariaLabel:"Previous",className:this.props.cssClasses.previous,isDisabled:e.isFirstPage(),label:this.props.labels.previous,pageNumber:e.currentPage-1,createURL:t})}},{key:"nextPageLink",value:function(e,t){return this.pageLink({ariaLabel:"Next",className:this.props.cssClasses.next,isDisabled:e.isLastPage(),label:this.props.labels.next,pageNumber:e.currentPage+1,createURL:t})}},{key:"firstPageLink",value:function(e,t){return this.pageLink({ariaLabel:"First",className:this.props.cssClasses.first,isDisabled:e.isFirstPage(),label:this.props.labels.first,pageNumber:0,createURL:t})}},{key:"lastPageLink",value:function(e,t){return this.pageLink({ariaLabel:"Last",className:this.props.cssClasses.last,isDisabled:e.isLastPage(),label:this.props.labels.last,pageNumber:e.total-1,createURL:t})}},{key:"pages",value:function n(e,t){var r=this,n=[];return u(e.pages(),function(o){var i=o===e.currentPage;n.push(r.pageLink({ariaLabel:o+1,className:r.props.cssClasses.page,isActive:i,label:o+1,pageNumber:o,createURL:t}))}),n}},{key:"render",value:function(){var e=new f({currentPage:this.props.currentPage,total:this.props.nbPages,padding:this.props.padding}),t=this.props.createURL;return s.createElement("ul",{className:this.props.cssClasses.root},this.props.showFirstLast?this.firstPageLink(e,t):null,this.previousPageLink(e,t),this.pages(e,t),this.nextPageLink(e,t),this.props.showFirstLast?this.lastPageLink(e,t):null)}}]),t}(s.Component);v.propTypes={createURL:s.PropTypes.func,cssClasses:s.PropTypes.shape({root:s.PropTypes.string,item:s.PropTypes.string,page:s.PropTypes.string,previous:s.PropTypes.string,next:s.PropTypes.string,first:s.PropTypes.string,last:s.PropTypes.string,active:s.PropTypes.string,disabled:s.PropTypes.string}),currentPage:s.PropTypes.number,labels:s.PropTypes.shape({first:s.PropTypes.string,last:s.PropTypes.string,next:s.PropTypes.string,previous:s.PropTypes.string}),nbHits:s.PropTypes.number,nbPages:s.PropTypes.number,padding:s.PropTypes.number,setCurrentPage:s.PropTypes.func.isRequired,showFirstLast:s.PropTypes.bool},v.defaultProps={nbHits:0,currentPage:0,nbPages:0},e.exports=v},function(e,t,n){var r=n(137),o=n(53),i=n(395),a=r(o,i);e.exports=a},function(e,t,n){function r(e,t){return void 0===e?t:o(e,t,r)}var o=n(53);e.exports=r},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var o=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),i=n(397),a=function(){function e(t){r(this,e),this.currentPage=t.currentPage,this.total=t.total,this.padding=t.padding}return o(e,[{key:"pages",value:function(){var e=this.currentPage,t=this.padding,n=Math.min(this.calculatePaddingLeft(e,t,this.total),this.total),r=Math.max(Math.min(2*t+1,this.total)-n,1),o=Math.max(e-n,0),a=e+r;return i(o,a)}},{key:"calculatePaddingLeft",value:function(e,t,n){return t>=e?e:e>=n-t?2*t+1-(n-e):t}},{key:"isLastPage",value:function(){return this.currentPage===this.total-1}},{key:"isFirstPage",value:function(){return 0===this.currentPage}}]),e}();e.exports=a},function(e,t,n){function r(e,t,n){n&&o(e,t,n)&&(t=n=void 0),e=+e||0,n=null==n?1:+n||0,null==t?(t=e,e=0):t=+t||0;for(var r=-1,s=a(i((t-e)/(n||1)),0),u=Array(s);++r<s;)u[r]=e,e+=n;return u}var o=n(52),i=Math.ceil,a=Math.max;e.exports=r},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),a=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;return void 0===u?void 0:u.call(a)}var c=Object.getPrototypeOf(o);if(null===c)return void 0;e=c,t=i,n=a,r=!0,s=c=void 0}},s=n(217),u=function(e){function t(){r(this,t),a(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return o(t,e),i(t,[{key:"render",value:function(){var e=this.props,t=e.className,n=e.label,r=e.ariaLabel,o=e.handleClick,i=e.url;return s.createElement("li",{className:t},s.createElement("a",{ariaLabel:r,className:t,dangerouslySetInnerHTML:{__html:n},href:i,onClick:o}))}}]),t}(s.Component);u.propTypes={ariaLabel:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.number]).isRequired,className:s.PropTypes.string,handleClick:s.PropTypes.func.isRequired,label:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.number]).isRequired,url:s.PropTypes.string},e.exports=u},function(e,t,n){"use strict";function r(e){var t=e.container,r=e.attributeName,h=e.cssClasses,d=void 0===h?{}:h,v=e.templates,m=void 0===v?u:v,g=e.labels,y=void 0===g?{currency:"$",button:"Go",separator:"to"}:g,b=e.hideContainerWhenNoResults,w=void 0===b?!0:b,x=a.getContainerNode(t),_="Usage: priceRanges({container, attributeName, [cssClasses.{root,header,body,list,item,active,link,form,label,input,currency,separator,button,footer}, templates.{header,item,footer}, labels.{currency,separator,button}, hideContainerWhenNoResults]})",P=l(n(402));if(w===!0&&(P=c(P)),!t||!r)throw new Error(_);return{getConfiguration:function(){return{facets:[r]}},_generateRanges:function(e){var t=e.getFacetStats(r);return s(t)},_extractRefinedRange:function(e){var t=e.getRefinements(r),n=void 0,o=void 0;return 0===t.length?[]:(t.forEach(function(e){-1!==e.operator.indexOf(">")?n=e.value[0]+1:-1!==e.operator.indexOf("<")&&(o=e.value[0]-1)}),[{from:n,to:o,isRefined:!0}])},_refine:function(e,t,n){var o=this._extractRefinedRange(e);e.clearRefinements(r),(0===o.length||o[0].from!==t||o[0].to!==n)&&("undefined"!=typeof t&&e.addNumericRefinement(r,">",t-1),"undefined"!=typeof n&&e.addNumericRefinement(r,"<",n+1)),e.search()},render:function(e){var t=e.results,n=e.helper,s=e.templatesConfig,c=e.state,l=e.createURL,h=0===t.nbHits,v=void 0;t.hits.length>0?(v=this._extractRefinedRange(n),0===v.length&&(v=this._generateRanges(t))):v=[];var g=a.prepareTemplateProps({defaultTemplates:u,templatesConfig:s,templates:m}),b={root:f(p(null),d.root),header:f(p("header"),d.header),body:f(p("body"),d.body),list:f(p("list"),d.list),link:f(p("link"),d.link),item:f(p("item"),d.item),active:f(p("item","active"),d.active),form:f(p("form"),d.form),label:f(p("label"),d.label),input:f(p("input"),d.input),currency:f(p("currency"),d.currency),button:f(p("button"),d.button),separator:f(p("separator"),d.separator),footer:f(p("footer"),d.footer)};i.render(o.createElement(P,{createURL:function(e,t,n){var o=c.clearRefinements(r);return n||("undefined"!=typeof e&&(o=o.addNumericRefinement(r,">",e-1)),"undefined"!=typeof t&&(o=o.addNumericRefinement(r,"<",t+1))),l(o)},cssClasses:b,facetValues:v,labels:y,refine:this._refine.bind(this,n),shouldAutoHideContainer:h,templateProps:g}),x)}}}var o=n(217),i=n(369),a=n(370),s=n(400),u=n(401),c=n(372),l=n(373),p=a.bemHelper("ais-price-ranges"),f=n(371);e.exports=r},function(e){"use strict";function t(e,t){var n=Math.round(e/t)*t;return 1>n&&(n=1),n}function n(e){var n=void 0;n=e.avg<100?1:e.avg<1e3?10:100;for(var r=t(Math.round(e.avg),n),o=Math.ceil(e.min),i=t(Math.floor(e.max),n);i>e.max;)i-=n;var a=void 0,s=void 0,u=[];if(o!==i){for(a=t(o,n),u.push({to:a});r>a;)s=u[u.length-1].to,a=t(s+(r-o)/3,n),s>=a&&(a=s+1),u.push({from:s,to:a});for(;i>a;)s=u[u.length-1].to,a=t(s+(i-r)/3,n),s>=a&&(a=s+1),u.push({from:s,to:a});1===u.length&&a!==r&&(u.push({from:a,to:r}),a=r),1===u.length?(u[0].from=e.min,u[0].to=e.max):delete u[u.length-1].to}return u}e.exports=n},function(e){"use strict";e.exports={header:"",item:"\n {{#from}}\n {{^to}}\n &ge;\n {{/to}}\n ${{from}}\n {{/from}}\n {{#to}}\n {{#from}}\n -\n {{/from}}\n {{^from}}\n &le;\n {{/from}}\n ${{to}}\n {{/to}}\n ",footer:""}},function(e,t,n){"use strict";function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),u=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;return void 0===u?void 0:u.call(a)}var c=Object.getPrototypeOf(o);if(null===c)return void 0;e=c,t=i,n=a,r=!0,s=c=void 0}},c=n(217),l=n(374),p=n(403),f=n(371),h=function(e){function t(){o(this,t),u(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return i(t,e),s(t,[{key:"getForm",value:function(){return c.createElement(p,{cssClasses:this.props.cssClasses,labels:this.props.labels,refine:this.refine.bind(this)})}},{key:"getURLFromFacetValue",value:function(e){return this.props.createURL?this.props.createURL(e.from,e.to,e.isRefined):"#"}},{key:"getItemFromFacetValue",value:function(e){var t=f(this.props.cssClasses.item,r({},this.props.cssClasses.active,e.isRefined)),n=this.getURLFromFacetValue(e),o=e.from+"_"+e.to,i=this.refine.bind(this,e.from,e.to);return c.createElement("div",{className:t,key:o},c.createElement("a",{className:this.props.cssClasses.link,href:n,onClick:i},c.createElement(l,a({data:e,templateKey:"item"},this.props.templateProps))))}},{key:"refine",value:function(e,t,n){n.preventDefault(),this.setState({formFromValue:null,formToValue:null}),this.props.refine(e,t)}},{key:"render",value:function(){var e=this,t=this.getForm();return c.createElement("div",null,c.createElement("div",{className:this.props.cssClasses.list},this.props.facetValues.map(function(t){return e.getItemFromFacetValue(t)})),t)}}]),t}(c.Component);h.propTypes={createURL:c.PropTypes.func.isRequired,cssClasses:c.PropTypes.shape({active:c.PropTypes.string,button:c.PropTypes.string,form:c.PropTypes.string,input:c.PropTypes.string,item:c.PropTypes.string,label:c.PropTypes.string,link:c.PropTypes.string,list:c.PropTypes.string,separator:c.PropTypes.string}),facetValues:c.PropTypes.array,labels:c.PropTypes.shape({button:c.PropTypes.string,currency:c.PropTypes.string,to:c.PropTypes.string}),refine:c.PropTypes.func.isRequired,templateProps:c.PropTypes.object.isRequired},h.defaultProps={cssClasses:{}},e.exports=h},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),a=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;return void 0===u?void 0:u.call(a)}var c=Object.getPrototypeOf(o);if(null===c)return void 0;e=c,t=i,n=a,r=!0,s=c=void 0}},s=n(217),u=function(e){function t(){r(this,t),a(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return o(t,e),i(t,[{key:"getInput",value:function(e){return s.createElement("label",{className:this.props.cssClasses.label},s.createElement("span",{className:this.props.cssClasses.currency},this.props.labels.currency," "),s.createElement("input",{className:this.props.cssClasses.input,ref:e,type:"number"}))}},{key:"handleSubmit",value:function(e){var t=+this.refs.from.value||void 0,n=+this.refs.to.value||void 0;this.props.refine(t,n,e)}},{key:"render",value:function(){var e=this.getInput("from"),t=this.getInput("to"),n=this.handleSubmit.bind(this);return s.createElement("form",{className:this.props.cssClasses.form,onSubmit:n,ref:"form"},e,s.createElement("span",{className:this.props.cssClasses.separator}," ",this.props.labels.separator," "),t,s.createElement("button",{className:this.props.cssClasses.button,type:"submit"},this.props.labels.button))}}]),t}(s.Component);u.propTypes={cssClasses:s.PropTypes.shape({button:s.PropTypes.string,currency:s.PropTypes.string,form:s.PropTypes.string,input:s.PropTypes.string,label:s.PropTypes.string,separator:s.PropTypes.string}),labels:s.PropTypes.shape({button:s.PropTypes.string,currency:s.PropTypes.string,separator:s.PropTypes.string}),refine:s.PropTypes.func.isRequired},u.defaultProps={cssClasses:{},labels:{}},e.exports=u},function(e,t,n){"use strict";function r(e){var t=e.container,r=e.placeholder,l=void 0===r?"":r,p=e.cssClasses,f=void 0===p?{}:p,h=e.poweredBy,d=void 0===h?!1:h,v=e.wrapInput,m=void 0===v?!0:v,g=e.autofocus,y=void 0===g?"auto":g;if(!t)throw new Error("Usage: searchBox({container[, placeholder, cssClasses.{input,poweredBy}, poweredBy, wrapInput, autofocus]})");return t=a.getContainerNode(t),"boolean"!=typeof y&&(y="auto"),{getInput:function(){return"INPUT"===t.tagName?t:document.createElement("input")},wrapInput:function(e){var t=document.createElement("div");return t.classList.add(c(u(null),f.root)),t.appendChild(e),t},addDefaultAttributesToInput:function(e,t){var n={autocapitalize:"off",autocomplete:"off",autocorrect:"off",placeholder:l,role:"textbox",spellcheck:"false",type:"text",value:t};s(n,function(t,n){e.hasAttribute(n)||e.setAttribute(n,t)}),e.classList.add(c(u("input"),f.input))},addPoweredBy:function(e){var t=n(405),r=document.createElement("div");e.parentNode.insertBefore(r,e.nextSibling);var a={root:c(u("powered-by"),f.poweredBy),link:u("powered-by-link")};i.render(o.createElement(t,{cssClasses:a}),r)},init:function(e,n){var r="INPUT"===t.tagName,o=this.getInput();if(this.addDefaultAttributesToInput(o,e.query),o.addEventListener("keyup",function(){n.setQuery(o.value).search()}),r){var i=document.createElement("div");o.parentNode.insertBefore(i,o);var a=o.parentNode,s=m?this.wrapInput(o):o;a.replaceChild(s,i)}else{var s=m?this.wrapInput(o):o;t.appendChild(s)}d&&this.addPoweredBy(o),n.on("change",function(e){o!==document.activeElement&&o.value!==e.query&&(o.value=e.query)}),(y===!0||"auto"===y&&""===n.state.query)&&o.focus()}}}var o=n(217),i=n(369),a=n(370),s=n(17),u=n(370).bemHelper("ais-search-box"),c=n(371);e.exports=r},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),a=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;return void 0===u?void 0:u.call(a)}var c=Object.getPrototypeOf(o);if(null===c)return void 0;e=c,t=i,n=a,r=!0,s=c=void 0}},s=n(217),u=function(e){function t(){r(this,t),a(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return o(t,e),i(t,[{key:"render",value:function(){return s.createElement("div",{className:this.props.cssClasses.root},"Powered by",s.createElement("a",{className:this.props.cssClasses.link,href:"https://www.algolia.com/",target:"_blank"},"Algolia"))}}]),t}(s.Component);u.propTypes={cssClasses:s.PropTypes.shape({root:s.PropTypes.string,link:s.PropTypes.string})},e.exports=u},function(e,t,n){"use strict";function r(e){var t=e.container,r=void 0===t?null:t,l=e.attributeName,p=void 0===l?null:l,f=e.tooltips,h=void 0===f?!0:f,d=e.templates,v=void 0===d?c:d,m=e.cssClasses,g=void 0===m?{root:null,body:null}:m,y=e.step,b=void 0===y?1:y,w=e.pips,x=void 0===w?!0:w,_=e.hideContainerWhenNoResults,P=void 0===_?!0:_,C=a.getContainerNode(r),E=u(n(407));return P===!0&&(E=s(E)),{getConfiguration:function(){return{disjunctiveFacets:[p]}},_getCurrentRefinement:function(e){var t=e.state.getNumericRefinement(p,">="),n=e.state.getNumericRefinement(p,"<=");return t=t&&t.length?t[0]:-(1/0),n=n&&n.length?n[0]:1/0,{min:t,max:n}},_refine:function(e,t,n){e.clearRefinements(p),n[0]>t.min&&e.addNumericRefinement(p,">=",n[0]),n[1]<t.max&&e.addNumericRefinement(p,"<=",n[1]),e.search()},render:function(e){var t=e.results,n=e.helper,r=e.templatesConfig,s=t.getFacetStats(p),u=this._getCurrentRefinement(n);void 0===s&&(s={min:null,max:null});var l=null===s.min&&null===s.max,f=a.prepareTemplateProps({defaultTemplates:c,templatesConfig:r,templates:v});i.render(o.createElement(E,{cssClasses:g,onChange:this._refine.bind(this,n,s),pips:x,range:{min:Math.floor(s.min),max:Math.ceil(s.max)},shouldAutoHideContainer:l,start:[u.min,u.max],step:b,templateProps:f,tooltips:h}),C)}}}var o=n(217),i=n(369),a=n(370),s=n(372),u=n(373),c={header:"",footer:""};e.exports=r},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;return void 0===u?void 0:u.call(a)}var c=Object.getPrototypeOf(o);if(null===c)return void 0;e=c,t=i,n=a,r=!0,s=c=void 0}},u=n(217),c=n(408),l="ais-range-slider--",p=function(e){function t(){r(this,t),s(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return o(t,e),a(t,[{key:"handleChange",value:function(e,t,n){this.props.onChange(n)}},{key:"render",value:function(){var e=void 0;return e=this.props.pips===!1?void 0:this.props.pips===!0||"undefined"==typeof this.props.pips?{mode:"positions",density:3,values:[0,50,100],stepped:!0,format:{to:function(e){return Number(e).toLocaleString()}}}:this.props.pips,u.createElement(c,i({},this.props,{animate:!1,behaviour:"snap",connect:!0,cssPrefix:l,onChange:this.handleChange.bind(this),pips:e}))}}]),t}(u.Component);p.propTypes={onChange:u.PropTypes.func,onSlide:u.PropTypes.func,pips:u.PropTypes.object,range:u.PropTypes.object.isRequired,start:u.PropTypes.arrayOf(u.PropTypes.number).isRequired,tooltips:u.PropTypes.oneOfType([u.PropTypes.bool,u.PropTypes.object])},e.exports=p},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),u=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;return void 0===u?void 0:u.call(a)}var c=Object.getPrototypeOf(o);if(null===c)return void 0;e=c,t=i,n=a,r=!0,s=c=void 0}},c=n(217),l=r(c),p=n(409),f=r(p),h=function(e){function t(){o(this,t),u(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return i(t,e),s(t,[{key:"componentDidMount",value:function(){var e=this.slider=f["default"].create(this.sliderContainer,a({},this.props));this.props.onUpdate&&e.on("update",this.props.onUpdate),this.props.onChange&&e.on("change",this.props.onChange)}},{key:"componentWillReceiveProps",value:function(e){this.slider.updateOptions(a({},this.props)),this.slider.set(e.start)}},{key:"componentWillUnmount",value:function(){this.slider.destroy()}},{key:"render",value:function(){var e=this;return l["default"].createElement("div",{ref:function(t){e.sliderContainer=t}})}}]),t}(l["default"].Component);h.propTypes={animate:l["default"].PropTypes.bool,connect:l["default"].PropTypes.oneOfType([l["default"].PropTypes.oneOf(["lower","upper"]),l["default"].PropTypes.bool]),cssPrefix:l["default"].PropTypes.string,direction:l["default"].PropTypes.oneOf(["ltr","rtl"]),limit:l["default"].PropTypes.number,margin:l["default"].PropTypes.number,onChange:l["default"].PropTypes.func,onUpdate:l["default"].PropTypes.func,orientation:l["default"].PropTypes.oneOf(["horizontal","vertical"]),pips:l["default"].PropTypes.object,range:l["default"].PropTypes.object.isRequired,start:l["default"].PropTypes.arrayOf(l["default"].PropTypes.number).isRequired,step:l["default"].PropTypes.number,tooltips:l["default"].PropTypes.oneOfType([l["default"].PropTypes.bool,l["default"].PropTypes.object])},e.exports=h},function(e,t,n){var r,o,i;(function(n){!function(n){o=[],r=n,i="function"==typeof r?r.apply(t,o):r,!(void 0!==i&&(e.exports=i))}(function(){"use strict";function e(e){return e.filter(function(e){return this[e]?!1:this[e]=!0},{})}function t(e,t){return Math.round(e/t)*t}function r(e){var t=e.getBoundingClientRect(),n=e.ownerDocument,r=n.documentElement,o=h();return/webkit.*Chrome.*Mobile/i.test(navigator.userAgent)&&(o.x=0),{top:t.top+o.y-r.clientTop,left:t.left+o.x-r.clientLeft}}function o(e){return"number"==typeof e&&!isNaN(e)&&isFinite(e)}function i(e){var t=Math.pow(10,7);return Number((Math.round(e*t)/t).toFixed(7))}function a(e,t,n){l(e,t),setTimeout(function(){p(e,t)},n)}function s(e){return Math.max(Math.min(e,100),0)}function u(e){return Array.isArray(e)?e:[e]}function c(e){var t=e.split(".");return t.length>1?t[1].length:0}function l(e,t){e.classList?e.classList.add(t):e.className+=" "+t}function p(e,t){e.classList?e.classList.remove(t):e.className=e.className.replace(new RegExp("(^|\\b)"+t.split(" ").join("|")+"(\\b|$)","gi")," ")}function f(e,t){e.classList?e.classList.contains(t):new RegExp("(^| )"+t+"( |$)","gi").test(e.className)}function h(){var e=void 0!==window.pageXOffset,t="CSS1Compat"===(document.compatMode||""),n=e?window.pageXOffset:t?document.documentElement.scrollLeft:document.body.scrollLeft,r=e?window.pageYOffset:t?document.documentElement.scrollTop:document.body.scrollTop;return{x:n,y:r}}function d(e){return function(t){return e+t}}function v(e,t,r,o){function i(e,r){if(null===e)return null;if(0==r)return e;var a,l;if("object"!=typeof e)return e;if(v.__isArray(e))a=[];else if(v.__isRegExp(e))a=new RegExp(e.source,w(e)),e.lastIndex&&(a.lastIndex=e.lastIndex);else if(v.__isDate(e))a=new Date(e.getTime());else{if(c&&n.isBuffer(e))return a=new n(e.length),e.copy(a),a;"undefined"==typeof o?(l=Object.getPrototypeOf(e),a=Object.create(l)):(a=Object.create(o),l=o)}if(t){var p=s.indexOf(e);if(-1!=p)return u[p];s.push(e),u.push(a)}for(var f in e){var h;l&&(h=Object.getOwnPropertyDescriptor(l,f)),h&&null==h.set||(a[f]=i(e[f],r-1))}return a}var a;"object"==typeof t&&(r=t.depth,o=t.prototype, a=t.filter,t=t.circular);var s=[],u=[],c="undefined"!=typeof n;return"undefined"==typeof t&&(t=!0),"undefined"==typeof r&&(r=1/0),i(e,r)}function m(e){return Object.prototype.toString.call(e)}function g(e){return"object"==typeof e&&"[object Date]"===m(e)}function y(e){return"object"==typeof e&&"[object Array]"===m(e)}function b(e){return"object"==typeof e&&"[object RegExp]"===m(e)}function w(e){var t="";return e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),t}function x(e,t){return 100/(t-e)}function _(e,t){return 100*t/(e[1]-e[0])}function P(e,t){return _(e,e[0]<0?t+Math.abs(e[0]):t-e[0])}function C(e,t){return t*(e[1]-e[0])/100+e[0]}function E(e,t){for(var n=1;e>=t[n];)n+=1;return n}function R(e,t,n){if(n>=e.slice(-1)[0])return 100;var r,o,i,a,s=E(n,e);return r=e[s-1],o=e[s],i=t[s-1],a=t[s],i+P([r,o],n)/x(i,a)}function T(e,t,n){if(n>=100)return e.slice(-1)[0];var r,o,i,a,s=E(n,t);return r=e[s-1],o=e[s],i=t[s-1],a=t[s],C([r,o],(n-i)*x(i,a))}function O(e,n,r,o){if(100===o)return o;var i,a,s=E(o,e);return r?(i=e[s-1],a=e[s],o-i>(a-i)/2?a:i):n[s-1]?e[s-1]+t(o-e[s-1],n[s-1]):o}function S(e,t,n){var r;if("number"==typeof t&&(t=[t]),"[object Array]"!==Object.prototype.toString.call(t))throw new Error("noUiSlider: 'range' contains invalid value.");if(r="min"===e?0:"max"===e?100:parseFloat(e),!o(r)||!o(t[0]))throw new Error("noUiSlider: 'range' value isn't numeric.");n.xPct.push(r),n.xVal.push(t[0]),r?n.xSteps.push(isNaN(t[1])?!1:t[1]):isNaN(t[1])||(n.xSteps[0]=t[1])}function N(e,t,n){return t?void(n.xSteps[e]=_([n.xVal[e],n.xVal[e+1]],t)/x(n.xPct[e],n.xPct[e+1])):!0}function j(e,t,n,r){this.xPct=[],this.xVal=[],this.xSteps=[r||!1],this.xNumSteps=[!1],this.snap=t,this.direction=n;var o,i=[];for(o in e)e.hasOwnProperty(o)&&i.push([e[o],o]);for(i.sort(i.length&&"object"==typeof i[0][0]?function(e,t){return e[0][0]-t[0][0]}:function(e,t){return e[0]-t[0]}),o=0;o<i.length;o++)S(i[o][1],i[o][0],this);for(this.xNumSteps=this.xSteps.slice(0),o=0;o<this.xNumSteps.length;o++)N(o,this.xNumSteps[o],this)}function k(e,t){if(!o(t))throw new Error("noUiSlider: 'step' is not numeric.");e.singleStep=t}function I(e,t){if("object"!=typeof t||Array.isArray(t))throw new Error("noUiSlider: 'range' is not an object.");if(void 0===t.min||void 0===t.max)throw new Error("noUiSlider: Missing 'min' or 'max' in 'range'.");e.spectrum=new j(t,e.snap,e.dir,e.singleStep)}function D(e,t){if(t=u(t),!Array.isArray(t)||!t.length||t.length>2)throw new Error("noUiSlider: 'start' option is incorrect.");e.handles=t.length,e.start=t}function A(e,t){if(e.snap=t,"boolean"!=typeof t)throw new Error("noUiSlider: 'snap' option must be a boolean.")}function M(e,t){if(e.animate=t,"boolean"!=typeof t)throw new Error("noUiSlider: 'animate' option must be a boolean.")}function F(e,t){if("lower"===t&&1===e.handles)e.connect=1;else if("upper"===t&&1===e.handles)e.connect=2;else if(t===!0&&2===e.handles)e.connect=3;else{if(t!==!1)throw new Error("noUiSlider: 'connect' option doesn't match handle count.");e.connect=0}}function U(e,t){switch(t){case"horizontal":e.ort=0;break;case"vertical":e.ort=1;break;default:throw new Error("noUiSlider: 'orientation' option is invalid.")}}function L(e,t){if(!o(t))throw new Error("noUiSlider: 'margin' option must be numeric.");if(e.margin=e.spectrum.getMargin(t),!e.margin)throw new Error("noUiSlider: 'margin' option is only supported on linear sliders.")}function B(e,t){if(!o(t))throw new Error("noUiSlider: 'limit' option must be numeric.");if(e.limit=e.spectrum.getMargin(t),!e.limit)throw new Error("noUiSlider: 'limit' option is only supported on linear sliders.")}function q(e,t){switch(t){case"ltr":e.dir=0;break;case"rtl":e.dir=1,e.connect=[0,2,1,3][e.connect];break;default:throw new Error("noUiSlider: 'direction' option was not recognized.")}}function H(e,t){if("string"!=typeof t)throw new Error("noUiSlider: 'behaviour' must be a string containing options.");var n=t.indexOf("tap")>=0,r=t.indexOf("drag")>=0,o=t.indexOf("fixed")>=0,i=t.indexOf("snap")>=0;if(r&&!e.connect)throw new Error("noUiSlider: 'drag' behaviour must be used with 'connect': true.");e.events={tap:n||i,drag:r,fixed:o,snap:i}}function V(e,t){if(t===!0&&(e.tooltips=!0),t&&t.format){if("function"!=typeof t.format)throw new Error("noUiSlider: 'tooltips.format' must be an object.");e.tooltips={format:t.format}}}function W(e,t){if(e.format=t,"function"==typeof t.to&&"function"==typeof t.from)return!0;throw new Error("noUiSlider: 'format' requires 'to' and 'from' methods.")}function K(e,t){if(void 0!==t&&"string"!=typeof t)throw new Error("noUiSlider: 'cssPrefix' must be a string.");e.cssPrefix=t}function Q(e){var t,n={margin:0,limit:0,animate:!0,format:J};t={step:{r:!1,t:k},start:{r:!0,t:D},connect:{r:!0,t:F},direction:{r:!0,t:q},snap:{r:!1,t:A},animate:{r:!1,t:M},range:{r:!0,t:I},orientation:{r:!1,t:U},margin:{r:!1,t:L},limit:{r:!1,t:B},behaviour:{r:!0,t:H},format:{r:!1,t:W},tooltips:{r:!1,t:V},cssPrefix:{r:!1,t:K}};var r={connect:!1,direction:"ltr",behaviour:"tap",orientation:"horizontal"};return Object.keys(r).forEach(function(t){void 0===e[t]&&(e[t]=r[t])}),Object.keys(t).forEach(function(r){var o=t[r];if(void 0===e[r]){if(o.r)throw new Error("noUiSlider: '"+r+"' is required.");return!0}o.t(n,e[r])}),n.pips=e.pips,n.style=n.ort?"top":"left",n}function Y(t,n){function o(e,t,n){var r=e+t[0],o=e+t[1];return n?(0>r&&(o+=Math.abs(r)),o>100&&(r-=o-100),[s(r),s(o)]):[r,o]}function i(e,t){e.preventDefault();var n,r,o=0===e.type.indexOf("touch"),i=0===e.type.indexOf("mouse"),a=0===e.type.indexOf("pointer"),s=e;return 0===e.type.indexOf("MSPointer")&&(a=!0),o&&(n=e.changedTouches[0].pageX,r=e.changedTouches[0].pageY),t=t||h(),(i||a)&&(n=e.clientX+t.x,r=e.clientY+t.y),s.pageOffset=t,s.points=[n,r],s.cursor=i||a,s}function v(e,t){var n=document.createElement("div"),r=document.createElement("div"),o=["-lower","-upper"];return e&&o.reverse(),l(r,ee[3]),l(r,ee[3]+o[t]),l(n,ee[2]),n.appendChild(r),n}function m(e,t,n){switch(e){case 1:l(t,ee[7]),l(n[0],ee[6]);break;case 3:l(n[1],ee[6]);case 2:l(n[0],ee[7]);case 0:l(t,ee[6])}}function g(e,t,n){var r,o=[];for(r=0;e>r;r+=1)o.push(n.appendChild(v(t,r)));return o}function y(e,t,n){l(n,ee[0]),l(n,ee[8+e]),l(n,ee[4+t]);var r=document.createElement("div");return l(r,ee[1]),n.appendChild(r),r}function b(e){return e}function w(e){var t=document.createElement("div");return t.className=ee[18],e.firstChild.appendChild(t)}function x(e){var t=e.format?e.format:b,n=K.map(w);q("update",function(e,r,o){n[r].innerHTML=t(e[r],o[r])})}function _(e,t,n){if("range"===e||"steps"===e)return J.xVal;if("count"===e){var r,o=100/(t-1),i=0;for(t=[];(r=i++*o)<=100;)t.push(r);e="positions"}return"positions"===e?t.map(function(e){return J.fromStepping(n?J.getStep(e):e)}):"values"===e?n?t.map(function(e){return J.fromStepping(J.getStep(J.toStepping(e)))}):t:void 0}function P(t,n,r){function o(e,t){return(e+t).toFixed(7)/1}var i=J.direction,a={},s=J.xVal[0],u=J.xVal[J.xVal.length-1],c=!1,l=!1,p=0;return J.direction=0,r=e(r.slice().sort(function(e,t){return e-t})),r[0]!==s&&(r.unshift(s),c=!0),r[r.length-1]!==u&&(r.push(u),l=!0),r.forEach(function(e,i){var s,u,f,h,d,v,m,g,y,b,w=e,x=r[i+1];if("steps"===n&&(s=J.xNumSteps[i]),s||(s=x-w),w!==!1&&void 0!==x)for(u=w;x>=u;u=o(u,s)){for(h=J.toStepping(u),d=h-p,g=d/t,y=Math.round(g),b=d/y,f=1;y>=f;f+=1)v=p+f*b,a[v.toFixed(5)]=["x",0];m=r.indexOf(u)>-1?1:"steps"===n?2:0,!i&&c&&(m=0),u===x&&l||(a[h.toFixed(5)]=[u,m]),p=h}}),J.direction=i,a}function C(e,t,r){function o(e){return["-normal","-large","-sub"][e]}function i(e,t,r){return'class="'+t+" "+t+"-"+s+" "+t+o(r[1])+'" style="'+n.style+": "+e+'%"'}function a(e,n){J.direction&&(e=100-e),n[1]=n[1]&&t?t(n[0],n[1]):n[1],u.innerHTML+="<div "+i(e,ee[21],n)+"></div>",n[1]&&(u.innerHTML+="<div "+i(e,ee[22],n)+">"+r.to(n[0])+"</div>")}var s=["horizontal","vertical"][n.ort],u=document.createElement("div");return l(u,ee[20]),l(u,ee[20]+"-"+s),Object.keys(e).forEach(function(t){a(t,e[t])}),u}function E(e){var t=e.mode,n=e.density||1,r=e.filter||!1,o=e.values||!1,i=e.stepped||!1,a=_(t,o,i),s=P(n,t,a),u=e.format||{to:Math.round};return Y.appendChild(C(s,r,u))}function R(){return W["offset"+["Width","Height"][n.ort]]}function T(e,t){void 0!==t&&1!==n.handles&&(t=Math.abs(t-n.dir)),Object.keys(Z).forEach(function(n){var r=n.split(".")[0];e===r&&Z[n].forEach(function(e){e(u(U()),t,O(Array.prototype.slice.call(X)))})})}function O(e){return 1===e.length?e[0]:n.dir?e.reverse():e}function S(e,t,r,o){var a=function(t){return Y.hasAttribute("disabled")?!1:f(Y,ee[14])?!1:(t=i(t,o.pageOffset),e===G.start&&void 0!==t.buttons&&t.buttons>1?!1:(t.calcPoint=t.points[n.ort],void r(t,o)))},s=[];return e.split(" ").forEach(function(e){t.addEventListener(e,a,!1),s.push([e,a])}),s}function N(e,t){if(0===e.buttons&&0===e.which&&0!==t.buttonsProperty)return j(e,t);var n,r,i=t.handles||K,a=!1,s=100*(e.calcPoint-t.start)/t.baseSize,u=i[0]===K[0]?0:1;if(n=o(s,t.positions,i.length>1),a=A(i[0],n[u],1===i.length),i.length>1){if(a=A(i[1],n[u?0:1],!1)||a)for(r=0;r<t.handles.length;r++)T("slide",r)}else a&&T("slide",u)}function j(e,t){var n=W.querySelector("."+ee[15]),r=t.handles[0]===K[0]?0:1;null!==n&&p(n,ee[15]),e.cursor&&(document.body.style.cursor="",document.body.removeEventListener("selectstart",document.body.noUiListener));var o=document.documentElement;o.noUiListeners.forEach(function(e){o.removeEventListener(e[0],e[1])}),p(Y,ee[12]),T("set",r),T("change",r)}function k(e,t){var n=document.documentElement;if(1===t.handles.length&&(l(t.handles[0].children[0],ee[15]),t.handles[0].hasAttribute("disabled")))return!1;e.stopPropagation();var r=S(G.move,n,N,{start:e.calcPoint,baseSize:R(),pageOffset:e.pageOffset,handles:t.handles,buttonsProperty:e.buttons,positions:[z[0],z[K.length-1]]}),o=S(G.end,n,j,{handles:t.handles});if(n.noUiListeners=r.concat(o),e.cursor){document.body.style.cursor=getComputedStyle(e.target).cursor,K.length>1&&l(Y,ee[12]);var i=function(){return!1};document.body.noUiListener=i,document.body.addEventListener("selectstart",i,!1)}}function I(e){var t,o,i=e.calcPoint,s=0;return e.stopPropagation(),K.forEach(function(e){s+=r(e)[n.style]}),t=s/2>i||1===K.length?0:1,i-=r(W)[n.style],o=100*i/R(),n.events.snap||a(Y,ee[14],300),K[t].hasAttribute("disabled")?!1:(A(K[t],o),T("slide",t),T("set",t),T("change",t),void(n.events.snap&&k(e,{handles:[K[t]]})))}function D(e){var t,n;if(!e.fixed)for(t=0;t<K.length;t+=1)S(G.start,K[t].children[0],k,{handles:[K[t]]});e.tap&&S(G.start,W,I,{handles:K}),e.drag&&(n=[W.querySelector("."+ee[7])],l(n[0],ee[10]),e.fixed&&n.push(K[n[0]===K[0]?1:0].children[0]),n.forEach(function(e){S(G.start,e,k,{handles:K})}))}function A(e,t,r){var o=e!==K[0]?1:0,i=z[0]+n.margin,a=z[1]-n.margin,u=z[0]+n.limit,c=z[1]-n.limit,f=J.fromStepping(t);return K.length>1&&(t=o?Math.max(t,i):Math.min(t,a)),r!==!1&&n.limit&&K.length>1&&(t=o?Math.min(t,u):Math.max(t,c)),t=J.getStep(t),t=s(parseFloat(t.toFixed(7))),t===z[o]&&f===X[o]?!1:(window.requestAnimationFrame?window.requestAnimationFrame(function(){e.style[n.style]=t+"%"}):e.style[n.style]=t+"%",e.previousSibling||(p(e,ee[17]),t>50&&l(e,ee[17])),z[o]=t,X[o]=J.fromStepping(t),T("update",o),!0)}function M(e,t){var r,o,i;for(n.limit&&(e+=1),r=0;e>r;r+=1)o=r%2,i=t[o],null!==i&&i!==!1&&("number"==typeof i&&(i=String(i)),i=n.format.from(i),(i===!1||isNaN(i)||A(K[o],J.toStepping(i),r===3-n.dir)===!1)&&T("update",o))}function F(e){var t,r,o=u(e);for(n.dir&&n.handles>1&&o.reverse(),n.animate&&-1!==z[0]&&a(Y,ee[14],300),t=K.length>1?3:1,1===o.length&&(t=1),M(t,o),r=0;r<K.length;r++)T("set",r)}function U(){var e,t=[];for(e=0;e<n.handles;e+=1)t[e]=n.format.to(X[e]);return O(t)}function L(){ee.forEach(function(e){e&&p(Y,e)}),Y.innerHTML="",delete Y.noUiSlider}function B(){var e=z.map(function(e,t){var n=J.getApplicableStep(e),r=c(String(n[2])),o=X[t],i=100===e?null:n[2],a=Number((o-n[2]).toFixed(r)),s=0===e?null:a>=n[1]?n[2]:n[0]||!1;return[s,i]});return O(e)}function q(e,t){Z[e]=Z[e]||[],Z[e].push(t),"update"===e.split(".")[0]&&K.forEach(function(e,t){T("update",t)})}function H(e){var t=e.split(".")[0],n=e.substring(t.length);Object.keys(Z).forEach(function(e){var r=e.split(".")[0],o=e.substring(r.length);t&&t!==r||n&&n!==o||delete Z[e]})}function V(e){var t=Q({start:[0,0],margin:e.margin,limit:e.limit,step:e.step,range:e.range,animate:e.animate});n.margin=t.margin,n.limit=t.limit,n.step=t.step,n.range=t.range,n.animate=t.animate,J=t.spectrum}var W,K,Y=t,z=[-1,-1],J=n.spectrum,X=[],Z={},ee=["target","base","origin","handle","horizontal","vertical","background","connect","ltr","rtl","draggable","","state-drag","","state-tap","active","","stacking","tooltip","","pips","marker","value"].map(d(n.cssPrefix||$));if(Y.noUiSlider)throw new Error("Slider was already initialized.");return W=y(n.dir,n.ort,Y),K=g(n.handles,n.dir,W),m(n.connect,Y,K),D(n.events),n.pips&&E(n.pips),n.tooltips&&x(n.tooltips),{destroy:L,steps:B,on:q,off:H,get:U,set:F,updateOptions:V}}function z(e,t){if(!e.nodeName)throw new Error("noUiSlider.create requires a single element.");var n=Q(v(t),e),r=Y(e,n);return r.set(n.start),e.noUiSlider=r,r}v.clonePrototype=function(e){if(null===e)return null;var t=function(){};return t.prototype=e,new t},v.__objToStr=m,v.__isDate=g,v.__isArray=y,v.__isRegExp=b,v.__getRegExpFlags=w;var G=window.navigator.pointerEnabled?{start:"pointerdown",move:"pointermove",end:"pointerup"}:window.navigator.msPointerEnabled?{start:"MSPointerDown",move:"MSPointerMove",end:"MSPointerUp"}:{start:"mousedown touchstart",move:"mousemove touchmove",end:"mouseup touchend"},$="noUi-";j.prototype.getMargin=function(e){return 2===this.xPct.length?_(this.xVal,e):!1},j.prototype.toStepping=function(e){return e=R(this.xVal,this.xPct,e),this.direction&&(e=100-e),e},j.prototype.fromStepping=function(e){return this.direction&&(e=100-e),i(T(this.xVal,this.xPct,e))},j.prototype.getStep=function(e){return this.direction&&(e=100-e),e=O(this.xPct,this.xSteps,this.snap,e),this.direction&&(e=100-e),e},j.prototype.getApplicableStep=function(e){var t=E(e,this.xPct),n=100===e?2:1;return[this.xNumSteps[t-2],this.xVal[t-n],this.xNumSteps[t-n]]},j.prototype.convert=function(e){return this.getStep(this.toStepping(e))};var J={to:function(e){return void 0!==e&&e.toFixed(2)},from:Number};return{create:z}})}).call(t,n(410).Buffer)},function(e,t,n){(function(e,r){function o(){function e(){}try{var t=new Uint8Array(1);return t.foo=function(){return 42},t.constructor=e,42===t.foo()&&t.constructor===e&&"function"==typeof t.subarray&&0===t.subarray(1,1).byteLength}catch(n){return!1}}function i(){return e.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function e(t){return this instanceof e?(this.length=0,this.parent=void 0,"number"==typeof t?a(this,t):"string"==typeof t?s(this,t,arguments.length>1?arguments[1]:"utf8"):u(this,t)):arguments.length>1?new e(t,arguments[1]):new e(t)}function a(t,n){if(t=v(t,0>n?0:0|m(n)),!e.TYPED_ARRAY_SUPPORT)for(var r=0;n>r;r++)t[r]=0;return t}function s(e,t,n){("string"!=typeof n||""===n)&&(n="utf8");var r=0|y(t,n);return e=v(e,r),e.write(t,n),e}function u(t,n){if(e.isBuffer(n))return c(t,n);if($(n))return l(t,n);if(null==n)throw new TypeError("must start with number, buffer, array or string");if("undefined"!=typeof ArrayBuffer){if(n.buffer instanceof ArrayBuffer)return p(t,n);if(n instanceof ArrayBuffer)return f(t,n)}return n.length?h(t,n):d(t,n)}function c(e,t){var n=0|m(t.length);return e=v(e,n),t.copy(e,0,0,n),e}function l(e,t){var n=0|m(t.length);e=v(e,n);for(var r=0;n>r;r+=1)e[r]=255&t[r];return e}function p(e,t){var n=0|m(t.length);e=v(e,n);for(var r=0;n>r;r+=1)e[r]=255&t[r];return e}function f(t,n){return e.TYPED_ARRAY_SUPPORT?(n.byteLength,t=e._augment(new Uint8Array(n))):t=p(t,new Uint8Array(n)),t}function h(e,t){var n=0|m(t.length);e=v(e,n);for(var r=0;n>r;r+=1)e[r]=255&t[r];return e}function d(e,t){var n,r=0;"Buffer"===t.type&&$(t.data)&&(n=t.data,r=0|m(n.length)),e=v(e,r);for(var o=0;r>o;o+=1)e[o]=255&n[o];return e}function v(t,n){e.TYPED_ARRAY_SUPPORT?(t=e._augment(new Uint8Array(n)),t.__proto__=e.prototype):(t.length=n,t._isBuffer=!0);var r=0!==n&&n<=e.poolSize>>>1;return r&&(t.parent=J),t}function m(e){if(e>=i())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i().toString(16)+" bytes");return 0|e}function g(t,n){if(!(this instanceof g))return new g(t,n);var r=new e(t,n);return delete r.parent,r}function y(e,t){"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"binary":case"raw":case"raws":return n;case"utf8":case"utf-8":return V(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return Q(e).length;default:if(r)return V(e).length;t=(""+t).toLowerCase(),r=!0}}function b(e,t,n){var r=!1;if(t=0|t,n=void 0===n||n===1/0?this.length:0|n,e||(e="utf8"),0>t&&(t=0),n>this.length&&(n=this.length),t>=n)return"";for(;;)switch(e){case"hex":return j(this,t,n);case"utf8":case"utf-8":return T(this,t,n);case"ascii":return S(this,t,n);case"binary":return N(this,t,n);case"base64":return R(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function w(e,t,n,r){n=Number(n)||0;var o=e.length-n;r?(r=Number(r),r>o&&(r=o)):r=o;var i=t.length;if(i%2!==0)throw new Error("Invalid hex string");r>i/2&&(r=i/2);for(var a=0;r>a;a++){var s=parseInt(t.substr(2*a,2),16);if(isNaN(s))throw new Error("Invalid hex string");e[n+a]=s}return a}function x(e,t,n,r){return Y(V(t,e.length-n),e,n,r)}function _(e,t,n,r){return Y(W(t),e,n,r)}function P(e,t,n,r){return _(e,t,n,r)}function C(e,t,n,r){return Y(Q(t),e,n,r)}function E(e,t,n,r){return Y(K(t,e.length-n),e,n,r)}function R(e,t,n){return z.fromByteArray(0===t&&n===e.length?e:e.slice(t,n))}function T(e,t,n){n=Math.min(e.length,n);for(var r=[],o=t;n>o;){var i=e[o],a=null,s=i>239?4:i>223?3:i>191?2:1;if(n>=o+s){var u,c,l,p;switch(s){case 1:128>i&&(a=i);break;case 2:u=e[o+1],128===(192&u)&&(p=(31&i)<<6|63&u,p>127&&(a=p));break;case 3:u=e[o+1],c=e[o+2],128===(192&u)&&128===(192&c)&&(p=(15&i)<<12|(63&u)<<6|63&c,p>2047&&(55296>p||p>57343)&&(a=p));break;case 4:u=e[o+1],c=e[o+2],l=e[o+3],128===(192&u)&&128===(192&c)&&128===(192&l)&&(p=(15&i)<<18|(63&u)<<12|(63&c)<<6|63&l,p>65535&&1114112>p&&(a=p))}}null===a?(a=65533,s=1):a>65535&&(a-=65536,r.push(a>>>10&1023|55296),a=56320|1023&a),r.push(a),o+=s}return O(r)}function O(e){var t=e.length;if(X>=t)return String.fromCharCode.apply(String,e);for(var n="",r=0;t>r;)n+=String.fromCharCode.apply(String,e.slice(r,r+=X));return n}function S(e,t,n){var r="";n=Math.min(e.length,n);for(var o=t;n>o;o++)r+=String.fromCharCode(127&e[o]);return r}function N(e,t,n){var r="";n=Math.min(e.length,n);for(var o=t;n>o;o++)r+=String.fromCharCode(e[o]);return r}function j(e,t,n){var r=e.length;(!t||0>t)&&(t=0),(!n||0>n||n>r)&&(n=r);for(var o="",i=t;n>i;i++)o+=H(e[i]);return o}function k(e,t,n){for(var r=e.slice(t,n),o="",i=0;i<r.length;i+=2)o+=String.fromCharCode(r[i]+256*r[i+1]);return o}function I(e,t,n){if(e%1!==0||0>e)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function D(t,n,r,o,i,a){if(!e.isBuffer(t))throw new TypeError("buffer must be a Buffer instance");if(n>i||a>n)throw new RangeError("value is out of bounds");if(r+o>t.length)throw new RangeError("index out of range")}function A(e,t,n,r){0>t&&(t=65535+t+1);for(var o=0,i=Math.min(e.length-n,2);i>o;o++)e[n+o]=(t&255<<8*(r?o:1-o))>>>8*(r?o:1-o)}function M(e,t,n,r){0>t&&(t=4294967295+t+1);for(var o=0,i=Math.min(e.length-n,4);i>o;o++)e[n+o]=t>>>8*(r?o:3-o)&255}function F(e,t,n,r,o,i){if(t>o||i>t)throw new RangeError("value is out of bounds");if(n+r>e.length)throw new RangeError("index out of range");if(0>n)throw new RangeError("index out of range")}function U(e,t,n,r,o){return o||F(e,t,n,4,3.4028234663852886e38,-3.4028234663852886e38),G.write(e,t,n,r,23,4),n+4}function L(e,t,n,r,o){return o||F(e,t,n,8,1.7976931348623157e308,-1.7976931348623157e308),G.write(e,t,n,r,52,8),n+8}function B(e){if(e=q(e).replace(ee,""),e.length<2)return"";for(;e.length%4!==0;)e+="=";return e}function q(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}function H(e){return 16>e?"0"+e.toString(16):e.toString(16)}function V(e,t){t=t||1/0;for(var n,r=e.length,o=null,i=[],a=0;r>a;a++){if(n=e.charCodeAt(a),n>55295&&57344>n){if(!o){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(a+1===r){(t-=3)>-1&&i.push(239,191,189);continue}o=n;continue}if(56320>n){(t-=3)>-1&&i.push(239,191,189),o=n;continue}n=o-55296<<10|n-56320|65536}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,128>n){if((t-=1)<0)break;i.push(n)}else if(2048>n){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(65536>n){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(1114112>n))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function W(e){for(var t=[],n=0;n<e.length;n++)t.push(255&e.charCodeAt(n));return t}function K(e,t){for(var n,r,o,i=[],a=0;a<e.length&&!((t-=2)<0);a++)n=e.charCodeAt(a),r=n>>8,o=n%256,i.push(o),i.push(r);return i}function Q(e){return z.toByteArray(B(e))}function Y(e,t,n,r){for(var o=0;r>o&&!(o+n>=t.length||o>=e.length);o++)t[o+n]=e[o];return o}var z=n(411),G=n(412),$=n(413);t.Buffer=e,t.SlowBuffer=g,t.INSPECT_MAX_BYTES=50,e.poolSize=8192;var J={};e.TYPED_ARRAY_SUPPORT=void 0!==r.TYPED_ARRAY_SUPPORT?r.TYPED_ARRAY_SUPPORT:o(),e.TYPED_ARRAY_SUPPORT&&(e.prototype.__proto__=Uint8Array.prototype,e.__proto__=Uint8Array),e.isBuffer=function(e){return!(null==e||!e._isBuffer)},e.compare=function(t,n){if(!e.isBuffer(t)||!e.isBuffer(n))throw new TypeError("Arguments must be Buffers");if(t===n)return 0;for(var r=t.length,o=n.length,i=0,a=Math.min(r,o);a>i&&t[i]===n[i];)++i;return i!==a&&(r=t[i],o=n[i]),o>r?-1:r>o?1:0},e.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},e.concat=function(t,n){if(!$(t))throw new TypeError("list argument must be an Array of Buffers.");if(0===t.length)return new e(0);var r;if(void 0===n)for(n=0,r=0;r<t.length;r++)n+=t[r].length;var o=new e(n),i=0;for(r=0;r<t.length;r++){var a=t[r];a.copy(o,i),i+=a.length}return o},e.byteLength=y,e.prototype.length=void 0,e.prototype.parent=void 0,e.prototype.toString=function(){var e=0|this.length;return 0===e?"":0===arguments.length?T(this,0,e):b.apply(this,arguments)},e.prototype.equals=function(t){if(!e.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t?!0:0===e.compare(this,t)},e.prototype.inspect=function(){var e="",n=t.INSPECT_MAX_BYTES;return this.length>0&&(e=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(e+=" ... ")),"<Buffer "+e+">"},e.prototype.compare=function(t){if(!e.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t?0:e.compare(this,t)},e.prototype.indexOf=function(t,n){function r(e,t,n){for(var r=-1,o=0;n+o<e.length;o++)if(e[n+o]===t[-1===r?0:o-r]){if(-1===r&&(r=o),o-r+1===t.length)return n+r}else r=-1;return-1}if(n>2147483647?n=2147483647:-2147483648>n&&(n=-2147483648),n>>=0,0===this.length)return-1;if(n>=this.length)return-1;if(0>n&&(n=Math.max(this.length+n,0)),"string"==typeof t)return 0===t.length?-1:String.prototype.indexOf.call(this,t,n);if(e.isBuffer(t))return r(this,t,n);if("number"==typeof t)return e.TYPED_ARRAY_SUPPORT&&"function"===Uint8Array.prototype.indexOf?Uint8Array.prototype.indexOf.call(this,t,n):r(this,[t],n);throw new TypeError("val must be string, number or Buffer")},e.prototype.get=function(e){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(e)},e.prototype.set=function(e,t){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(e,t)},e.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else if(isFinite(t))t=0|t,isFinite(n)?(n=0|n,void 0===r&&(r="utf8")):(r=n,n=void 0);else{var o=r;r=t,t=0|n,n=o}var i=this.length-t;if((void 0===n||n>i)&&(n=i),e.length>0&&(0>n||0>t)||t>this.length)throw new RangeError("attempt to write outside buffer bounds");r||(r="utf8");for(var a=!1;;)switch(r){case"hex":return w(this,e,t,n);case"utf8":case"utf-8":return x(this,e,t,n);case"ascii":return _(this,e,t,n);case"binary":return P(this,e,t,n);case"base64":return C(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,e,t,n);default:if(a)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),a=!0}},e.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var X=4096;e.prototype.slice=function(t,n){var r=this.length;t=~~t,n=void 0===n?r:~~n,0>t?(t+=r,0>t&&(t=0)):t>r&&(t=r),0>n?(n+=r,0>n&&(n=0)):n>r&&(n=r),t>n&&(n=t);var o;if(e.TYPED_ARRAY_SUPPORT)o=e._augment(this.subarray(t,n));else{var i=n-t;o=new e(i,void 0);for(var a=0;i>a;a++)o[a]=this[a+t]}return o.length&&(o.parent=this.parent||this),o},e.prototype.readUIntLE=function(e,t,n){e=0|e,t=0|t,n||I(e,t,this.length);for(var r=this[e],o=1,i=0;++i<t&&(o*=256);)r+=this[e+i]*o;return r},e.prototype.readUIntBE=function(e,t,n){e=0|e,t=0|t,n||I(e,t,this.length);for(var r=this[e+--t],o=1;t>0&&(o*=256);)r+=this[e+--t]*o;return r},e.prototype.readUInt8=function(e,t){return t||I(e,1,this.length),this[e]},e.prototype.readUInt16LE=function(e,t){return t||I(e,2,this.length),this[e]|this[e+1]<<8},e.prototype.readUInt16BE=function(e,t){return t||I(e,2,this.length),this[e]<<8|this[e+1]},e.prototype.readUInt32LE=function(e,t){return t||I(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},e.prototype.readUInt32BE=function(e,t){return t||I(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},e.prototype.readIntLE=function(e,t,n){e=0|e,t=0|t,n||I(e,t,this.length);for(var r=this[e],o=1,i=0;++i<t&&(o*=256);)r+=this[e+i]*o;return o*=128,r>=o&&(r-=Math.pow(2,8*t)),r},e.prototype.readIntBE=function(e,t,n){e=0|e,t=0|t,n||I(e,t,this.length);for(var r=t,o=1,i=this[e+--r];r>0&&(o*=256);)i+=this[e+--r]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*t)),i},e.prototype.readInt8=function(e,t){return t||I(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},e.prototype.readInt16LE=function(e,t){t||I(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},e.prototype.readInt16BE=function(e,t){t||I(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},e.prototype.readInt32LE=function(e,t){return t||I(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},e.prototype.readInt32BE=function(e,t){return t||I(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},e.prototype.readFloatLE=function(e,t){return t||I(e,4,this.length),G.read(this,e,!0,23,4)},e.prototype.readFloatBE=function(e,t){return t||I(e,4,this.length),G.read(this,e,!1,23,4)},e.prototype.readDoubleLE=function(e,t){return t||I(e,8,this.length),G.read(this,e,!0,52,8)},e.prototype.readDoubleBE=function(e,t){return t||I(e,8,this.length),G.read(this,e,!1,52,8)},e.prototype.writeUIntLE=function(e,t,n,r){e=+e,t=0|t,n=0|n,r||D(this,e,t,n,Math.pow(2,8*n),0);var o=1,i=0;for(this[t]=255&e;++i<n&&(o*=256);)this[t+i]=e/o&255;return t+n},e.prototype.writeUIntBE=function(e,t,n,r){e=+e,t=0|t,n=0|n,r||D(this,e,t,n,Math.pow(2,8*n),0);var o=n-1,i=1;for(this[t+o]=255&e;--o>=0&&(i*=256);)this[t+o]=e/i&255;return t+n},e.prototype.writeUInt8=function(t,n,r){return t=+t,n=0|n,r||D(this,t,n,1,255,0),e.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[n]=255&t,n+1},e.prototype.writeUInt16LE=function(t,n,r){return t=+t,n=0|n,r||D(this,t,n,2,65535,0),e.TYPED_ARRAY_SUPPORT?(this[n]=255&t,this[n+1]=t>>>8):A(this,t,n,!0),n+2},e.prototype.writeUInt16BE=function(t,n,r){return t=+t,n=0|n,r||D(this,t,n,2,65535,0),e.TYPED_ARRAY_SUPPORT?(this[n]=t>>>8,this[n+1]=255&t):A(this,t,n,!1),n+2},e.prototype.writeUInt32LE=function(t,n,r){return t=+t,n=0|n,r||D(this,t,n,4,4294967295,0),e.TYPED_ARRAY_SUPPORT?(this[n+3]=t>>>24,this[n+2]=t>>>16,this[n+1]=t>>>8,this[n]=255&t):M(this,t,n,!0),n+4},e.prototype.writeUInt32BE=function(t,n,r){return t=+t,n=0|n,r||D(this,t,n,4,4294967295,0),e.TYPED_ARRAY_SUPPORT?(this[n]=t>>>24,this[n+1]=t>>>16,this[n+2]=t>>>8,this[n+3]=255&t):M(this,t,n,!1),n+4},e.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t=0|t,!r){var o=Math.pow(2,8*n-1);D(this,e,t,n,o-1,-o)}var i=0,a=1,s=0>e?1:0;for(this[t]=255&e;++i<n&&(a*=256);)this[t+i]=(e/a>>0)-s&255;return t+n},e.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t=0|t,!r){var o=Math.pow(2,8*n-1);D(this,e,t,n,o-1,-o)}var i=n-1,a=1,s=0>e?1:0;for(this[t+i]=255&e;--i>=0&&(a*=256);)this[t+i]=(e/a>>0)-s&255;return t+n},e.prototype.writeInt8=function(t,n,r){return t=+t,n=0|n,r||D(this,t,n,1,127,-128),e.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),0>t&&(t=255+t+1),this[n]=255&t,n+1},e.prototype.writeInt16LE=function(t,n,r){return t=+t,n=0|n,r||D(this,t,n,2,32767,-32768),e.TYPED_ARRAY_SUPPORT?(this[n]=255&t,this[n+1]=t>>>8):A(this,t,n,!0),n+2},e.prototype.writeInt16BE=function(t,n,r){return t=+t,n=0|n,r||D(this,t,n,2,32767,-32768),e.TYPED_ARRAY_SUPPORT?(this[n]=t>>>8,this[n+1]=255&t):A(this,t,n,!1),n+2},e.prototype.writeInt32LE=function(t,n,r){return t=+t,n=0|n,r||D(this,t,n,4,2147483647,-2147483648),e.TYPED_ARRAY_SUPPORT?(this[n]=255&t,this[n+1]=t>>>8,this[n+2]=t>>>16,this[n+3]=t>>>24):M(this,t,n,!0),n+4},e.prototype.writeInt32BE=function(t,n,r){return t=+t,n=0|n,r||D(this,t,n,4,2147483647,-2147483648),0>t&&(t=4294967295+t+1),e.TYPED_ARRAY_SUPPORT?(this[n]=t>>>24,this[n+1]=t>>>16,this[n+2]=t>>>8,this[n+3]=255&t):M(this,t,n,!1),n+4},e.prototype.writeFloatLE=function(e,t,n){return U(this,e,t,!0,n)},e.prototype.writeFloatBE=function(e,t,n){return U(this,e,t,!1,n)},e.prototype.writeDoubleLE=function(e,t,n){return L(this,e,t,!0,n)},e.prototype.writeDoubleBE=function(e,t,n){return L(this,e,t,!1,n)},e.prototype.copy=function(t,n,r,o){if(r||(r=0),o||0===o||(o=this.length),n>=t.length&&(n=t.length),n||(n=0),o>0&&r>o&&(o=r),o===r)return 0;if(0===t.length||0===this.length)return 0;if(0>n)throw new RangeError("targetStart out of bounds");if(0>r||r>=this.length)throw new RangeError("sourceStart out of bounds");if(0>o)throw new RangeError("sourceEnd out of bounds");o>this.length&&(o=this.length),t.length-n<o-r&&(o=t.length-n+r);var i,a=o-r;if(this===t&&n>r&&o>n)for(i=a-1;i>=0;i--)t[i+n]=this[i+r];else if(1e3>a||!e.TYPED_ARRAY_SUPPORT)for(i=0;a>i;i++)t[i+n]=this[i+r];else t._set(this.subarray(r,r+a),n);return a},e.prototype.fill=function(e,t,n){if(e||(e=0),t||(t=0),n||(n=this.length),t>n)throw new RangeError("end < start");if(n!==t&&0!==this.length){if(0>t||t>=this.length)throw new RangeError("start out of bounds");if(0>n||n>this.length)throw new RangeError("end out of bounds");var r;if("number"==typeof e)for(r=t;n>r;r++)this[r]=e;else{var o=V(e.toString()),i=o.length;for(r=t;n>r;r++)this[r]=o[r%i]}return this}},e.prototype.toArrayBuffer=function(){if("undefined"!=typeof Uint8Array){if(e.TYPED_ARRAY_SUPPORT)return new e(this).buffer;for(var t=new Uint8Array(this.length),n=0,r=t.length;r>n;n+=1)t[n]=this[n];return t.buffer}throw new TypeError("Buffer.toArrayBuffer not supported in this browser")};var Z=e.prototype;e._augment=function(t){return t.constructor=e,t._isBuffer=!0,t._set=t.set,t.get=Z.get,t.set=Z.set,t.write=Z.write,t.toString=Z.toString,t.toLocaleString=Z.toString,t.toJSON=Z.toJSON,t.equals=Z.equals,t.compare=Z.compare,t.indexOf=Z.indexOf,t.copy=Z.copy,t.slice=Z.slice,t.readUIntLE=Z.readUIntLE,t.readUIntBE=Z.readUIntBE,t.readUInt8=Z.readUInt8,t.readUInt16LE=Z.readUInt16LE,t.readUInt16BE=Z.readUInt16BE,t.readUInt32LE=Z.readUInt32LE,t.readUInt32BE=Z.readUInt32BE,t.readIntLE=Z.readIntLE,t.readIntBE=Z.readIntBE,t.readInt8=Z.readInt8,t.readInt16LE=Z.readInt16LE,t.readInt16BE=Z.readInt16BE, t.readInt32LE=Z.readInt32LE,t.readInt32BE=Z.readInt32BE,t.readFloatLE=Z.readFloatLE,t.readFloatBE=Z.readFloatBE,t.readDoubleLE=Z.readDoubleLE,t.readDoubleBE=Z.readDoubleBE,t.writeUInt8=Z.writeUInt8,t.writeUIntLE=Z.writeUIntLE,t.writeUIntBE=Z.writeUIntBE,t.writeUInt16LE=Z.writeUInt16LE,t.writeUInt16BE=Z.writeUInt16BE,t.writeUInt32LE=Z.writeUInt32LE,t.writeUInt32BE=Z.writeUInt32BE,t.writeIntLE=Z.writeIntLE,t.writeIntBE=Z.writeIntBE,t.writeInt8=Z.writeInt8,t.writeInt16LE=Z.writeInt16LE,t.writeInt16BE=Z.writeInt16BE,t.writeInt32LE=Z.writeInt32LE,t.writeInt32BE=Z.writeInt32BE,t.writeFloatLE=Z.writeFloatLE,t.writeFloatBE=Z.writeFloatBE,t.writeDoubleLE=Z.writeDoubleLE,t.writeDoubleBE=Z.writeDoubleBE,t.fill=Z.fill,t.inspect=Z.inspect,t.toArrayBuffer=Z.toArrayBuffer,t};var ee=/[^+\/0-9A-Za-z-_]/g}).call(t,n(410).Buffer,function(){return this}())},function(e,t){var n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";!function(e){"use strict";function t(e){var t=e.charCodeAt(0);return t===a||t===p?62:t===s||t===f?63:u>t?-1:u+10>t?t-u+26+26:l+26>t?t-l:c+26>t?t-c+26:void 0}function r(e){function n(e){c[p++]=e}var r,o,a,s,u,c;if(e.length%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var l=e.length;u="="===e.charAt(l-2)?2:"="===e.charAt(l-1)?1:0,c=new i(3*e.length/4-u),a=u>0?e.length-4:e.length;var p=0;for(r=0,o=0;a>r;r+=4,o+=3)s=t(e.charAt(r))<<18|t(e.charAt(r+1))<<12|t(e.charAt(r+2))<<6|t(e.charAt(r+3)),n((16711680&s)>>16),n((65280&s)>>8),n(255&s);return 2===u?(s=t(e.charAt(r))<<2|t(e.charAt(r+1))>>4,n(255&s)):1===u&&(s=t(e.charAt(r))<<10|t(e.charAt(r+1))<<4|t(e.charAt(r+2))>>2,n(s>>8&255),n(255&s)),c}function o(e){function t(e){return n.charAt(e)}function r(e){return t(e>>18&63)+t(e>>12&63)+t(e>>6&63)+t(63&e)}var o,i,a,s=e.length%3,u="";for(o=0,a=e.length-s;a>o;o+=3)i=(e[o]<<16)+(e[o+1]<<8)+e[o+2],u+=r(i);switch(s){case 1:i=e[e.length-1],u+=t(i>>2),u+=t(i<<4&63),u+="==";break;case 2:i=(e[e.length-2]<<8)+e[e.length-1],u+=t(i>>10),u+=t(i>>4&63),u+=t(i<<2&63),u+="="}return u}var i="undefined"!=typeof Uint8Array?Uint8Array:Array,a="+".charCodeAt(0),s="/".charCodeAt(0),u="0".charCodeAt(0),c="a".charCodeAt(0),l="A".charCodeAt(0),p="-".charCodeAt(0),f="_".charCodeAt(0);e.toByteArray=r,e.fromByteArray=o}(t)},function(e,t){t.read=function(e,t,n,r,o){var i,a,s=8*o-r-1,u=(1<<s)-1,c=u>>1,l=-7,p=n?o-1:0,f=n?-1:1,h=e[t+p];for(p+=f,i=h&(1<<-l)-1,h>>=-l,l+=s;l>0;i=256*i+e[t+p],p+=f,l-=8);for(a=i&(1<<-l)-1,i>>=-l,l+=r;l>0;a=256*a+e[t+p],p+=f,l-=8);if(0===i)i=1-c;else{if(i===u)return a?0/0:(h?-1:1)*(1/0);a+=Math.pow(2,r),i-=c}return(h?-1:1)*a*Math.pow(2,i-r)},t.write=function(e,t,n,r,o,i){var a,s,u,c=8*i-o-1,l=(1<<c)-1,p=l>>1,f=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,h=r?0:i-1,d=r?1:-1,v=0>t||0===t&&0>1/t?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=l):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),t+=a+p>=1?f/u:f*Math.pow(2,1-p),t*u>=2&&(a++,u/=2),a+p>=l?(s=0,a=l):a+p>=1?(s=(t*u-1)*Math.pow(2,o),a+=p):(s=t*Math.pow(2,p-1)*Math.pow(2,o),a=0));o>=8;e[n+h]=255&s,h+=d,s/=256,o-=8);for(a=a<<o|s,c+=o;c>0;e[n+h]=255&a,h+=d,a/=256,c-=8);e[n+h-d]|=128*v}},function(e){var t=Array.isArray,n=Object.prototype.toString;e.exports=t||function(e){return!!e&&"[object Array]"==n.call(e)}},function(e,t,n){"use strict";function r(e){var t=e.container,r=e.cssClasses,f=void 0===r?{}:r,h=e.hideContainerWhenNoResults,d=void 0===h?!0:h,v=e.templates,m=void 0===v?p:v,g=e.transformData,y=a.getContainerNode(t),b=u(n(416));if(d===!0&&(b=s(b)),!y)throw new Error("Usage: stats({container[, template, transformData, hideContainerWhenNoResults]})");return{render:function(e){var t=e.results,n=e.templatesConfig,r=0===t.nbHits,s=a.prepareTemplateProps({transformData:g,defaultTemplates:p,templatesConfig:n,templates:m}),u={body:l(c("body"),f.body),footer:l(c("footer"),f.footer),header:l(c("header"),f.header),root:l(c(null),f.root),time:l(c("time"),f.time)};i.render(o.createElement(b,{cssClasses:u,hitsPerPage:t.hitsPerPage,nbHits:t.nbHits,nbPages:t.nbPages,page:t.page,processingTimeMS:t.processingTimeMS,query:t.query,shouldAutoHideContainer:r,templateProps:s}),y)}}}var o=n(217),i=n(369),a=n(370),s=n(372),u=n(373),c=n(370).bemHelper("ais-stats"),l=n(371),p=n(415);e.exports=r},function(e){"use strict";e.exports={header:"",body:'{{#hasNoResults}}No results{{/hasNoResults}}\n {{#hasOneResult}}1 result{{/hasOneResult}}\n {{#hasManyResults}}{{#helpers.formatNumber}}{{nbHits}}{{/helpers.formatNumber}} results{{/hasManyResults}}\n <span class="{{cssClasses.time}}">found in {{processingTimeMS}}ms</span>',footer:""}},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;return void 0===u?void 0:u.call(a)}var c=Object.getPrototypeOf(o);if(null===c)return void 0;e=c,t=i,n=a,r=!0,s=c=void 0}},u=n(217),c=n(374),l=function(e){function t(){r(this,t),s(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return o(t,e),a(t,[{key:"render",value:function(){var e={hasManyResults:this.props.nbHits>1,hasNoResults:0===this.props.nbHits,hasOneResult:1===this.props.nbHits,hitsPerPage:this.props.hitsPerPage,nbHits:this.props.nbHits,nbPages:this.props.nbPages,page:this.props.page,processingTimeMS:this.props.processingTimeMS,query:this.props.query,cssClasses:this.props.cssClasses};return u.createElement(c,i({data:e,templateKey:"body"},this.props.templateProps))}}]),t}(u.Component);l.propTypes={cssClasses:u.PropTypes.shape({time:u.PropTypes.string}),hitsPerPage:u.PropTypes.number,nbHits:u.PropTypes.number,nbPages:u.PropTypes.number,page:u.PropTypes.number,processingTimeMS:u.PropTypes.number,query:u.PropTypes.string,templateProps:u.PropTypes.object.isRequired},e.exports=l},function(e,t,n){"use strict";function r(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.container,r=e.facetName,d=e.label,v=e.templates,m=void 0===v?h:v,g=e.cssClasses,y=void 0===g?{}:g,b=e.transformData,w=e.hideContainerWhenNoResults,x=void 0===w?!0:w,_=u.getContainerNode(t),P="Usage: toggle({container, facetName, label[, cssClasses.{root,header,body,footer,list,item,active,label,checkbox,count}, templates.{header,item,footer}, transformData, hideContainerWhenNoResults]})",C=f(n(381));if(x===!0&&(C=p(C)),!t||!r||!d)throw new Error(P);return{getConfiguration:function(){return{facets:[r]}},render:function(e){var t=e.helper,n=e.results,p=e.templatesConfig,f=e.state,v=e.createURL,g=t.hasRefinements(r),w=i(n.getFacetValues(r),{name:g.toString()}),x=0===n.nbHits,P=u.prepareTemplateProps({transformData:b,defaultTemplates:h,templatesConfig:p,templates:m}),E={name:d,isRefined:g,count:w&&w.count||null},R={root:l(c(null),y.root),header:l(c("header"),y.header),body:l(c("body"),y.body),footer:l(c("footer"),y.footer),list:l(c("list"),y.list),item:l(c("item"),y.item),active:l(c("item","active"),y.active),label:l(c("label"),y.label),checkbox:l(c("checkbox"),y.checkbox),count:l(c("count"),y.count)};s.render(a.createElement(C,{createURL:function(){return v(f.toggleRefinement(r,E.isRefined))},cssClasses:R,facetValues:[E],shouldAutoHideContainer:x,templateProps:P,toggleRefinement:o.bind(null,t,r,E.isRefined)}),_)}}}function o(e,t,n){var r=n?"remove":"add";e[r+"FacetRefinement"](t,!0),e.search()}var i=n(128),a=n(217),s=n(369),u=n(370),c=u.bemHelper("ais-toggle"),l=n(371),p=n(372),f=n(373),h=n(418);e.exports=r},function(e){"use strict";e.exports={header:"",item:'<label class="{{cssClasses.label}}">\n <input type="checkbox" class="{{cssClasses.checkbox}}" value="{{name}}" {{#isRefined}}checked{{/isRefined}} />{{name}}\n <span class="{{cssClasses.count}}">{{count}}</span>\n</label>',footer:""}}])}); //# sourceMappingURL=instantsearch.min.map
node_modules/case-sensitive-paths-webpack-plugin/demo/src/AppRoot.component.js
okristian1/react-info
import React, { Component } from 'react'; export default class AppRoot extends Component { // we can't use `connect` in this component, so must do naiively: constructor(props) { super(props); this.state = { }; } render() { return ( <div> <h1>This is just an empty demo</h1> <p>(Run the tests.)</p> </div> ); } }
src/components/timer-config-table.js
SawyerHood/pomodoro-redux
import React from 'react' import Table from 'material-ui/lib/table/table' import TableBody from 'material-ui/lib/table/table-body' import TableFooter from 'material-ui/lib/table/table-footer' import TableHeader from 'material-ui/lib/table/table-header' import TableHeaderColumn from 'material-ui/lib/table/table-header-column' import TableRow from 'material-ui/lib/table/table-row' import TableRowColumn from 'material-ui/lib/table/table-row-column' import Checkbox from 'material-ui/lib/checkbox' import TextField from 'material-ui/lib/text-field' import { displayTime, numFromTimeString } from '../constants' import FlatButton from 'material-ui/lib/flat-button' const TimerConfigRow = ({timer, handleNameEdit, handleTimeEdit, handlePin, handleDeleteRow}) => { return ( <TableRow selectable> <TableRowColumn><Checkbox checked={timer.pinned} onCheck={handlePin}/></TableRowColumn> <TableRowColumn> <TextField value={timer.name} hintText='Timer Name' onChange={handleNameEdit}/> </TableRowColumn> <TableRowColumn> <TextField value={timer.timerText} hintText='Timer Length' errorText={timer.valid ? '' : 'Time must be in the format \'MM:SS\''} onChange={handleTimeEdit}/> </TableRowColumn> <TableRowColumn> <FlatButton label='Delete' onTouchTap={handleDeleteRow}/> </TableRowColumn> </TableRow> ) } class TimerConfigTable extends React.Component { static propTypes = { timers: React.PropTypes.array.isRequired, setValid: React.PropTypes.func.isRequired } constructor (props) { // Configure the form with the initial timers. Once we validate them, // we will update the reduxStore super() this.state = { timers: props.timers.map((timer) => { return {...timer, timerText: displayTime(timer.timerLength), valid: true} }) } } makeHandleNameEdit (index) { return (e) => { e.preventDefault() const newName = e.target.value const arrayCopy = this.state.timers.slice() arrayCopy.splice(index, 1, { ...arrayCopy[index], name: newName }) this.setState({timers: arrayCopy}) } } makeHandleTimeEdit (index) { return (e) => { e.preventDefault() const newTimeString = e.target.value const timeMilli = numFromTimeString(newTimeString) || 0 const valid = timeMilli !== 0 this.props.setValid(valid) const arrayCopy = this.state.timers.slice() arrayCopy.splice(index, 1, { ...arrayCopy[index], valid, timerText: newTimeString, timerLength: timeMilli }) this.setState({timers: arrayCopy}) } } makeHandlePin (index) { return (e) => { e.preventDefault() const arrayCopy = this.state.timers.slice() arrayCopy.splice(index, 1, {...arrayCopy[index], pinned: !arrayCopy[index].pinned}) this.setState({timers: arrayCopy}) } } addRow () { this.setState({timers: [...this.state.timers, {timerLength: 0, name: '', timerText: '', valid: false}]}) } makeHandleDeleteRow (index) { return () => { const arrayCopy = this.state.timers.slice() arrayCopy.splice(index, 1) this.setState({timers: arrayCopy}) } } render () { const timers = this.state.timers const rows = timers.map((timer, index) => { return <TimerConfigRow timer={timer} key={index} handleNameEdit={this.makeHandleNameEdit(index)} handleTimeEdit={this.makeHandleTimeEdit(index)} handlePin={this.makeHandlePin(index)} handleDeleteRow={this.makeHandleDeleteRow(index)}/> }) return ( <Table selectable={false}> <TableHeader enableSelectAll={false} displaySelectAll={false} adjustForCheckbox={false}> <TableRow> <TableHeaderColumn tooltip='Pinned'>Pinned</TableHeaderColumn> <TableHeaderColumn tooltip='Name'>Name</TableHeaderColumn> <TableHeaderColumn tooltip='Time'>Time</TableHeaderColumn> </TableRow> </TableHeader> <TableBody selectable> {rows} </TableBody> <TableFooter> <TableRow> <TableRowColumn colSpan='3' style={{textAlign: 'center'}}> <FlatButton label='Add Timer' onTouchTap={() => this.addRow()}/> </TableRowColumn> </TableRow> </TableFooter> </Table> ) } } export default {TimerConfigTable}
ajax/libs/react/0.7.0/react.min.js
barcadictni/cdnjs
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. !function(e,t){function i(){this._events={},this._conf&&s.call(this,this._conf)}function s(e){e&&(this._conf=e,e.delimiter&&(this.delimiter=e.delimiter),e.maxListeners&&(this._events.maxListeners=e.maxListeners),e.wildcard&&(this.wildcard=e.wildcard),e.newListener&&(this.newListener=e.newListener),this.wildcard&&(this.listenerTree={}))}function o(e){this._events={},this.newListener=!1,s.call(this,e)}function u(e,t,n,r){if(!n)return[];var i=[],s,o,a,f,l,c,h,p=t.length,d=t[r],v=t[r+1];if(r===p&&n._listeners){if(typeof n._listeners=="function")return e&&e.push(n._listeners),[n];for(s=0,o=n._listeners.length;s<o;s++)e&&e.push(n._listeners[s]);return[n]}if(d==="*"||d==="**"||n[d]){if(d==="*"){for(a in n)a!=="_listeners"&&n.hasOwnProperty(a)&&(i=i.concat(u(e,t,n[a],r+1)));return i}if(d==="**"){h=r+1===p||r+2===p&&v==="*",h&&n._listeners&&(i=i.concat(u(e,t,n,p)));for(a in n)a!=="_listeners"&&n.hasOwnProperty(a)&&(a==="*"||a==="**"?(n[a]._listeners&&!h&&(i=i.concat(u(e,t,n[a],p))),i=i.concat(u(e,t,n[a],r))):a===v?i=i.concat(u(e,t,n[a],r+2)):i=i.concat(u(e,t,n[a],r)));return i}i=i.concat(u(e,t,n[d],r+1))}f=n["*"],f&&u(e,t,f,r+1),l=n["**"];if(l)if(r<p){l._listeners&&u(e,t,l,p);for(a in l)a!=="_listeners"&&l.hasOwnProperty(a)&&(a===v?u(e,t,l[a],r+2):a===d?u(e,t,l[a],r+1):(c={},c[a]=l[a],u(e,t,{"**":c},r+1)))}else l._listeners?u(e,t,l,p):l["*"]&&l["*"]._listeners&&u(e,t,l["*"],p);return i}function a(e,t){e=typeof e=="string"?e.split(this.delimiter):e.slice();for(var i=0,s=e.length;i+1<s;i++)if(e[i]==="**"&&e[i+1]==="**")return;var o=this.listenerTree,u=e.shift();while(u){o[u]||(o[u]={}),o=o[u];if(e.length===0){if(!o._listeners)o._listeners=t;else if(typeof o._listeners=="function")o._listeners=[o._listeners,t];else if(n(o._listeners)){o._listeners.push(t);if(!o._listeners.warned){var a=r;typeof this._events.maxListeners!="undefined"&&(a=this._events.maxListeners),a>0&&o._listeners.length>a&&(o._listeners.warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",o._listeners.length),console.trace())}}return!0}u=e.shift()}return!0}var n=Array.isArray?Array.isArray:function(t){return Object.prototype.toString.call(t)==="[object Array]"},r=10;o.prototype.delimiter=".",o.prototype.setMaxListeners=function(e){this._events||i.call(this),this._events.maxListeners=e,this._conf||(this._conf={}),this._conf.maxListeners=e},o.prototype.event="",o.prototype.once=function(e,t){return this.many(e,1,t),this},o.prototype.many=function(e,t,n){function i(){--t===0&&r.off(e,i),n.apply(this,arguments)}var r=this;if(typeof n!="function")throw new Error("many only accepts instances of Function");return i._origin=n,this.on(e,i),r},o.prototype.emit=function(){this._events||i.call(this);var e=arguments[0];if(e==="newListener"&&!this.newListener&&!this._events.newListener)return!1;if(this._all){var t=arguments.length,n=new Array(t-1);for(var r=1;r<t;r++)n[r-1]=arguments[r];for(r=0,t=this._all.length;r<t;r++)this.event=e,this._all[r].apply(this,n)}if(e==="error"&&!this._all&&!this._events.error&&(!this.wildcard||!this.listenerTree.error))throw arguments[1]instanceof Error?arguments[1]:new Error("Uncaught, unspecified 'error' event.");var s;if(this.wildcard){s=[];var o=typeof e=="string"?e.split(this.delimiter):e.slice();u.call(this,s,o,this.listenerTree,0)}else s=this._events[e];if(typeof s=="function"){this.event=e;if(arguments.length===1)s.call(this);else if(arguments.length>1)switch(arguments.length){case 2:s.call(this,arguments[1]);break;case 3:s.call(this,arguments[1],arguments[2]);break;default:var t=arguments.length,n=new Array(t-1);for(var r=1;r<t;r++)n[r-1]=arguments[r];s.apply(this,n)}return!0}if(s){var t=arguments.length,n=new Array(t-1);for(var r=1;r<t;r++)n[r-1]=arguments[r];var a=s.slice();for(var r=0,t=a.length;r<t;r++)this.event=e,a[r].apply(this,n);return a.length>0||this._all}return this._all},o.prototype.on=function(e,t){if(typeof e=="function")return this.onAny(e),this;if(typeof t!="function")throw new Error("on only accepts instances of Function");this._events||i.call(this),this.emit("newListener",e,t);if(this.wildcard)return a.call(this,e,t),this;if(!this._events[e])this._events[e]=t;else if(typeof this._events[e]=="function")this._events[e]=[this._events[e],t];else if(n(this._events[e])){this._events[e].push(t);if(!this._events[e].warned){var s=r;typeof this._events.maxListeners!="undefined"&&(s=this._events.maxListeners),s>0&&this._events[e].length>s&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),console.trace())}}return this},o.prototype.onAny=function(e){this._all||(this._all=[]);if(typeof e!="function")throw new Error("onAny only accepts instances of Function");return this._all.push(e),this},o.prototype.addListener=o.prototype.on,o.prototype.off=function(e,t){if(typeof t!="function")throw new Error("removeListener only takes instances of Function");var r,i=[];if(this.wildcard){var s=typeof e=="string"?e.split(this.delimiter):e.slice();i=u.call(this,null,s,this.listenerTree,0)}else{if(!this._events[e])return this;r=this._events[e],i.push({_listeners:r})}for(var o=0;o<i.length;o++){var a=i[o];r=a._listeners;if(n(r)){var f=-1;for(var l=0,c=r.length;l<c;l++)if(r[l]===t||r[l].listener&&r[l].listener===t||r[l]._origin&&r[l]._origin===t){f=l;break}if(f<0)return this;this.wildcard?a._listeners.splice(f,1):this._events[e].splice(f,1),r.length===0&&(this.wildcard?delete a._listeners:delete this._events[e])}else if(r===t||r.listener&&r.listener===t||r._origin&&r._origin===t)this.wildcard?delete a._listeners:delete this._events[e]}return this},o.prototype.offAny=function(e){var t=0,n=0,r;if(e&&this._all&&this._all.length>0){r=this._all;for(t=0,n=r.length;t<n;t++)if(e===r[t])return r.splice(t,1),this}else this._all=[];return this},o.prototype.removeListener=o.prototype.off,o.prototype.removeAllListeners=function(e){if(arguments.length===0)return!this._events||i.call(this),this;if(this.wildcard){var t=typeof e=="string"?e.split(this.delimiter):e.slice(),n=u.call(this,null,t,this.listenerTree,0);for(var r=0;r<n.length;r++){var s=n[r];s._listeners=null}}else{if(!this._events[e])return this;this._events[e]=null}return this},o.prototype.listeners=function(e){if(this.wildcard){var t=[],r=typeof e=="string"?e.split(this.delimiter):e.slice();return u.call(this,t,r,this.listenerTree,0),t}return this._events||i.call(this),this._events[e]||(this._events[e]=[]),n(this._events[e])||(this._events[e]=[this._events[e]]),this._events[e]},o.prototype.listenersAny=function(){return this._all?this._all:[]},typeof define=="function"&&define.amd?define("eventemitter2",[],function(){return o}):e.EventEmitter2=o}(typeof process!="undefined"&&typeof process.title!="undefined"&&typeof exports!="undefined"?exports:window),define("react/eventemitter",["eventemitter2"],function(e){var t=e?e.EventEmitter2?e.EventEmitter2:e:EventEmitter2;return t}),define("util",["require","exports","module"],function(e,t,n){function s(e,t,n,r){var i={showHidden:t,seen:[],stylize:r?a:f};return l(i,e,typeof n=="undefined"?2:n)}function a(e,t){var n=u[t];return n?"["+o[n][0]+"m"+e+"["+o[n][1]+"m":e}function f(e,t){return e}function l(e,n,r){if(n&&typeof n.inspect=="function"&&n.inspect!==t.inspect&&(!n.constructor||n.constructor.prototype!==n))return n.inspect(r);var i=c(e,n);if(i)return i;var s=Object.keys(n),o=e.showHidden?Object.getOwnPropertyNames(n):s;if(o.length===0){if(typeof n=="function"){var u=n.name?": "+n.name:"";return e.stylize("[Function"+u+"]","special")}if(g(n))return e.stylize(RegExp.prototype.toString.call(n),"regexp");if(y(n))return e.stylize(Date.prototype.toString.call(n),"date");if(b(n))return h(n)}var a="",f=!1,l=["{","}"];m(n)&&(f=!0,l=["[","]"]);if(typeof n=="function"){var w=n.name?": "+n.name:"";a=" [Function"+w+"]"}g(n)&&(a=" "+RegExp.prototype.toString.call(n)),y(n)&&(a=" "+Date.prototype.toUTCString.call(n)),b(n)&&(a=" "+h(n));if(o.length!==0||!!f&&n.length!==0){if(r<0)return g(n)?e.stylize(RegExp.prototype.toString.call(n),"regexp"):e.stylize("[Object]","special");e.seen.push(n);var E;return f?E=p(e,n,r,s,o):E=o.map(function(t){return d(e,n,r,s,t,f)}),e.seen.pop(),v(E,a,l)}return l[0]+a+l[1]}function c(e,t){switch(typeof t){case"undefined":return e.stylize("undefined","undefined");case"string":var n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string");case"number":return e.stylize(""+t,"number");case"boolean":return e.stylize(""+t,"boolean")}if(t===null)return e.stylize("null","null")}function h(e){return"["+Error.prototype.toString.call(e)+"]"}function p(e,t,n,r,i){var s=[];for(var o=0,u=t.length;o<u;++o)Object.prototype.hasOwnProperty.call(t,String(o))?s.push(d(e,t,n,r,String(o),!0)):s.push("");return i.forEach(function(i){i.match(/^\d+$/)||s.push(d(e,t,n,r,i,!0))}),s}function d(e,t,n,r,i,s){var o,u,a;a=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]},a.get?a.set?u=e.stylize("[Getter/Setter]","special"):u=e.stylize("[Getter]","special"):a.set&&(u=e.stylize("[Setter]","special")),r.indexOf(i)<0&&(o="["+i+"]"),u||(e.seen.indexOf(a.value)<0?(n===null?u=l(e,a.value,null):u=l(e,a.value,n-1),u.indexOf("\n")>-1&&(s?u=u.split("\n").map(function(e){return" "+e}).join("\n").substr(2):u="\n"+u.split("\n").map(function(e){return" "+e}).join("\n"))):u=e.stylize("[Circular]","special"));if(typeof o=="undefined"){if(s&&i.match(/^\d+$/))return u;o=JSON.stringify(""+i),o.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=e.stylize(o,"name")):(o=o.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),o=e.stylize(o,"string"))}return o+": "+u}function v(e,t,n){var r=0,i=e.reduce(function(e,t){return r++,t.indexOf("\n")>=0&&r++,e+t.length+1},0);return i>60?n[0]+(t===""?"":t+"\n ")+" "+e.join(",\n ")+" "+n[1]:n[0]+t+" "+e.join(", ")+" "+n[1]}function m(e){return Array.isArray(e)||typeof e=="object"&&w(e)==="[object Array]"}function g(e){return typeof e=="object"&&w(e)==="[object RegExp]"}function y(e){return typeof e=="object"&&w(e)==="[object Date]"}function b(e){return typeof e=="object"&&w(e)==="[object Error]"}function w(e){return Object.prototype.toString.call(e)}function E(e){return e<10?"0"+e.toString(10):e.toString(10)}function x(){var e=new Date,t=[E(e.getHours()),E(e.getMinutes()),E(e.getSeconds())].join(":");return[e.getDate(),S[e.getMonth()],t].join(" ")}var r=/%[sdj%]/g;t.format=function(e){if(typeof e!="string"){var t=[];for(var n=0;n<arguments.length;n++)t.push(s(arguments[n]));return t.join(" ")}var i=1,o=arguments,u=o.length,a=String(e).replace(r,function(e){if(e==="%%")return"%";if(i>=u)return e;switch(e){case"%s":return String(o[i++]);case"%d":return Number(o[i++]);case"%j":return JSON.stringify(o[i++]);default:return e}});for(var f=o[i];i<u;f=o[++i])f===null||typeof f!="object"?a+=" "+f:a+=" "+s(f);return a},t.print=function(){for(var e=0,t=arguments.length;e<t;++e)process.stdout.write(String(arguments[e]))},t.puts=function(){for(var e=0,t=arguments.length;e<t;++e)process.stdout.write(arguments[e]+"\n")},t.debug=function(e){process.stderr.write("DEBUG: "+e+"\n")};var i=t.error=function(e){for(var t=0,n=arguments.length;t<n;++t)process.stderr.write(arguments[t]+"\n")};t.inspect=s;var o={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},u={special:"cyan",number:"yellow","boolean":"yellow","undefined":"grey","null":"bold",string:"green",date:"magenta",regexp:"red"};t.isArray=m,t.isRegExp=g,t.isDate=y,t.isError=b;var S=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];t.log=function(e){t.puts(x()+" - "+e.toString())},t.pump=function(e,t,n){function i(e,t,i){n&&!r&&(n(e,t,i),r=!0)}var r=!1;e.addListener("data",function(n){t.write(n)===!1&&e.pause()}),t.addListener("drain",function(){e.resume()}),e.addListener("end",function(){t.end()}),e.addListener("close",function(){i()}),e.addListener("error",function(e){t.end(),i(e)}),t.addListener("error",function(t){e.destroy(),i(t)})},t.inherits=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})},t._extend=function(e,t){if(!t)return e;var n=Object.keys(t),r=n.length;while(r--)e[n[r]]=t[n[r]];return e}}),define("react/error",["util"],function(e){function t(e){if(!Error.stackTraceLimit||Error.stackTraceLimit<e)Error.stackTraceLimit=e}function n(e){return e?e&&e.name?e.name:e:"undefined"}function r(t){if(!t.meta)return;var r=t.meta.vcon,i=t.meta.task,s="\n\n";return i&&i.f&&i.a&&(s+="Error occurs in Task function: "+n(i.f)+"("+i.a.join(",")+")\n\n"),r&&(s+="Variable Context: \n",s+=e.inspect(r),s+="\n\n"),i&&i.f&&(s+="Task Source:\n\n",s+=i.f.toString(),s+="\n\n"),s}function i(e,t){typeof e=="string"&&(e=new Error(e));var n=e.toString();return e.meta=t,e.toString=function(){return n+r(e)},e}return{ensureStackTraceLimitSet:t,augmentError:i}}),define("react/sprintf",["util"],function(e){var t=e.format;return t}),function(e,t){typeof exports=="object"?module.exports=t():typeof define=="function"&&define.amd?define("ensure-array",[],t):e.ensureArray=t()}(this,function(){function e(e,t,n){if(arguments.length===0)return[];if(arguments.length===1){if(e===undefined||e===null)return[];if(Array.isArray(e))return e}return Array.prototype.slice.call(arguments)}return e}),define("react/status",[],function(){var e={READY:"ready",RUNNING:"running",ERRORED:"errored",COMPLETE:"complete"};return e}),define("react/event-manager",["./eventemitter"],function(e){function i(){}var t={wildcard:!0,delimiter:".",maxListeners:30},n=/^ast.defined$/,r={AST_DEFINED:"ast.defined",FLOW_BEGIN:"flow.begin",TASK_BEGIN:"task.begin",TASK_COMPLETE:"task.complete",TASK_ERRORED:"task.errored",FLOW_COMPLETE:"flow.complete",FLOW_ERRORED:"flow.errored",EXEC_FLOW_START:"exec.flow.start",EXEC_INPUT_PREPROCESS:"exec.input.preprocess",EXEC_TASKS_PRECREATE:"exec.tasks.precreate",EXEC_OUTTASK_CREATE:"exec.outTask.create",EXEC_TASK_START:"exec.task.start",EXEC_TASK_COMPLETE:"exec.task.complete",EXEC_TASK_ERRORED:"exec.task.errored",EXEC_FLOW_COMPLETE:"exec.flow.complete",EXEC_FLOW_ERRORED:"exec.flow.errored"};return i.create=function(){return new i},i.TYPES=r,i.prototype.TYPES=r,i.prototype.isEnabled=function(){return!!(this.emitter||this.parent&&this.parent.isEnabled())},i.prototype.on=function(n,r){this.emitter||(this.emitter=new e(t)),n==="*"?this.emitter.onAny(r):this.emitter.on(n,r)},i.prototype.emit=function(e,t,r,i){if(e===undefined)throw new Error("event is undefined");this.emitter&&this.emitter.emit.apply(this.emitter,arguments),this.parent&&this.parent.isEnabled()&&this.parent.emit.apply(this.parent,arguments),n.test(e)&&typeof process!="undefined"&&process.emit&&process.emit.apply(process,arguments)},i.prototype.removeListener=function(e,t){this.emitter&&this.emitter.removeListener.apply(this.emitter,arguments)},i.prototype.removeAllListeners=function(e){this.emitter&&this.emitter.removeAllListeners.apply(this.emitter,arguments)},i.global=i.create(),i}),define("react/base-task",["ensure-array","./status","./event-manager"],function(e,t,n){function r(){}function i(e){return e.indexOf(".")!==-1}return r.prototype.getOutParams=function(){return e(this.out)},r.prototype.isComplete=function(){return this.status===t.COMPLETE},r.prototype.start=function(e){this.args=e,this.env.currentTask=this,this.env.flowEmitter.emit(n.TYPES.EXEC_TASK_START,this)},r.prototype.complete=function(e){this.status=t.COMPLETE,this.results=e,this.env.currentTask=this,this.env.flowEmitter.emit(n.TYPES.EXEC_TASK_COMPLETE,this)},r.prototype.functionExists=function(e){var t=this.f;if(!t)return!1;if(t instanceof Function)return!0;if(typeof t=="string"){var n=e.getVar(t);if(n&&n instanceof Function)return!0}return!1},r.prototype.areAllDepArgsDefined=function(e){return this.a.every(function(t){return e.getVar(t)!==undefined})},r.prototype.depTasksAreDone=function(e){return!this.after||!this.after.length||this.after.every(function(t){return e[t].isComplete()})},r.prototype.parentExists=function(e,t){if(!i(e))return!0;var n=e.split(".");n.pop();var r=n.reduce(function(e,t){return e===undefined||e===null?undefined:e[t]},t.values);return r!==undefined&&r!==null},r.prototype.outParentsExist=function(e){var t=this;return this.getOutParams().every(function(n){return n===null?!0:t.parentExists(n,e)})},r.prototype.isReady=function(e,t){return!this.status&&this.functionExists(e)&&this.areAllDepArgsDefined(e)&&this.depTasksAreDone(t)&&(!this.outParentsExist||this.outParentsExist(e))},r.prototype.isMethodCall=function(){return typeof this.f=="string"&&/^.*\..*$/.test(this.f)},r.prototype.getMethodObj=function(e){var t=this.f;if(!t)return undefined;var n=t.split(".");n.pop();if(!n.length)return undefined;var r=e.resolveNameArr(n);return r},r}),define("react/cb-task",["util","./sprintf","./base-task"],function(e,t,n){function r(n,r){return t("%s - %s",n,e.inspect(r))}function a(e){var t=this;Object.keys(e).forEach(function(n){t[n]=e[n]})}var i="cbTask requires f, a, out",s="cbTask requires f to be a function or string",o="cbTask requires a to be an array of string param names",u="cbTask requires out to be an array of string param names";return a.prototype=new n,a.prototype.constructor=a,a.validate=function(e){var t=[];if(!e.f||!e.a||!e.out)t.push(r(i,e));else{var n=typeof e.f;e.f instanceof Function||n==="string"||t.push(r(s,e)),(!Array.isArray(e.a)||!e.a.every(function(e){return typeof e=="string"}))&&t.push(r(o,e)),(!Array.isArray(e.out)||!e.out.every(function(e){return typeof e=="string"}))&&t.push(r(u,e))}return t},a.prototype.prepare=function(t,n,r){var i=this;this.cbFun=function(e,s,o,u){var a=Array.prototype.slice.call(arguments,1);if(e){t(i,e);return}n.saveResults(i.out,a),i.complete(a),r()}},a.prototype.exec=function(t,n,r){try{var i=this.a.map(function(e){return t.getVar(e)});this.start(i),i.push(this.cbFun);var s=this.f,o=t.getVar("this");this.isMethodCall()?(s=t.getVar(this.f),o=this.getMethodObj(t)):typeof s=="string"&&(s=t.getVar(s)),s.apply(o,i)}catch(u){n(this,u)}},a}),define("react/promise-task",["util","./sprintf","./base-task"],function(e,t,n){function r(n,r){return t("%s - %s",n,e.inspect(r))}function a(e){var t=this;Object.keys(e).forEach(function(n){t[n]=e[n]})}var i="promiseTask requires f, a, out",s="promiseTask requires f to be a function or string",o="promiseTask requires a to be an array of string param names",u="promiseTask requires out to be an array[1] of string param names";return a.prototype=new n,a.prototype.constructor=a,a.validate=function(e){var t=[];if(!e.f||!e.a||!e.out)t.push(r(i,e));else{var n=typeof e.f;e.f instanceof Function||n==="string"||t.push(r(s,e)),(!Array.isArray(e.a)||!e.a.every(function(e){return typeof e=="string"}))&&t.push(r(o,e)),Array.isArray(e.out)&&e.out.length<=1&&e.out.every(function(e){return typeof e=="string"})||t.push(r(u,e))}return t},a.prototype.prepare=function(t,n,r){var i=this;this.nextFn=function(e){var t=Array.prototype.slice.call(arguments);n.saveResults(i.out,t),i.complete(t),r()},this.failFn=function(e){t(i,e)}},a.prototype.exec=function(t,n,r){try{var i=this.a.map(function(e){return t.getVar(e)});this.start(i);var s=this.f,o=t.getVar("this");this.isMethodCall()?(s=t.getVar(this.f),o=this.getMethodObj(t)):typeof s=="string"&&(s=t.getVar(s));var u=s.apply(o,i);u&&typeof u.then=="function"?u.then(this.nextFn,this.failFn):this.nextFn(u)}catch(a){n(this,a)}},a}),define("react/ret-task",["util","./sprintf","./base-task"],function(e,t,n){function r(n,r){return t("%s - %s",n,e.inspect(r))}function a(e){var t=this;Object.keys(e).forEach(function(n){t[n]=e[n]})}var i="retTask requires f, a, out",s="retTask requires f to be a function or string",o="retTask requires a to be an array of string param names",u="retTask requires out to be an array with single string param name or []";return a.prototype=new n,a.prototype.constructor=a,a.validate=function(e){var t=[];if(!e.f||!e.a||!e.out)t.push(r(i,e));else{var n=typeof e.f;e.f instanceof Function||n==="string"||t.push(r(s,e)),(!Array.isArray(e.a)||!e.a.every(function(e){return typeof e=="string"}))&&t.push(r(o,e)),(!Array.isArray(e.out)||!(e.out.length===0||e.out.length===1&&typeof (e.out[0]==="string")))&&t.push(r(u,e))}return t},a.prototype.exec=function(t,n,r){try{var i=this.a.map(function(e){return t.getVar(e)});this.start(i);var s=this.f,o=t.getVar("this");this.isMethodCall()?(s=t.getVar(this.f),o=this.getMethodObj(t)):typeof s=="string"&&(s=t.getVar(s));var u=[s.apply(o,i)];t.saveResults(this.out,u),this.complete(u),r()}catch(a){n(this,a)}},a}),define("react/when-task",["util","./sprintf","./base-task"],function(e,t,n){function r(n,r){return t("%s - %s",n,e.inspect(r))}function u(e){var t=this;Object.keys(e).forEach(function(n){t[n]=e[n]})}var i="whenTask requires a, out",s="whenTask requires a to be an array[1] of string param names",o="whenTask requires out to be an array[1] of string param names";return u.prototype=new n,u.prototype.constructor=u,u.prototype.f=function(){},u.validate=function(e){var t=[];return!e.a||!e.out?t.push(r(i,e)):((!Array.isArray(e.a)||e.a.length!==1||!e.a.every(function(e){return typeof e=="string"}))&&t.push(r(s,e)),Array.isArray(e.out)&&e.out.length<=1&&e.out.every(function(e){return typeof e=="string"})||t.push(r(o,e))),t},u.prototype.prepare=function(t,n,r){var i=this;this.nextFn=function(e){var t=Array.prototype.slice.call(arguments);n.saveResults(i.out,t),i.complete(t),r()},this.failFn=function(e){t(i,e)}},u.prototype.exec=function(t,n,r){try{var i=this.a.map(function(e){return t.getVar(e)});this.start(i);var s=i[0];s&&typeof s.then=="function"?s.then(this.nextFn,this.failFn):this.nextFn(s)}catch(o){n(this,o)}},u}),define("react/finalcb-task",["./sprintf","util","./status","./event-manager"],function(e,t,n,r){function s(e){var t=e.taskDef;if(typeof e.cbFunc!="function")throw new Error("callback is not a function");var n=this;for(var r in t)n[r]=t[r];this.f=e.cbFunc,this.tasks=e.tasks,this.vCon=e.vCon,this.retValue=e.retValue,this.execOptions=e.execOptions,this.env=e.env}function o(n,r){return e("%s - %s",n,t.inspect(r))}var i="ast.outTask.a should be an array of string param names";return s.validate=function(e){var t=[];return(!Array.isArray(e.a)||!e.a.every(function(e){return typeof e=="string"}))&&t.push(o(i,e)),t},s.prototype.isReady=function(){return this.tasks.every(function(e){return e.status===n.COMPLETE})},s.prototype.exec=function(e){if(!this.f)return;if(e)this.env.error=e,this.env.flowEmitter.emit(r.TYPES.EXEC_FLOW_ERRORED,this.env),this.f.call(null,e);else{var t=this.vCon,n=this.a.map(function(e){return t.getVar(e)});n.unshift(null),this.env.results=n,this.env.flowEmitter.emit(r.TYPES.EXEC_FLOW_COMPLETE,this.env),this.f.apply(null,n)}this.f=null},s}),define("react/vcon",[],function(){function t(){}var e=":LAST_RESULTS";return t.prototype.getLastResults=function(){return this.getVar(e)},t.prototype.setLastResults=function(t){this.setVar(e,t)},t.prototype.getVar=function(e){var t=this.values;if(typeof e!="string")return e;e=e.trim();if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;if(/^-?[0-9]+$/.test(e))return parseInt(e,10);if(/^-?[0-9.]+$/.test(e))return parseFloat(e);var n=/^("|')([^\1]*)\1$/.exec(e);if(n)return n[2];var r=e.split("."),i=this.resolveNameArr(r);return i},t.prototype.resolveNameArr=function(e){var t=this.values,n=e.reduce(function(e,t){return e===undefined||e===null?undefined:e[t]},t);return n===undefined&&this.global!==undefined&&(n=e.reduce(function(e,t){return e===undefined||e===null?undefined:e[t]},this.global)),n},t.prototype.saveResults=function(e,t){var n=this;e.forEach(function(e,r){n.setVar(e,t[r]!==undefined?t[r]:null)}),this.setLastResults(t)},t.prototype.setVar=function(e,t){if(!e)return;var n=this.values,r=e.split("."),i=r.pop(),s=r.reduce(function(e,t){var n=e[t];if(n===undefined||n===null)n=e[t]={};return n},n);s[i]=t},t.create=function(e,n,r,i){var s={};i&&(s["this"]=i),r&&Object.keys(r).forEach(function(e){s[e]=r[e]});var o=new t;return o.values=e.reduce(function(e,t,r){var i=n[r];return i&&(e[i]=t!==undefined?t:null),e},s),typeof global=="object"?o.global=global:o.global=(new Function("return this"))(),o},t}),define("react/finalcb-first-task",["./sprintf","util","./status","./vcon","./event-manager"],function(e,t,n,r,i){function o(e){var t=e.taskDef;if(typeof e.cbFunc!="function")throw new Error("callback is not a function");var n=this;for(var r in t)n[r]=t[r];this.f=e.cbFunc,this.tasks=e.tasks,this.vCon=e.vCon,this.retValue=e.retValue,this.env=e.env}function u(n,r){return e("%s - %s",n,t.inspect(r))}var s="ast.outTask.a should be an array of string param names";return o.validate=function(e){var t=[];return(!Array.isArray(e.a)||!e.a.every(function(e){return typeof e=="string"}))&&t.push(u(s,e)),t},o.prototype.isReady=function(){var e=this.vCon.getLastResults();return e?e.some(function(e){return e!==undefined&&e!==null}):!1},o.prototype.exec=function(e){if(!this.f)return;if(e)this.env.error=e,this.env.flowEmitter.emit(i.TYPES.EXEC_FLOW_ERRORED,this.env),this.f.call(null,e);else{var t=this.vCon,n=this.a.map(function(e){return t.getVar(e)});n.unshift(null),this.env.results=n,this.env.flowEmitter.emit(i.TYPES.EXEC_FLOW_COMPLETE,this.env),this.f.apply(null,n)}this.f=null},o}),define("react/task",["util","./sprintf","ensure-array","./cb-task","./promise-task","./ret-task","./when-task","./finalcb-task","./finalcb-first-task","./status","./error","./vcon","./event-manager"],function(e,t,n,r,i,s,o,u,a,f,l,c,h){function v(){return Object.keys(p)}function g(){return Object.keys(m)}function S(n,r){return t("%s - %s",n,e.inspect(r))}function x(e){return e.type?e:(e.type="cb",e)}function T(e){e.type||(e.type=Object.keys(m)[0])}function N(e){if(!e.after)return;var t=n(e.after);t=t.map(function(e){return typeof e=="function"?e.name:e}),e.after=t}function C(e){if(!e||typeof e!="object")return[S(b,e)];x(e),N(e);var t=[];return t=t.concat(k(e)),t=t.concat(L(e)),t}function k(e){var t=[];return Object.keys(p).some(function(t){return e.type===t})||t.push(S(E,e)),t}function L(e){var t=[],n=p[e.type];return n&&(t=t.concat(n.validate(e))),t}function A(e){var t=[];T(e);var n=m[e.type];return t=t.concat(n.validate(e)),t}function O(e,n,r){function s(){}var i=[],o=e.map(function(e){return s}),u=c.create(o,e,r),a=n.map(D),f=a.filter(function(e){return e.type!=="when"});return f.forEach(function(e,n){if(!e.functionExists(u))if(!e.isMethodCall())i.push(t(y,e.f,n));else{var r=e.getMethodObj(u);r&&r!==s&&i.push(t(y,e.f,n))}}),i}function M(e){return typeof e=="function"?e.name:e?e:""}function _(e){var n=e.reduce(function(e,t){return t.name&&(e[t.name]=t),e},{});return e.forEach(function(e,r){if(!e.name){var i=M(e.f);i||(i=t(d,r));if(!i||n[i])i=t("%s_%s",i,r);e.name=i,n[i]=e}}),n}function D(e){var t=p[e.type];return new t(e)}function P(e,t,n,r,i,s){T(e);var o={taskDef:e,cbFunc:t,tasks:n,vCon:r,execOptions:i,env:s,TaskConstructor:m[e.type]};h.global.emit(h.TYPES.EXEC_OUTTASK_CREATE,o);var u=o.TaskConstructor;return new u(o)}function H(e,t){return function(r,i){r.status=f.ERRORED,r.error=i,t.env.currentTask=r,t.env.flowEmitter.emit(h.TYPES.EXEC_TASK_ERRORED,r);var s=l.augmentError(i,{task:r,vcon:e});t.exec(s)}}function B(e,t,n){return t.filter(function(t){return t.isReady(e,n)})}function j(e,t,n,r){e.forEach(function(e){e.status=f.READY}),e.forEach(function(e){e.exec(t,n,r)})}function F(e,n,r,i){var s=n.filter(function(e){return e.status===f.RUNNING||e.status===f.READY});if(!s.length){var o=n.filter(function(e){return!e.status}),u=o.map(function(e){return e.name}),a=t(w,u.join(", ")),l={env:i};r(l,new Error(a))}}function I(e,t,n,r,i,s){var o=B(e,t,n);o.length||F(e,t,r,s),j(o,e,r,i)}function q(e){return _(e),e.forEach(function(e,t,n){t!==0&&(e.after=[n[t-1].name])}),e}var p={cb:r,ret:s,promise:i,when:o},d="task_%s",m={finalcb:u,finalcbFirst:a},y="function: %s not found in locals or input params - task[%s]",b="task must be an object",w="no tasks running, flow will not complete, remaining tasks: %s",E="task.type should match one of "+Object.keys(p).join(", ");return{serializeTasks:q,TASK_TYPES:p,taskTypeKeys:v,OUT_TASK_TYPES:m,outTaskTypeKeys:g,setMissingType:x,validate:C,validateOutTask:A,validateLocalFunctions:O,nameTasks:_,create:D,createOutTask:P,createErrorHandler:H,findReadyAndExec:I}}),define("react/validate",["util","./sprintf","ensure-array","./task"],function(e,t,n,r){function h(n,r){return t("%s - %s",n,e.inspect(r))}function p(e){return c.test(e)}function d(e){if(!e||!e.inParams||!e.tasks||!e.outTask)return[i];var t=[];return t=t.concat(v(e.inParams)),t=t.concat(m(e.tasks)),t=t.concat(g(e.tasks)),t=t.concat(r.validateOutTask(e.outTask)),t=t.concat(y(e.locals)),t.length===0&&(e.outTask.type!=="finalcbFirst"&&(t=t.concat(w(e.tasks))),t=t.concat(r.validateLocalFunctions(e.inParams,e.tasks,e.locals)),t=t.concat(E(e))),t}function v(e){return!Array.isArray(e)||!e.every(function(e){return typeof e=="string"})?[s]:[]}function m(e){if(!Array.isArray(e))return[o];var t=[];return e.forEach(function(e){t=t.concat(r.validate(e))}),t}function g(e){if(!Array.isArray(e))return[];var n=[],r=e.filter(function(e){return e.name}),i=r.map(function(e){return e.name});return i.reduce(function(e,r){return e[r]?n.push(t("%s %s",u,r)):e[r]=!0,e},{}),n}function y(e){var t=[];return e===null&&t.push(a),t}function b(e){return n(e.out)}function w(e){var n=[];return e.reduce(function(e,r){return b(r).forEach(function(r){e[r]!==undefined?n.push(t("%s: %s",f,r)):e[r]=!0}),e},{}),n}function E(e){var n=[],r={};return e.locals&&(r=Object.keys(e.locals).reduce(function(e,t){return e[t]=!0,e},r)),e.inParams.reduce(function(e,t){return e[t]=!0,e},r),e.tasks.reduce(function(e,t){return t.out.reduce(function(e,t){return e[t]=!0,e},e)},r),e.tasks.reduce(function(e,n){return n.a.reduce(function(e,n){return!p(n)&&!r[n]&&e.push(t(l,n)),e},e)},n),e.outTask.a.reduce(function(e,n){return!p(n)&&!r[n]&&e.push(t(l,n)),e},n),n}var i="ast must be an object with inParams, tasks, and outTask",s="ast.inParams must be an array of strings",o="ast.tasks must be an array of tasks",u="ast.tasks that specify name need to be unique, duplicate:",a="ast.locals should not be null",f="multiple tasks output the same param, must be unique. param",l="missing or mispelled variable referenced in flow definition: %s",c=/^(true|false|this|null|\-?[0-9\.]+)$|'|"|\./i;return d}),define("react/input-parser",["./event-manager"],function(e){function r(e){return e&&e.reactExecOptions}function i(e){return r(e)}function s(e){return!r(e)}function o(e,t){return Object.keys(t).forEach(function(n){e[n]=t[n]}),e}function u(e,t,r){var i={};return i.args=t.map(function(t){return e.shift()}),r===n.CALLBACK&&e.length&&(i.cb=e.shift()),i.extra=e,i}function a(n,r){var a={},f=n.filter(i);f.unshift(t),a.options=f.reduce(o,{});var l=n.filter(s),c=u(l,r.inParams,a.options.outputStyle);return a.args=c.args,a.cb=c.cb,c.outputStyle&&(a.options.outputStyle=c.outputStyle),c.extra&&(a.extraArgs=c.extra),e.global.emit(e.TYPES.EXEC_INPUT_PREPROCESS,a),a}var t={reactExecOptions:!0,outputStyle:"cb"},n={CALLBACK:"cb",NONE:"none"};return a.defaultExecOptions=t,a}),define("react/id",[],function(){function t(){return e+=1,e===Number.MAX_VALUE&&(e=0),e}var e=0;return{createUniqueId:t}}),define("react/core",["./eventemitter","./error","./validate","./task","./status","./vcon","./event-manager","./input-parser","./id","./sprintf"],function(e,t,n,r,i,s,o,u,a,f){function h(e){return Object.keys(l).reduce(function(e,t){return e[t]||(e[t]=l[t]),e},e)}function p(){return f("flow_%s",a.createUniqueId())}function d(){function f(t){Object.keys(t).forEach(function(e){i[e]=t[e]});var s=n(i);return s.length||(i.name||(i.name=p()),r.nameTasks(i.tasks)),Object.freeze&&(Object.keys(t).forEach(function(e){typeof t[e]=="object"&&Object.freeze(t[e])}),Object.freeze(t)),e.emit(o.TYPES.AST_DEFINED,i),s}function d(t,n,f,l){function E(){if(!b.f)return;if(b.isReady())return b.exec();r.findReadyAndExec(m,g,y,w,E,d)}var p=Array.prototype.slice.call(arguments),d={execId:a.createUniqueId(),args:p,ast:i,flowEmitter:e};d.name=i.name||d.execId,e.emit(o.TYPES.EXEC_FLOW_START,d);var v=u(p,i),m=s.create(v.args,i.inParams,i.locals,this);d.parsedInput=v,d.options=h(v.options),d.vCon=m,d.taskDefs=i.tasks.slice(),d.outTaskDef=Object.create(i.outTask),c.emit(o.TYPES.EXEC_TASKS_PRECREATE,d);var g=d.taskDefs.map(r.create),y=r.nameTasks(g),b=r.createOutTask(d.outTaskDef,v.cb,g,m,d.options,d),w=r.createErrorHandler(m,b);return g.forEach(function(t){t.id=a.createUniqueId(),t.env=d,t.prepare&&t.prepare(w,m,E,e)}),E(),b.retValue}if(arguments.length)throw new Error("react() takes no args, check API");t.ensureStackTraceLimitSet(l.stackTraceLimitMin);var e=o.create();e.parent=c;var i={name:undefined,inParams:[],tasks:[],outTask:{},locals:{}},v=d;return v.ast=i,v.setAndValidateAST=f,v.events=e,v}var l={stackTraceLimitMin:30},c=o.global;return d.options=l,d.events=c,d}),define("react/parse",["./sprintf"],function(e){function t(e){return e?e.split(",").map(function(e){return e.trim()}).filter(function(e){return e}):[]}function n(e,t){if(typeof e!="string")return e;var n=t.regex?t.regex.exec(e):e.split(t.splitStr);return n?t.fn(n,e):e}function r(t,r,i){var s=r.reduce(n,t);if(typeof s!="string")return s;throw new Error(e(i,t))}return{splitTrimFilterArgs:t,parseStr:r}}),define("react/dsl",["./sprintf","./core","./parse","./task"],function(e,t,n,r){function h(e){return e.length&&e[e.length-1].match(l)&&e.pop(),e}function p(e){return e.length&&e[0].match(c)&&e.shift(),e}function v(e){var t=n.parseStr(e,[d],s);return t.inDef=h(t.inDef),t}function m(t){var n=[],r,i,s;while(t.length>=2){i={},r=t.shift(),s=v(t.shift()),typeof t[0]=="object"&&(i=t.shift()),i.f=r,i.a=s.inDef;var o=s.type;i.out=s.outDef,i.type=o,n.push(i)}if(t.length)throw new Error(e(a,t[0]));return n}function g(e){var t=e.shift()||"",n=e.length&&typeof e[0]=="object"?e.shift():{},r=e,i={inOutParamStr:t,taskDefArr:r,options:n};return i}function y(n,r,s,o){var u=t();if(n&&f.test(n))throw new Error(e(i,n));var a=g(Array.prototype.slice.call(arguments,1)),l=v(a.inOutParamStr),c={name:n,inParams:l.inDef,tasks:m(a.taskDefArr),outTask:{a:l.outDef}};a.options&&Object.keys(a.options).forEach(function(e){c[e]=a.options[e]});var h=u.setAndValidateAST(c);if(h.length){var p=h.join("\n");throw new Error(p)}return u}function b(e,n,i,s){var o=t(),u=g(Array.prototype.slice.call(arguments,1)),a=v(u.inOutParamStr),f=r.serializeTasks(m(u.taskDefArr)),l={name:e,inParams:a.inDef,tasks:f,outTask:{type:"finalcbFirst",a:a.outDef}};u.options&&Object.keys(u.options).forEach(function(e){l[e]=u.options[e]});var c=o.setAndValidateAST(l);if(c.length){var h=c.join("\n");throw new Error(h)}return o}var i="first flow parameter should be the flow name, but found in/out def: %s",s='params in wrong format, wanted "foo, bar, cb -> err, baz" - found: %s',o='callback specified, but first out param was not "err", use for clarity. Found in/out def: %s',u="found err param, but cb/callback is not specified, is this cb-style async or sync function? Found in/out def: %s",a="extra unmatched task arg: %s",f=/\->/,l=/^cb|callback$/i,c=/^err$/i,d={splitStr:"->",fn:function(t,r){var i=n.splitTrimFilterArgs(t[0]),s=i[i.length-1],a=s&&l.test(s)?"cb":"ret",f=n.splitTrimFilterArgs(t[1]),d=f[0];if(a==="cb"&&(!d||!c.test(d)))throw new Error(e(o,r));if(a==="ret"&&d&&c.test(d))throw new Error(e(u,r));return{type:a,inDef:h(i),outDef:p(f)}}};return y.selectFirst=b,y}),define("react/track-tasks",[],function(){function t(t){if(e)return;e=!0,t.events.on(t.events.TYPES.EXEC_FLOW_START,function(e){e.startTime=Date.now(),e.flowEmitter.emit(t.events.TYPES.FLOW_BEGIN,e)}),t.events.on(t.events.TYPES.EXEC_TASK_START,function(e){e.startTime=Date.now(),e.env.flowEmitter.emit(t.events.TYPES.TASK_BEGIN,e)}),t.events.on(t.events.TYPES.EXEC_TASK_COMPLETE,function(e){e.endTime=Date.now(),e.elapsedTime=e.endTime-e.startTime,e.env.flowEmitter.emit(t.events.TYPES.TASK_COMPLETE,e)}),t.events.on(t.events.TYPES.EXEC_TASK_ERRORED,function(e){e.endTime=Date.now(),e.elapsedTime=e.endTime-e.startTime,e.env.flowEmitter.emit(t.events.TYPES.TASK_ERRORED,e)}),t.events.on(t.events.TYPES.EXEC_FLOW_COMPLETE,function(e){e.endTime=Date.now(),e.elapsedTime=e.endTime-e.startTime,e.flowEmitter.emit(t.events.TYPES.FLOW_COMPLETE,e)}),t.events.on(t.events.TYPES.EXEC_FLOW_ERRORED,function(e){e.endTime=Date.now(),e.elapsedTime=e.endTime-e.startTime,e.flowEmitter.emit(t.events.TYPES.FLOW_ERRORED,e)})}var e=!1;return t}),define("react/log-events",["util"],function(e){function s(t){var n=new Date;n.setTime(t.startTime);var r=t.args.filter(function(e){return typeof e!="function"}),i=n.toISOString();if(this.event==="flow.complete"){var s=t;console.error("%s: %s msecs: %s \n args: %s \n results: %s\n",this.event,s.name,s.elapsedTime,e.inspect(r),e.inspect(s.results))}else{var o=t.name,u=t.args;console.error("%s: %s \n args: %s\n",this.event,o,e.inspect(r))}}function o(t){var n=new Date;n.setTime(t.startTime);var r=t.args.filter(function(e){return typeof e!="function"}),i=n.toISOString();if(this.event==="task.complete"){var s=t;console.error("%s: %s:%s msecs: %s \n args: %s \n results: %s\n",this.event,s.env.name,s.name,s.elapsedTime,e.inspect(r),e.inspect(s.results))}else{var o=t.name,u=t.args;console.error("%s: %s:%s \n args: %s\n",this.event,t.env.name,t.name,e.inspect(r))}}function u(e,t){if(!e)throw new Error("flowFn is required");e.events._loggingEvents||(e.events._loggingEvents=[]);if(t===!1)e.events._loggingEvents.forEach(function(t){e.events.removeAllListeners(t)}),e.events._loggingEvents.length=0;else if(t&&t!=="*"){var u=i.test(t)?s:o;e.events.removeListener(t,u),e.events.on(t,u),e.events._loggingEvents.push(t)}else e.events.removeListener(n,s),e.events.on(n,s),e.events._loggingEvents.push(n),e.events.removeListener(r,o),e.events.on(r,o),e.events._loggingEvents.push(r)}var t={},n="flow.*",r="task.*",i=/^flow\./;return t.logEvents=u,t}),define("react/promise-resolve",[],function(){function n(n){if(t)return;t=!0,n.events.on(n.events.TYPES.EXEC_TASKS_PRECREATE,function(t){var n=t.vCon.values,r=t.ast.inParams.filter(function(e){var t=n[e];return t&&typeof t.then=="function"});r.forEach(function(r){var i=r+e;n[i]=n[r],n[r]=undefined,t.taskDefs.push({type:"when",a:[i],out:[r]})})})}var e="__promise",t=!1;return n}),define("react/event-collector",[],function(){function e(e){function i(){this.events=[]}e.trackTasks();var t=/^ast\./,n=/^task\./,r=/^flow\./;return i.prototype.capture=function(i,s){function a(e){var i={event:this.event,time:Date.now()};r.test(this.event)?i.env=e:n.test(this.event)?i.task=e:t.test(this.event)&&(i.ast=e),u.events.push(i)}!s&&typeof i=="string"?(s=i,i=e):i||(i=e),s||(s="*");var o=i.events,u=this;o.on(s,a)},i.prototype.list=function(){return this.events},i.prototype.clear=function(){this.events=[]},new i}return e}),define("react/react",["./core","./dsl","./track-tasks","./log-events","./promise-resolve","./event-collector"],function(e,t,n,r,i,s){function u(){i(o)}function a(){n(o)}function f(e,t){return typeof e!="function"&&(t=e,e=undefined),e||(e=o),a(),r.logEvents(e,t)}function l(){return s(o)}var o=t;return o.options=e.options,o.events=e.events,o.logEvents=f,o.resolvePromises=u,o.trackTasks=a,o.createEventCollector=l,o}),define("react",["react/react"],function(e){return e});
src/routes/Measurements/components/nettests/HttpHeaderFieldManipulation.js
TheTorProject/ooni-wui
import React from 'react' import { FormattedMessage } from 'react-intl' export const HttpHeaderFieldManipulationDetails = ({ measurement }) => { let anomaly = false const tampering = measurement.test_keys.tampering Object.keys(tampering).forEach((key) => { if (tampering[key] === true) { anomaly = true } }) return ( <div> {anomaly === true && <div> <h2 className='result-danger'><i className='fa fa-times-circle-o' /> <FormattedMessage id='nettests.httpHeaderFieldManipulation.networkTampering' defaultMessage='Evidence of possible network tampering' /> </h2> <p> <FormattedMessage id='nettests.httpHeaderFieldManipulation.trafficManipulation' defaultMessage='When contacting our control servers we noticed that network traffic was manipulated. This means that there could be a {middleBox} which could be responsible for censorship and/or traffic manipulation.' values={{ middleBox: <strong> <FormattedMessage id='nettests.httpHeaderFieldManipulation.middleBox' defaultMessage='“middle box”' /> </strong> }} /> </p> </div> } {anomaly === false && <div> <h2 className='result-success'><i className='fa fa-check-circle-o' /> <FormattedMessage id='nettests.httpHeaderFieldManipulation.everythingOk' defaultMessage='Everything is OK' /> </h2> <p> <FormattedMessage id='nettests.httpHeaderFieldManipulation.noAnomaly' defaultMessage='No network anomaly was detected when communicating to our control servers.' /> </p> </div> } </div> ) } HttpHeaderFieldManipulationDetails.propTypes = { measurement: React.PropTypes.object } export default HttpHeaderFieldManipulationDetails
src/StaticAlert/StaticAlert.js
Pearson-Higher-Ed/compounds
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Icon from '../Icon'; import './StaticAlert.scss'; export default class StaticAlert extends Component { static propTypes = { type: PropTypes.string.isRequired, title: PropTypes.string.isRequired, message: PropTypes.string.isRequired, inline: PropTypes.bool, disable: PropTypes.bool } static defaultProps = { inline: false, disable: false } constructor(props) { super(props) this.state = { isOpen: true } } handleClose = () => { this.setState({ isOpen: false }); } typeCheck = () => { if (this.props.type === 'Error') { return ( <span className="static-error-svg"> <Icon name="warning-18" /> </span> ); } if (this.props.type === 'Success') { return ( <span className="static-success-svg"> <Icon name="check-lg-18" /> </span> ); } } render() { const { type, title, message, inline, disable } = this.props; const infoCheck = type === 'Information' ? 'info':''; const inlineCheck = inline ? '-inline':''; const disableCheck = disable ? 'disabled': null; return ( <div> {this.state.isOpen && <div className={`static-pe-alert${inlineCheck} static-alert-${type}`}> <div className="static-alert-content-container"> {this.typeCheck()} <div className={`static-alert-content-${infoCheck}`}> <h2 className="pe-label static-alert-title"> <strong>{title}</strong> </h2> <p className="pe-paragraph static-alert-text"> {message} </p> </div> </div> <button className="pe-icon--btn static-close-title" disabled={disableCheck} onClick={this.handleClose} aria-label="Close alert"> <Icon name="remove-sm-24" /> </button> </div> } </div> ) } }
packages/flow-upgrade/src/upgrades/0.53.0/ReactComponentExplicitTypeArgs/__tests__/fixtures/AllGood.js
jamesgpearce/flow
// @flow import React from 'react'; class MyComponent extends React.Component<DefaultProps, Props, State> { static defaultProps: BadDefaultProps = {}; props: BadProps; state: BadState = {}; } const expression = () => class extends React.Component<DefaultProps, Props, State> { static defaultProps: BadDefaultProps = {}; props: BadProps; state: BadState = {}; }
docs/app/Examples/collections/Form/Content/FormExampleField.js
vageeshb/Semantic-UI-React
import React from 'react' import { Form } from 'semantic-ui-react' const FormExampleField = () => ( <Form> <Form.Field> <label>User Input</label> <input /> </Form.Field> </Form> ) export default FormExampleField
files/rxjs/2.4.3/rx.lite.extras.compat.js
cedricbousmanne/jsdelivr
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (factory) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } // Because of build optimizers if (typeof define === 'function' && define.amd) { define(['rx-lite-compat'], function (Rx, exports) { return factory(root, exports, Rx); }); } else if (typeof module === 'object' && module && module.exports === freeExports) { module.exports = factory(root, module.exports, require('./rx-lite-compat')); } else { root.Rx = factory(root, {}, root.Rx); } }.call(this, function (root, exp, Rx, undefined) { // References var Observable = Rx.Observable, observableProto = Observable.prototype, observableNever = Observable.never, observableThrow = Observable.throwException, AnonymousObservable = Rx.AnonymousObservable, AnonymousObserver = Rx.AnonymousObserver, notificationCreateOnNext = Rx.Notification.createOnNext, notificationCreateOnError = Rx.Notification.createOnError, notificationCreateOnCompleted = Rx.Notification.createOnCompleted, Observer = Rx.Observer, Subject = Rx.Subject, internals = Rx.internals, helpers = Rx.helpers, ScheduledObserver = internals.ScheduledObserver, SerialDisposable = Rx.SerialDisposable, SingleAssignmentDisposable = Rx.SingleAssignmentDisposable, CompositeDisposable = Rx.CompositeDisposable, RefCountDisposable = Rx.RefCountDisposable, disposableEmpty = Rx.Disposable.empty, immediateScheduler = Rx.Scheduler.immediate, defaultKeySerializer = helpers.defaultKeySerializer, addRef = Rx.internals.addRef, identity = helpers.identity, isPromise = helpers.isPromise, inherits = internals.inherits, bindCallback = internals.bindCallback, noop = helpers.noop, isScheduler = helpers.isScheduler, observableFromPromise = Observable.fromPromise, ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError; function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } function scheduleItem(s, self) { if (!self.isDisposed) { self.isDisposed = true; self.disposable.dispose(); } } ScheduledDisposable.prototype.dispose = function () { this.scheduler.scheduleWithState(this, scheduleItem); }; var CheckedObserver = (function (__super__) { inherits(CheckedObserver, __super__); function CheckedObserver(observer) { __super__.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); var res = tryCatch(this._observer.onNext).call(this._observer, value); this._state = 0; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); var res = tryCatch(this._observer.onError).call(this._observer, err); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); var res = tryCatch(this._observer.onCompleted).call(this._observer); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); var ObserveOnObserver = (function (__super__) { inherits(ObserveOnObserver, __super__); function ObserveOnObserver(scheduler, observer, cancel) { __super__.call(this, scheduler, observer); this._cancel = cancel; } ObserveOnObserver.prototype.next = function (value) { __super__.prototype.next.call(this, value); this.ensureActive(); }; ObserveOnObserver.prototype.error = function (e) { __super__.prototype.error.call(this, e); this.ensureActive(); }; ObserveOnObserver.prototype.completed = function () { __super__.prototype.completed.call(this); this.ensureActive(); }; ObserveOnObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this._cancel && this._cancel.dispose(); this._cancel = null; }; return ObserveOnObserver; })(ScheduledObserver); /** * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. * If a violation is detected, an Error is thrown from the offending observer method call. * * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. */ Observer.prototype.checked = function () { return new CheckedObserver(this); }; /** * Schedules the invocation of observer methods on the given scheduler. * @param {Scheduler} scheduler Scheduler to schedule observer messages on. * @returns {Observer} Observer whose messages are scheduled on the given scheduler. */ Observer.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; /** * Creates an observer from a notification callback. * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler, thisArg) { var handlerFunc = bindCallback(handler, thisArg, 1); return new AnonymousObserver(function (x) { return handlerFunc(notificationCreateOnNext(x)); }, function (e) { return handlerFunc(notificationCreateOnError(e)); }, function () { return handlerFunc(notificationCreateOnCompleted()); }); }; /** * Creates a notification callback from an observer. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { var source = this; return new AnonymousObserver( function (x) { source.onNext(x); }, function (e) { source.onError(e); }, function () { source.onCompleted(); } ); }; /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }, source); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }, source); }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); self(); } else { observer.onCompleted(); } }); }); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); resource && (disposable = resource); source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = []; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = []; if (Array.isArray(arguments[0])) { sources = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } } return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self)); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; +count || (count = 0); Math.abs(count) === Infinity && (count = 0); if (count <= 0) { throw new ArgumentOutOfRangeError(); } skip == null && (skip = count); +skip || (skip = 0); Math.abs(skip) === Infinity && (skip = 0); if (skip <= 0) { throw new ArgumentOutOfRangeError(); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = []; function createWindow () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } createWindow(); m.setDisposable(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; c >= 0 && c % skip === 0 && q.shift().onCompleted(); ++n % skip === 0 && createWindow(); }, function (e) { while (q.length > 0) { q.shift().onError(e); } observer.onError(e); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }, source); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, function (e) { o.onError(e); }, function () { o.onNext(q); o.onCompleted(); }); }, source); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * var res = obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; defaultValue === undefined && (defaultValue = null); return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, function (e) { observer.onError(e); }, function () { !found && observer.onNext(defaultValue); observer.onCompleted(); }); }, source); }; // Swap out for Array.findIndex function arrayIndexOfComparer(array, item, comparer) { for (var i = 0, len = array.length; i < len; i++) { if (comparer(array[i], item)) { return i; } } return -1; } function HashSet(comparer) { this.comparer = comparer; this.set = []; } HashSet.prototype.push = function(value) { var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; retValue && this.set.push(value); return retValue; }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [comparer] Used to compare items in the collection. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hashSet = new HashSet(comparer); return source.subscribe(function (x) { var key = x; if (keySelector) { try { key = keySelector(x); } catch (e) { o.onError(e); return; } } hashSet.push(key) && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; return Rx; }));
client/src/head/mathjax.js
HKuz/FreeCodeCamp
import React from 'react'; const cdnAddr = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/' + '2.7.4/MathJax.js?config=TeX-AMS_HTML'; const mathjax = [<script key='mathjax' src={cdnAddr} type='text/javascript' />]; export default mathjax;
others/music/src/js/components/Banner.js
fengnovo/diary
import React from 'react'; import ReactSwipe from 'react-swipe'; import '../../css/banner.css'; class Banner extends React.Component { constructor (...args) { super(...args); this.handleClick = this.handleClick.bind(this); window.back = ()=>{ window.history.go(-1); return true; } } handleClick () { location.href = location.origin+'/#/Detail'; } render() { return <ReactSwipe className="carousel" swipeOptions={{continuous: true,speed: 400,auto: 2000,}}> <div className="broadcast" onClick={this.handleClick} style={{ 'background': 'url(../src/img/cover1.jpg) no-repeat'}}> <p className="corner">推荐</p> <div className="audio-info"> <p className="title">陈慧琳:记事本</p> <p className="profile"> <span>陈慧琳</span> <span>香港歌手</span> <span>2008-01-27</span> </p> <p> <a className="btn-listen">立即收听</a> </p> </div> {/*<div className="audio-info"> <h5>精彩节目正在赶来</h5> <h3>敬请期待哦~</h3> </div>*/} </div> <div className="broadcast" onClick={this.handleClick} style={{ 'background': 'url(../src/img/cover2.png) no-repeat'}}> <div className="audio-info"> <p className="title">陈慧琳:记事本</p> <p className="profile"> <span>陈慧琳</span> <span>香港歌手</span> <span>2008-01-27</span> </p> <p> <a className="btn-listen">立即收听</a> </p> </div> </div> <div className="broadcast" onClick={this.handleClick} style={{ 'background': 'url(../src/img/cover3.png) no-repeat'}}> <div className="audio-info"> <p className="title">陈慧琳:记事本</p> <p className="profile"> <span>陈慧琳</span> <span>香港歌手</span> <span>2008-01-27</span> </p> <p> <a className="btn-listen">立即收听</a> </p> </div> </div> </ReactSwipe> } } export default Banner;
lib/Icon.js
luispablo/react-bootstrap3-components
var React = require("react"); var Icon = function (props) { if (props.visible === undefined || props.visible) { var className = "glyphicon glyphicon-"+ props.name; return React.createElement("span", { className: className, "aria-hidden": "true" }); } else { return null; } }; module.exports = Icon;
app/components/Tasks/index.js
prudhvisays/season
import React from 'react'; import Feed from '../Feed'; import TripCard from '../TripCard'; import Search from '../Search'; import { Sparklines, SparklinesLine, SparklinesSpots } from 'react-sparklines'; import classNames from 'classnames'; function boxMullerRandom() { let phase = false, x1, x2, w, z; return (function() { if (phase = !phase) { do { x1 = 2.0 * Math.random() - 1.0; x2 = 2.0 * Math.random() - 1.0; w = x1 * x1 + x2 * x2; } while (w >= 1.0); w = Math.sqrt((-2.0 * Math.log(w)) / w); return x1 * w; } else { return x2 * w; } })(); } export default class Tasks extends React.Component { //eslint-disable-line constructor() { super(); this.state = { expand: false, data: [], intervalId: '', }; this.taskExpand = this.taskExpand.bind(this); this.detailedInfo = this.detailedInfo.bind(this); this.loadOrders = this.loadOrders.bind(this); this.timer = this.timer.bind(this); this.searchText = this.searchText.bind(this); this.emitSearch = this.emitSearch.bind(this); } componentDidMount() { let datepicker = new Ink.UI.DatePicker( '.ink-datepicker' ); //eslint-disable-line const intervalId = setInterval(() => this.timer, 3000); this.setState({ intervalId }); } componentWillUnmount() { clearInterval(this.state.intervalId); } timer() { this.setState({ data: this.state.data.concat([boxMullerRandom()]) }); } taskExpand() { const taskDiv = document.querySelector('.taskExpand'); const listShow = document.querySelector('.listShow'); if (!this.props.orderBlock) { taskDiv.style.height = '98vh'; listShow.style.opacity = '1'; listShow.style.display = 'block'; this.props.orderClose(true); this.props.divTask(); } else { taskDiv.style.height = '30vh'; listShow.style.opacity = '0'; listShow.style.display = 'none'; this.props.orderExpand(false); this.props.divTask(); } } detailedInfo() { this.props.orderDetails(); } loadOrders() { console.log(this.props.assignedOrders()); } searchText(e) { this.emitSearch(e.target.value); } emitSearch(newSearch) { this.props.onSearch(newSearch); } render() { const { expand, data } = this.state; const { stats } = this.props; return ( <div className="all-40 marginTop" style={{ height: '30vh' }}> <div className={classNames('boxShadow liner tasksExpand block-background', { progressLiner: stats.request })} style={{ height: '30vh', position: 'relative', transition: 'height 0.5s linear 0s', overflow: 'hidden' }}> <div className={classNames('orders-block', 'ink-flex', { indeterminate: stats.request })}> <div className="all-100" style={{ padding: '0.5em 0.8em' }}> <div className="ink-flex"> <div className="all-70"> <div className="team-search" style={{ width: '100%' }}> <Search placeHolder={'search Orders'} searchText={this.searchText} /> </div> </div> <div className="all-30" style={{ textAlign: 'right' }}> <input type="text" className="ink-datepicker" data-format="d-m-Y" style={{ width: '92px', color: '#fff' }} /> </div> </div> </div> </div> <div style={{ padding: '0.6em 0.8em' }}> <div className="ink-flex" style={{ position: 'relative' }}> <div className="all-100"> <Sparklines data={data} limit={20} width={100} height={10} margin={0}> <SparklinesLine style={{ stroke: 'rgb(245, 37, 151)', strokeWidth: '0.5', fill: 'none' }} /> <SparklinesSpots size={1} /> </Sparklines> </div> <div className="all-100" style={{ position: 'relative', zIndex: '1', background: '#394264' }}> <Feed tasksExpand={this.taskExpand} stats={stats}/> </div> <div className="all-100 closeTag"> <a className="ink-flex push-right closeFeed" onClick={this.loadOrders}>Close</a> </div> </div> {/* <div className="search" style={{ marginTop: '14px', width: '20.90em' }}> <div className="wrapper"> <i className="fa fa-search" aria-hidden="true"></i> <input type="text" placeholder="Search" style={{ width: '100%', outline: 'none' }} /> </div> </div> */} <div className="listShow" style={{ marginTop: '2.65em', display: 'none', opacity: '0', transition: 'all 0.5s linear 0s' }}> <TripCard detailedInfo={this.detailedInfo} customerName={'Pablo Escobar'} orderStatus={'live'} orderAddress={'Malakpet'} orderPilot={'Tyson'} orderTime={'11:30'} /> <TripCard customerName={'Vayu'} orderStatus={'Pending'} orderAddress={'Madhapur'} orderPilot={'Mark'} orderTime={'11:00'} /> <TripCard customerName={'Plomo'} orderStatus={'success'} orderAddress={'Kondapur'} orderPilot={'Kalayug'} orderTime={'10:50'} /> <TripCard customerName={'Ferry'} orderStatus={'success'} orderAddress={'Madhapur'} orderPilot={'Gustavo'} orderTime={'10:40'} /> </div> </div> </div> </div> ); } }
frontend/src/Movie/Edit/EditMovieModalContent.js
Radarr/Radarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import Form from 'Components/Form/Form'; import FormGroup from 'Components/Form/FormGroup'; import FormInputGroup from 'Components/Form/FormInputGroup'; import FormLabel from 'Components/Form/FormLabel'; import Button from 'Components/Link/Button'; import SpinnerButton from 'Components/Link/SpinnerButton'; import ModalBody from 'Components/Modal/ModalBody'; import ModalContent from 'Components/Modal/ModalContent'; import ModalFooter from 'Components/Modal/ModalFooter'; import ModalHeader from 'Components/Modal/ModalHeader'; import { inputTypes, kinds } from 'Helpers/Props'; import MoveMovieModal from 'Movie/MoveMovie/MoveMovieModal'; import translate from 'Utilities/String/translate'; import styles from './EditMovieModalContent.css'; class EditMovieModalContent extends Component { // // Lifecycle constructor(props, context) { super(props, context); this.state = { isConfirmMoveModalOpen: false }; } // // Listeners onSavePress = () => { const { isPathChanging, onSavePress } = this.props; if (isPathChanging && !this.state.isConfirmMoveModalOpen) { this.setState({ isConfirmMoveModalOpen: true }); } else { this.setState({ isConfirmMoveModalOpen: false }); onSavePress(false); } }; onMoveMoviePress = () => { this.setState({ isConfirmMoveModalOpen: false }); this.props.onSavePress(true); }; // // Render render() { const { title, item, isSaving, originalPath, onInputChange, onModalClose, onDeleteMoviePress, ...otherProps } = this.props; const { monitored, qualityProfileId, minimumAvailability, // Id, path, tags } = item; return ( <ModalContent onModalClose={onModalClose}> <ModalHeader> {translate('Edit')} - {title} </ModalHeader> <ModalBody> <Form {...otherProps} > <FormGroup> <FormLabel>{translate('Monitored')}</FormLabel> <FormInputGroup type={inputTypes.CHECK} name="monitored" helpText={translate('MonitoredHelpText')} {...monitored} onChange={onInputChange} /> </FormGroup> <FormGroup> <FormLabel>{translate('MinimumAvailability')}</FormLabel> <FormInputGroup type={inputTypes.AVAILABILITY_SELECT} name="minimumAvailability" {...minimumAvailability} onChange={onInputChange} /> </FormGroup> <FormGroup> <FormLabel>{translate('QualityProfile')}</FormLabel> <FormInputGroup type={inputTypes.QUALITY_PROFILE_SELECT} name="qualityProfileId" {...qualityProfileId} onChange={onInputChange} /> </FormGroup> <FormGroup> <FormLabel>{translate('Path')}</FormLabel> <FormInputGroup type={inputTypes.PATH} name="path" {...path} onChange={onInputChange} /> </FormGroup> <FormGroup> <FormLabel>{translate('Tags')}</FormLabel> <FormInputGroup type={inputTypes.TAG} name="tags" {...tags} onChange={onInputChange} /> </FormGroup> </Form> </ModalBody> <ModalFooter> <Button className={styles.deleteButton} kind={kinds.DANGER} onPress={onDeleteMoviePress} > {translate('Delete')} </Button> <Button onPress={onModalClose} > {translate('Cancel')} </Button> <SpinnerButton isSpinning={isSaving} onPress={this.onSavePress} > {translate('Save')} </SpinnerButton> </ModalFooter> <MoveMovieModal originalPath={originalPath} destinationPath={path.value} isOpen={this.state.isConfirmMoveModalOpen} onSavePress={this.onSavePress} onMoveMoviePress={this.onMoveMoviePress} /> </ModalContent> ); } } EditMovieModalContent.propTypes = { movieId: PropTypes.number.isRequired, title: PropTypes.string.isRequired, item: PropTypes.object.isRequired, isSaving: PropTypes.bool.isRequired, isPathChanging: PropTypes.bool.isRequired, originalPath: PropTypes.string.isRequired, onInputChange: PropTypes.func.isRequired, onSavePress: PropTypes.func.isRequired, onModalClose: PropTypes.func.isRequired, onDeleteMoviePress: PropTypes.func.isRequired }; export default EditMovieModalContent;
packages/mineral-ui-icons/src/IconVolumeUp.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconVolumeUp(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3A4.5 4.5 0 0 0 14 7.97v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"/> </g> </Icon> ); } IconVolumeUp.displayName = 'IconVolumeUp'; IconVolumeUp.category = 'av';
src/containers/RegistrationStatus-spec.js
jack-hoang/registration
import React from 'react' import ReactDOM from 'react-dom' import { push } from 'react-router-redux' import { renderIntoDocument, findRenderedDOMComponentWithTag, scryRenderedDOMComponentsWithTag, Simulate } from 'react-addons-test-utils' import configureStore from 'redux-mock-store' import RegistrationStatus from './RegistrationStatus' const mockStore = configureStore() describe('When rendering RegistrationStatus', () => { it('should display status message from state', () => { const state = { registration: { userName: 'John Doe', registrationStatus: 'Thank you John Doe! You have successfully registered.' } } const store = mockStore(state) const component = renderIntoDocument( <RegistrationStatus store={store}/> ) const renderedDOM = ReactDOM.findDOMNode(component) const title = renderedDOM.querySelector('#title') expect(title).not.toBeNull() expect(title.textContent).toEqual('Registration Status') const message = renderedDOM.querySelector('#message') expect(message).not.toBeNull() expect(message.textContent).toEqual(state.registration.registrationStatus) }) })
commons/components/user/UserTermsKo.js
goominc/goommerce-react
// Copyright (C) 2016 Goom Inc. All rights reserved. import React from 'react'; export default React.createClass({ render() { return ( <div> <div> { /*<div id="title_area"> <h2 className="title"> 회원약관 </h2> </div> */ } {/* 편(part), 장(chapter), 절(section), 조(article), 항(paragraph), 호(subparagraph), 목(clause) */} <div> <p className="part-title">이용약관(구매회원용)</p> <p className="chapter">제1장 총칙</p> <p className="article-title"><strong>제1조 (목적)</strong></p> <p className="article-content">이 약관은 주식회사 에이프릴(이하 "회사")이 운영하는 링크샵스닷컴<span>(www.linkshops.com)</span>의 인터넷 또는 스마트폰 등 이동통신기기를 이용한 사이버 몰(이하 "몰")에서 제공하는 전자상거래 관련 서비스 및 기타 서비스를 이용함에 있어 몰과 이용자 사이의 권리&middot;의무를 규정하는 것을 목적으로 합니다.</p> <p className="article-title"><strong>제2조 (용어의 정의)</strong></p> <p className="paragraph-title">① 이 약관에서 사용하는 용어의 정의는 다음과 같습니다.</p> <ul className="subparagraph-title"> <li><span>1.</span> "몰"이란 회사가 판매회원의 재화 또는 용역(이하 "재화 등")을 이용자에게 제공하기 위하여 컴퓨터 등 정보통신설비를 이용하여 재화 등을 거래할 수 있도록 운영하는 가상의 영업장을 의미합니다.</li> <li> <span>2.</span> "회원"이란, 회사에 회원등록을 한 자로서, 계속적으로 회사가 제공하는 서비스를 이용할 수 있는 만 14세 이상의 개인이나 법인을 말합니다.</li> </ul> <ul className="clause"> <li><span>가.</span> "구매회원"이란 구매한 제품의 재판매 등 상행위를 목적으로 회사에서 제공하는 구매서비스를 이용할 수 있는 회원을 의미합니다(이하 ‘회원’이라 합니다). 구매회원은 '상행위를 목적으로 구매하는 것'이라는 점을 증명하기 위하여 회원가입 후 2주 이내에 회사에 사업자등록증 등 사업자임을 증명할 수 있는 자료를 제출하여야 합니다.</li> <li><span>나.</span> "판매회원"이란 회사와 표준거래계약을 체결하고 회사에서 운영하는 몰의 판매서비스를 이용하는 회원을 의미합니다. </li> </ul> <ul className="subparagraph-title"> <li><span>3.</span> "아이디(ID)"란 회원의 식별과 서비스의 이용을 위하여 회원이 설정하고 회사가 승인하여 등록된 문자와 숫자의 조합을 의미합니다.</li> <li><span>4.</span> "비밀번호"란 회원의 동일성 확인과 회원의 권익 및 비밀보호를 위하여 회원 스스로가 설정하여 회사에 등록한 영문과 숫자의 조합의 의미합니다.</li> <li><span>5.</span> "매매보호서비스"(구매안전서비스)란 회사가 구매자의 결제대금 보호를 위하여 일정기간 동안 결제대금을 예치하는 서비스를 말합니다.</li> <li><span>6.</span> "아이템할인"이란 판매자가 회사의 서비스를 통하여 물품을 판매할 때 회사와의 합의에 따라 서비스이용료의 범위 내에서 특정물품의 판매가격을 할인하는 것을 말합니다. 회사는 아이템할인으로 인한 특정물품 판매가격 할인액을 해당 서비스 화면에 게시합니다.</li> <li><span>7.</span> "쿠폰"이란 회원이 회사의 서비스를 통하여 물품을 구매할 때 표시된 금액 또는 비율만큼 물품대금에서 할인받을 수 있는 회사 전용의 온라인 또는 오프라인 쿠폰을 의미합니다. 회사는 판매회원의 개별 동의 없이 구매회원에게 쿠폰을 발행할 수 있습니다. </li> </ul> <p className="paragraph-title">② 제1항에 정의되지 않은 이 약관상의 용어의 의미는 일반적인 거래관행에 의합니다.</p> <p className="article-title"><strong>제3조 (약관의 명시, 효력과 개정)</strong></p> <p className="paragraph-title">① 회사는 이 약관의 내용과 회사의 상호, 영업소 소재지, 대표자의 성명, 사업자등록번호, 연락처(전화, 팩스, 전자우편주소 등) 등을 회원이 확인할 수 있도록 "몰"의 초기 서비스화면 또는 연결화면에 게시합니다.</p> <p className="paragraph-title">② 회사는 「약관의 규제에 관한 법률」, 「전자문서 및 전자거래기본법」, 「전자금융거래법」, 「전자서명법」, 「정보통신망 이용촉진 및 정보보호 등에 관한 법률」, 「방문판매 등에 관한 법률」, 「소비자기본법」 등 관련 법을 위배하지 않는 범위에서 이 약관을 개정할 수 있습니다.</p> <p className="paragraph-title">③ 회사가 약관을 개정하는 경우에는 적용일자 및 개정사유를 명시하여 현행 약관과 함께 몰의 초기화면에 그 적용일자 14일 전부터 적용일자 전일까지 공지합니다.</p> <p className="paragraph-title">④ 제3항에 따라 약관이 개정되는 경우, 개정약관은 적용일자 이후에 체결되는 계약에 적용되고 그 이전에 이미 체결된 계약에 대해서는 개정 전의 약관이 적용됩니다. 다만, 이미 계약을 체결한 이용자가 개정약관을 적용받기 원하는 뜻을 제3항에 정한 개정약관의 공지기간 내에 회사에 전하여, 회사가 이에 동의한 경우에는 개정약관이 적용될 수 있습니다.</p> <p className="paragraph-title">⑤ 이 약관에서 정하지 아니한 사항과 이 약관의 해석에 관하여는 「약관의 규제 등에 관한 법률」, 「상법」 등 관련 법령 또는 상관례에 따릅니다.</p><br /> <p className="chapter">제2장 서비스</p> <p className="article-title"><strong>제4조 (서비스의 제공 및 한계)</strong></p> <p className="paragraph-title">① 회사는 다음과 같은 서비스를 제공합니다.</p> <ul className="subparagraph-title"> <li><span>1.</span> 전자상거래 플랫폼 개발 및 운영서비스</li> </ul> <ul className="level1-1 clause"> <li><span>가.</span> 판매관련 업무지원서비스</li> <li><span>나.</span> 구매관련 지원서비스 </li> <li><span>다.</span> 매매계약 체결관련서비스 </li> <li><span>라.</span> 재화 또는 용역에 대한 정보 제공 서비스 </li> <li><span>마.</span> 재화 또는 용역의 배송에 관한 서비스 </li> <li><span>바.</span> 기타 전자상거래 관련 서비스 </li> </ul> <p className="paragraph-title">② 회사가 제공하는 제1항의 서비스는 회원이 재화 등을 거래할 수 있도록 몰의 이용을 허락하는 것을 목적으로 하며, 개별 판매회원이 몰에 등록한 제품 등과 관련해서는 일체의 책임을 지지 않습니다.</p> <p className="paragraph-title">③ 회사는 재화 등의 품절 또는 제품 사양의 변경 등의 경우에는 제공되는 재화 등의 내용이 변경될 수 있습니다. 이 경우 변경된 재화 등의 내용 및 제공일자 등을 명시하여 현재의 재화 등의 내용을 게시한 곳에 즉시 공지합니다.</p> <p className="paragraph-title">④ 회사의 서비스는 몰에서 구매한 제품 등을 재판매하는 등 상행위를 목적으로 제품 등을 구매하는 회원을 위하여 제공되고, 직접 사용을 목적으로 하는 소비자를 위하여 제공되지 않습니다. 회사는 상행위를 목적으로 한 구매회원에 대한 적절한 서비스 제공을 위하여 구매회원의 사업자등록증을 확인하는 등 기타의 방법으로 구매회원이 상행위를 목적으로 구매하는 것인지 여부를 확인할 수 있습니다. </p> <p className="article-title"><strong>제5조 (서비스 기간 및 중단)</strong></p> <p className="paragraph-title">① 이 약관에 따른 서비스의 이용기간은 서비스 신청일로부터 회원의 탈퇴 또는 자격상실로 인한 이용계약 종료시까지 입니다.</p> <p className="paragraph-title">② 회사는 컴퓨터 등 정보통신설비의 보수, 점검, 교체 또는 고장, 통신의 두절 등의 사유가 발생한 경우 서비스의 제공을 일시적으로 중단할 수 있습니다. 이 경우 회사는 서비스의 중단 사실 및 그 사유를 몰의 초기화면에 게시합니다.</p> <p className="paragraph-title">③ 회사는 천재지변 또는 이에 준하는 불가항력으로 인하여 서비스를 제공할 수 없는 경우에는 서비스의 제공을 제한하거나 일시 중단할 수 있습니다. 이 경우 회사는 서비스의 중단 사실 및 그 사유를 몰의 초기화면에 게시하지 않을 수 있습니다.</p> <p className="paragraph-title">④ 회사는 제2항 또는 제3항의 서비스 중단에 대하여 회사의 고의 또는 과실이 없는 경우, 고객의 손해를 배상하지 않습니다.</p><br /> <p className="chapter">제3장 서비스 이용계약</p> <p className="article-title"><strong>제6조 (이용계약의 성립)</strong></p> <p className="paragraph-title">① 이용자는 회사가 정한 몰의 가입 양식에 따라 회원정보를 기입한 후 이 약관에 동의한다는 의사표시를 함으로써 회원가입을 신청합니다.</p> <p className="paragraph-title">② 회사는 제1항의 회원가입을 신청한 이용자가 다음 각 호에 해당하지 않는 한 회원으로 등록하는 것을 승인합니다.</p> <ul className="subparagraph-title"> <li><span>1.</span> 가입신청자가 이 약관 제7조 제3항에 의하여 이전에 회원자격을 상실한 적이 있는경우, 다만 그 후 3년이 경과한 자로서 회사가 재가입을 승낙한 경우에는 예외로 합니다.</li> <li><span>2.</span> 가입신청자가 기재한 내용에 허위, 기재누락, 오기가 있는 경우</li> <li><span>3.</span> 회사의 설비 또는 기술상 지장으로 회원가입이 불가능한 경우</li> <li><span>4.</span> 기타 이 약관에 위배되거나 위법 또는 부당한 가입신청이 확인된 경우 및 회사가 합리적인 판단에 의하여 필요하다고 인정하는 경우</li> </ul> <p className="paragraph-title">③ 이용자의 회원가입신청에 대하여 회사의 승인의 의사표시가 도달한 시점에서 회사와 회원 간의 서비스 이용계약이 성립합니다.</p> <p className="paragraph-title">④ 회원은 회원가입 및 서비스 이용시 허위의 정보를 제공하여서는 안 되며, 기재한 사항에 변동이 있는 경우 즉시 변경사항을 최신의 정보로 수정하여야 합니다.</p> <p className="article-title"><strong>제7조 (이용계약의 종료)</strong></p> <p className="paragraph-title">① 회원은 언제든지 몰의 서비스 화면을 통하여 이용계약의 해지 즉, 탈퇴를 요청할 수 있으며, 회사는 즉시 회원의 탈퇴를 처리합니다.</p> <p className="paragraph-title">② 회원이 다음 각 호의 사유에 해당하는 경우, 회사는 회원의 자격을 제한 또는 정지시킬 수 있습니다.</p> <ul className="subparagraph-title"> <li><span>1.</span> 가입신청시에 허위의 내용을 기재한 경우</li> <li><span>2.</span> 몰을 이용하여 구입한 재화 등의 대금, 기타 몰의 이용과 관련하여 회원이 부담하는 채무를 기일에 지급하지 않는 경우</li> <li><span>3.</span> 다른 회원 또는 타인의 몰 이용을 방해하거나, 그 정보를 도용하는 등 타인의 권리나 명예, 신용 기타 정당한 이익을 침해하는 행위를 한 경우</li> <li><span>4.</span> 몰을 이용하여 이 약관 또는 법령이 금지하거나 공서양속에 반하는 행위를 하는 경우</li> <li><span>5.</span> 회사가 제공하는 서비스의 원활한 진행을 방해하는 행위를 하거나 시도한 경우</li> <li><span>6.</span> 기타 회사가 합리적인 판단에 기하여 서비스 제공을 거부할 필요가 있다고 인정하는 경우</li> </ul> <p className="paragraph-title">③ 회사가 제2항에 따라 회원 자격을 제한 또는 정지시킨 후 동일한 행위가 2회 이상 반복되거나 30일 이내에 그 사유가 시정되지 아니하는 경우, 회사는 회원자격을 상실시킬 수 있습니다.</p> <p className="paragraph-title">④ 회사가 제2항 또는 제3항에 따라 회원자격을 제한, 정지 또는 상실시키는 경우, 회사는 회원에게 e-mail, 전화 기타의 방법을 통하여 해지사유를 밝혀 해지의사를 통지하고, 회원등록 말소 전에 최소한 30일 이상의 기간을 정하여 소명할 기회를 부여합니다.</p> <p className="paragraph-title">⑤ 제2항 또는 제3항에 따라 이용계약이 제한, 정지 또는 종료되는 경우, 회사가 회원에게 부가적으로 제공한 각종 혜택을 회수할 수 있습니다.</p> <p className="paragraph-title">⑥ 제2항 또는 제3항에 따라 이용계약이 제한, 정지 또는 종료되는 경우라 하더라도, 그 이전에 이미 체결된 매매계약의 완결과 관련해서는 이 약관이 적용됩니다.</p> <p className="article-title"><strong>제8조 (회원에 대한 통지)</strong></p> <p className="paragraph-title">① 회사는 회원에 대하여 통지하는 경우, 회원이 회원가입시 등록하면서 지정한 전자우편 주소로 할 수 있습니다.</p> <p className="paragraph-title">② 회사는 불특정 다수의 회원에게 통지하는 경우, 일주일 이상 몰의 서비스 화면 또는 게시판에 게시함으로써 개별 통지에 갈음할 수 있습니다. 다만, 회원 본인의 거래와 관련하여 중대한 영향을 미치는 사항에 대하여는 제1항에 따라 개별통지를 하여야 합니다.</p><br /> <p className="chapter">4장 구매계약</p> <p className="article-title"><strong>제9조 (회원의 구매신청)</strong></p> <p className="paragraph-title">① 구매회원이 판매회원이 제시한 상품의 판매 조건에 응하여 청약의 의사표시(이하 "구매신청")를 하고, 이에 대하여 회사가 승낙의 의사표시를 함으로써 제품 등에 대한 매매계약이 체결됩니다.</p> <p className="paragraph-title">② 회사는 회원이 구매신청을 함에 있어 다음 각 호의 내용을 알기 쉽게 제공하여야 합니다.</p> <ul className="subparagraph-title"> <li><span>1.</span> 재화 등의 검색 및 선택</li> <li><span>2.</span> 배송에 관한 사항의 입력 방법</li> <li><span>3.</span> 약관의 내용, 청약철회권이 제한되는 서비스, 배송료 등의 비용부담과 관련한 내용</li> <li><span>4.</span> 제3호의 내용을 확인하고 이에 동의 또는 거절한다는 표시</li> <li><span>5.</span> 재화 등의 구매신청 및 이에 관한 회사의 확인 정보</li> <li><span>6.</span> 결제방법의 선택</li> </ul> <p className="article-title"><strong>제10조 (매매계약의 성립)</strong></p> <p className="paragraph-title">① 회사는 회원에게 제9조의 구매신청에 대하여 수신확인의 통지를 합니다. 회사의 수신확인 통지에는 회원의 구매신청에 대한 확인 및 판매가능 여부, 구매신청의 정정 취소 등에 관한 정보 등을 포함하여야 합니다.</p> <p className="paragraph-title">② 회사가 전송한 수신확인 통지가 회원에게 도달한 시점에 계약이 성립한 것으로 봅니다.</p> <p className="paragraph-title">③ 다만, 다음 각 호에 해당하는 경우 승낙하지 않을 수 있습니다.</p> <ul className="subparagraph-title"> <li><span>1.</span> 회원의 구매신청 내용에 허위, 기재누락, 오기가 있는 경우</li> <li><span>2.</span> 미성년자가 담배, 주류 등 청소년보호법에서 금지하는 재화 및 용역을 구매하는 경우</li> <li><span>3.</span> 기타 구매신청에 승낙하는 것이 회사의 기술상 현저히 지장이 있다고 판단하는 경우</li> </ul> <p className="paragraph-title">④ 회사로부터 수신확인 통지를 받은 회원은 수신확인 통지와 구매신청의 내용이 다른 경우 즉시 구매신청의 변경 또는 취소를 요청할 수 있고, 회사는 회원의 요청이 있는 경우 지체 없이 그 요청에 따라 변경 또는 취소업무를 처리하여야 합니다. 다만, 회원이 이미 대금을 지급한 경우 제15조의 청약철회 등에 관한 규정에 따릅니다.</p> <p className="article-title"><strong>제11조 (지급방법)</strong></p> <p className="article-content">회원은 몰에서 구매한 재화등에 대한 대금을 다음 각 호의 방법 중 가용한 방법으로 지불할 수 있으며, 회사는 회원의 지급방법에 대하여 재화 등의 대금에 어떠한 명목의 수수료도 추가하여 징수할 수 없습니다.</p> <ul className="subparagraph-title"> <li><span>1.</span> 계좌이체를 통한 입금</li> <li><span>2.</span> 선불카드, 직불카드, 신용카드 등의 카드결제</li> <li><span>3.</span> 무통장입금</li> <li><span>4.</span> 전자화폐에 의한 결제</li> <li><span>5.</span> 수령시 대금지급</li> <li><span>6.</span> 마일리지 등 몰에서 지급한 포인트를 이용한 결제</li> <li><span>7.</span> 회사와 계약을 맺거나 몰이 지정한 상품권에 의한 결제</li> <li><span>8.</span> 기타 전자적 지급방법에 의한 대금지급 등</li> </ul> <p className="article-title"><strong>제11조의2 (매매보호서비스)</strong></p> <p className="paragraph-title">① 회사는 선지급식 통신판매에 있어서 구매회원이 지급하는 결제대금을 예치하고 배송이 완료된 후 재화등의 대금을 판매회원에게 지급함으로써 구매자의 안전을 보호합니다.</p> <p className="paragraph-title">② 회사는 구매회원에게 배송이 완료된 경우 그 익일(토요일, 일요일 및 공휴일인 경우 그 다음 영업일)에 판매회원에게 결제대금을 지급합니다. 구매회원에게 배송이 완료되었는지 여부를 확인할 수 없는 경우, 회사는 물품 발송일로부터 7일이 경과한 날로부터 2영업일 이내에 판매회원에게 결제대금을 지급할 수 있습니다.</p> <p className="paragraph-title">③ 제13조 제1항 제2호에 따른 해외배송의 경우, 발송 후 14일이 경과하면 배송이 완료된 것으로 봅니다.</p> <p className="paragraph-title">④ 다만, 회사가 판매회원에게 결제대금을 지급하거나 구매회원이 취소, 반품, 교환 또는 환불의 의사를 표시한 경우에는 그 지급을 보류합니다.</p><br /> <p className="chapter">제5장 배송</p> <p className="article-title"><strong>제12조 (배송)</strong></p> <p className="paragraph-title">① 회사는 회원과의 재화 등의 공급시기에 관하여 별도의 약정이 없는 이상, 회원이 구매신청을 한 날로부터 7일 이내에 재화 등을 배송할 수 있도록 주문제작, 포장 등 기타 필요한 조취를 취합니다. 다만, 회사가 이미 재화등의 대금의 전부 또는 일부를 받은 경우 그 날로부터 3 영업일 이내에 조치를 취하여야 합니다.</p> <p className="paragraph-title">② 제1항의 경우 회사는 회원이 재화 등의 공급절차 및 배송 진행사항을 확인할 수 있도록 적절한 조치를 취하여야 합니다.</p> <p className="paragraph-title">③ 회사는 회원이 구매한 재화 등에 대한 배송수단, 수단별 배송비용 부담자, 수단별 배송기간 등을 명시합니다. 배송소요기간은 대금결제 확인일의 익일을 기산일로 하여 배송이 완료되기까지의 기간을 말합니다.</p> <p className="paragraph-title">④ 회원이 한 번에 다수의 판매회원이 판매하는 재화 등을 구매하여, 전체 제품을 동시에 배송받기를 요청하는 경우(이하 "합배송"), 회사는 각 판매회원으로부터 재화 등을 받아 이를 구매회원에게 발송합니다.</p> <p className="paragraph-title">⑤ 회사가 약정한 배송기간을 초과하여 배송한 경우 회사는 배송의 지연으로 인한 회원의 손해를 배상하여야 합니다. 다만, 천재지변 등 불가항력적인 사유로 인한 배송지연 및 회사의 고의 또는 과실 없는 사유로 인한 배송지연의 경우 그러하지 아니합니다.</p> <p className="article-title"><strong>제13조 (해외배송)</strong></p> <p className="paragraph-title">① 회사는 회사와 업무제휴관계에 있는 해외배송망을 통하여 매매계약이 체결된 재화 등의 해외 배송절차를 조력하는 서비스를 제공하며, 해외배송의 단계는 다음 각 호와 같이 구분됩니다.</p> <ul className="subparagraph-title"> <li><span>1.</span> 국내배송단계 : 구매회원이 구매한 재화 등이 회사의 물류센터로 입고되는 시점까지의 단계</li> <li><span>2.</span> 해외배송단계 : 재화 등이 물류센터 입고 후 해외배송망을 통하여 수취인에게 배송되기까지의 단계</li> </ul> <p className="paragraph-title">② 해외배송의 경우 발송 전에는 언제든지 구매계약 취소가 가능하며, 배송 중인 상태에서 구매자의 변심에 의한 반품은 국내배송단계까지로 제한됩니다. 또한 해외배송단계부터는 반품이 불가함을 원칙으로 하되, 해외배송이 완료된 재화등에 원시적인 하자가 있는 등의 사유로 인하여 회사가 교환 또는 반품을 승인하는 경우 예외로 합니다.</p> <p className="paragraph-title">③ 제품 등 구매시 결제한 예상 해외배송비가 실제 소요된 해외배송비보다 큰 경우 회사는 그 차액을 현금으로 환불하거나 그 부분 카드결제를 취소합니다.</p> <p className="paragraph-title">④ 제품 등 구매시 결제한 예상 해외배송비가 실제 소요된 해외배송비보다 부족한 경우에는 회원이 이를 추가 결제하여야만 발송이 가능합니다. 회사의 계속적인 통보에도 부족한 배송비가 3개월 이상 결제되지 않을 경우 해당 상품은 회사에 귀속될 수 있습니다.</p> <p className="paragraph-title">⑤ 해외배송 서비스 이용시 배송국가에 따라 발생할 수 있는 관세, 배송 국가들이 부과하는 제세금 등 기타비용은 수취인이 부담하여야 합니다.</p><br /> <p className="chapter">제6장 환급, 청약철회등</p> <p className="article-title" id="terms_14"><strong>제14조 (환급)</strong></p> <p className="paragraph-title">회사는 회원이 구매신청한 재화 등을 품절 등의 사유로 공급할 수 없는 경우 지체없이 그 사유를 회원에게 통지하고 사전에 재화등의 대금을 받은 경우, 대금을 받은 날로부터 7영업일 이내에 환급하거나 환급에 필요한 조취를 취하여야 합니다.</p> <p className="article-title"><strong>제15조 (청약철회 등)</strong></p> <p className="paragraph-title">① 회원은 구매한 상품이 발송되기 전까지 구매신청을 취소할 수 있으며, 배송 중인 경우에는 취소가 아닌 반품절차에 따라 처리됩니다.</p> <p className="paragraph-title">② 회사로부터 교환 또는 반품을 승인받은 경우 회원은 객관적인 입증자료를 회사로 송부하여 상품의 원시적인 하자 등 교환&middot;반품사유를 증명하여야 하고, 상품의 하자가 증명된 경우 교환 또는 반품에 소요되는 배송비 등 필요경비는 판매회원이 부담합니다.</p> <p className="paragraph-title">③ 회사로부터 교환 또는 반품을 승인받은 경우 회원은 고객센터에 연락한 후 해당지역 우체국을 통해 물품을 발송하고, 배송비 등을 증명할 수 있는 서류를 회사에 제공하여야 합니다.</p> <p className="paragraph-title">④ 회원은 재화 등을 배송을 받은 경우 다음 각 호에 해당하는 사유가 있는 경우 반품 및 교환을 요청할 수 없습니다.</p> <ul className="subparagraph-title"> <li><span>1.</span> 회원에게 책임있는 사유로 재화 등이 멸실 또는 훼손된 경우</li> <li><span>2.</span> 회원의 사용 또는 일부 소비에 의하여 재화 등의 가치가 현저히 감소한 경우</li> <li><span>3.</span> 시간의 경과에 의하여 재판매가 곤란할 정도로 재화 등의 가치가 현저히 감소한 경우</li> <li><span>4.</span> 복제가 가능한 경우 그 원본인 재화 등의 포장을 훼손한 경우</li> <li><span>5.</span> 주문에 따라 개별적으로 생산되는 재화 등 판매회원에게 회복할 수 없는 중대한 피해가 예상되는 경우로서 사전에 해당 거래에 대하여 별도로 그 사실을 고지하고 동의를 받은 경우</li> </ul> <p className="paragraph-title">⑤ 회사는 제4항 제2호 내지 제4호에 해당하는 재화 등에 대하여 몰의 서비스 화면에 청약철회&middot;반품&middot;교환 등이 제한되는 제품이라는 사실을 회원이 쉽게 알 수 있도록 명기하거나 시용상품을 제공하는 등의 조치를 취하여야 합니다. </p> <p className="paragraph-title">⑥ 회원은 제1항 및 제2항의 규정에도 불구하고 재화 등의 내용이 표시&middot;광고 내용과 다르거나 계약내용과 다르게 이행된 경우에는 당해 재화 등을 공급받은 날로부터 3월 이내 또는 그 사실을 안 날 또는 알 수 있었던 날로부터 30일 이내에 청약철회 등을 할 수 있습니다.</p> <p className="article-title"><strong>제16조 (청약철회 등의 효과)</strong></p> <p className="paragraph-title">① 회사는 회원으로부터 재화 등을 반환받은 날로부터 3영업일 이내에 이미 지급받은 재화 등의 대금을 환급합니다. 회사가 환급을 지연한 때에는 그 지연기간에 대하여 「상법」제54조에서 정한 이율로 산정한 지연이자를 가산하여 지급합니다.</p> <p className="paragraph-title">② 회사는 제1항의 대금을 환급함에 있어서 회원이 신용카드 또는 전자화폐 등의 결제수단으로 대금을 지급한 때에는 지체없이 당해 결제수단을 제공한 사업자로 하여금 재화 등의 대금청구를 정지 또는 취소하도록 요청합니다</p> <p className="paragraph-title">③ 청약철회 등의 경우 공급받은 재화 등의 반환에 필요한 비용은 회원이 부담합니다. 회사는 회원에게 청약철회 등을 이유로 위약금 또는 손해배상을 청구하지 않습니다. 다만, 재화 등의 내용이 표시&middot;광고 내용과 다르거나 계약의 내용과 다르게 이행되어 청약철회 등을 하는 경우 재화 등의 반환에 필요한 비용은 회사가 부담합니다.</p><br /> <p className="chapter">제7장 개인정보 보호등</p> <p className="article-title"><strong>제17조 (개인정보 보호)</strong></p> <p className="paragraph-title">① 회사는 회원의 개인정보 수집시 서비스 제공을 위하여 필요한 범위에서 최소한의 개인정보를 수집합니다.</p> <p className="paragraph-title">② 회사가 회원의 개인정보를 수집&middot;이용하는 경우, 회원에게 그 목적을 고지하고 동의를 받습니다.</p> <p className="paragraph-title">③ 회사는 수집한 개인정보를 목적 외의 용도로 이용하지 않으며, 새로운 이용 목적이 발생한 경우 또는 제3자에게 제공하는 경우에는 회원에게 그 목적을 고지하고 동의 받습니다. 다만, 관련 법령의 규정에 따라 이용 또는 제공하는 경우는 예외로 합니다.</p> <p className="paragraph-title">④ 회사가 제2항 또는 제3항의 동의를 받는 경우, 회사는 정보의 수집 및 이용 목적, 제3자에 대한 정보제공과 관련한 내용 등을 미리 명시하여야 하고, 회원은 언제든지 동의를 철회할 수 있습니다.</p> <p className="paragraph-title">⑤ 회원은 언제든지 회사가 처리하는 본인의 정보에 대한 열람 및 오류정정을 요구할 수 있으며, 회사는 이에 대하여 지체없이 필요한 조치를 취하여야 합니다.</p> <p className="paragraph-title">⑥ 회사 또는 회사로부터 개인정보를 제공받은 제3자는 개인정보의 수집목적 또는 제공받은 목적을 달성한 때에는 즉시 개인정보를 파기하여야 합니다.</p> <p className="paragraph-title">⑦ 회사는 개인정보의 수집&middot;이용&middot;제공에 관한 동의란을 미리 선택한 것으로 설정해두지 않습니다. 또한 개인정보 수집&middot;이용&middot;제공에 관한 회원의 동의 거절시 제한되는 서비스를 구체적으로 명시하고, 필수 수집항목이 아닌 개인정보의 수집&middot;이용&middot;제공에 관한 회원의 동의 거절을 이유로 회원가입 등 서비스 제공을 제한하거나 거절하지 않습니다.</p> <p className="paragraph-title">⑧ 회사가 회원의 개인정보를 위탁하는 경우에는 관련 법령에서 정한 바에 따라 '개인정보취급방침'을 수립하고, 개인정보 보호책임자를 지정하여 이를 게시하고 운영합니다.</p> <p className="article-title"><strong>제18조 (회원의 아이디 및 비밀번호 관리)</strong></p> <p className="paragraph-title">① 아이디(ID) 및 비밀번호에 대한 관리 책임은 회원에게 있으며, 회원은 어떠한 경우에도 본인의 아이디(ID)또는 비밀번호를 타인에게 양도하거나 대여할 수 없습니다.</p> <p className="paragraph-title">② 회원은 아이디(ID) 또는 비밀번호를 도난당하거나 제3자가 이를 무단으로 사용하고 있음을 인지한 경우, 즉시 회사에 통보하여야 하고 회사는 이에 대한 신속한 처리를 위하여 최선의 노력을 다하여야 합니다.</p><br /> <p className="chapter">제8장 기타</p> <p className="article-title"><strong>제19조 (회사의 의무)</strong></p> <p className="paragraph-title">① 회사는 이 약관 및 관련 법령에서 금지하거나 공서양속에 반하는 행위를 하지 않으며, 이 약관에서 정하는 바에 따라 지속적이고 안정적으로 재화 등을 제공하는데 최선을 다하여야 합니다.</p> <p className="paragraph-title">② 회사는 회원이 안전하게 서비스를 이용할 수 있도록 회원의 개인정보 보호를 위한 보안시스템을 갖추어야 합니다.</p> <p className="paragraph-title">③ 회사가 재화 등에 대하여 「표시&middot;광고의 공정화에 관한 법률」제3조 소정의 부당한 행위를 함으로써 회원이 손해를 입은 경우, 회사는 이를 배상하여야 합니다.</p> <p className="article-title"><strong>제20조 (회원의 의무)</strong></p> <p className="paragraph-title">① 회원은 회사로부터 제품을 구매하여 이를 소비자 등에게 재판매할 목적 즉, 상행위를 목적으로 제품 등을 구매하는 것임을 확인합니다. 따라서 본 약관에 동의하고 몰에서 제품 등을 구매하는 회원에 대해서는 「전자상거래 등에서의 소비자보호에 관한 법률」이 적용되지 않습니다.</p> <p className="paragraph-title">② 회원은 다음의 행위를 하여서는 안됩니다.</p> <ul className="subparagraph-title"> <li><span>1.</span> 허위 내용의 등록</li> <li><span>2.</span> 타인의 정보 도용</li> <li><span>3.</span> 몰에 게시된 정보의 임의적 변경</li> <li><span>4.</span> 몰에 게시된 정보 이외의 정보의 송신 또는 게시</li> <li><span>5.</span> 회사 또는 제3자의 저작권 등 지적재산권에 대한 침해</li> <li><span>6.</span> 회사 또는 제3자의 명예를 손상시키거나 업무를 방해하는 행위</li> <li><span>7.</span> 외설 또는 폭력적인 메세지, 화상, 음성 기타 공서양속에 반하는 정보를 몰에 공개 또는 게시하는 행위</li> </ul> <p className="article-title"><strong>제21조 (연결몰과 피연결몰의 관계)</strong></p> <p className="paragraph-title">① 상위몰과 하위몰이 하이퍼링크(문자, 그림 등) 방식으로 연결된 경우, 전자를 "연결몰"이라 하고, 후자를 "피연결몰"이라 합니다.</p> <p className="paragraph-title">② 연결몰은 피연결몰이 독자적으로 제공하는 재화 등에 대하여 회원과 행하는 거래에 대해서 보증책임을 지지 않는다는 내용을 연결몰의 초기화면 또는 연결되는 시점의 팝업화면 등에 명시한 경우, 연결몰은 그 거래에 대한 보증책임을 지지 않습니다.</p> <p className="article-title"><strong>제22조 (저작권의 귀속 및 이용제한)</strong></p> <p className="paragraph-title">① 회사가 몰에 게시한 저작물에 대한 저작권 기타 지적재산권은 회사에 귀속합니다.</p> <p className="paragraph-title">② 회원이 몰을 이용함으로써 얻은 정보 중 회사에게 지적재산권이 귀속된 정보를 회사의 사전 승낙 없이 복제, 송신, 출판, 배포, 방송 기타 방법에 의하여 영리목적으로 이용하거나 제3자에게 이용하게 하여서는 안 됩니다.</p> <p className="paragraph-title">③ 회사가 약정에 따라 회원에게 귀속된 저작권을 사용하는 경우 당해 회원에게 통보하여야 합니다.</p> <p className="article-title"><strong>제23조 (분쟁해결)</strong></p> <p className="paragraph-title">① 회사는 회원이 제기하는 정당한 의견이나 불만을 반영하고 그 피해를 보상하기 위하여 피해보상처리기구를 설치·운영합니다.</p> <p className="paragraph-title">② 회사는 회원으로부터 제출된 불만사항 및 의견을 우선적으로 처리합니다. 다만, 신속한 처리가 곤란한 경우 회원에게 그 사유와 처리일정을 즉시 통보합니다.</p> <p className="paragraph-title">③ 회사와 회원 간에 발생한 전자상거래 분쟁과 관련하여 회원의 피해구제신청이 있는 경우 공정거래위원회 또는 시·도지사가 의뢰하는 분쟁조정기관의 조정에 따를 수 있습니다.</p> <p className="article-title"><strong>제24조 (재판권 및 준거법)</strong></p> <p className="paragraph-title">① 이 약관과 이용계약 및 회원 상호간의 분쟁에 대하여 회사를 당사자로 하는 소송이 제기될 경우에는 회사의 본사 소재지를 관할하는 법원의 합의관할법원으로 정합니다.</p> <p className="paragraph-title">② 제1항의 분쟁으로 제기된 소송에는 한국법을 적용합니다.</p> <p className="article-title"><strong>부칙</strong></p> <p className="article-content">이 약관은 2015. 5. 18. 부터 적용됩니다. </p> </div> </div> </div> ); }, });
pages/components/app-bar.js
allanalexandre/material-ui
import 'docs/src/modules/components/bootstrap'; // --- Post bootstrap ----- import React from 'react'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; const req = require.context('docs/src/pages/components/app-bar', false, /\.(md|js|tsx)$/); const reqSource = require.context( '!raw-loader!../../docs/src/pages/components/app-bar', false, /\.(js|tsx)$/, ); const reqPrefix = 'pages/components/app-bar'; function Page() { return <MarkdownDocs req={req} reqSource={reqSource} reqPrefix={reqPrefix} />; } export default Page;
src/svg-icons/action/group-work.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionGroupWork = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM8 17.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5zM9.5 8c0-1.38 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5S9.5 9.38 9.5 8zm6.5 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/> </SvgIcon> ); ActionGroupWork = pure(ActionGroupWork); ActionGroupWork.displayName = 'ActionGroupWork'; ActionGroupWork.muiName = 'SvgIcon'; export default ActionGroupWork;
App/db/entities/content/Events/EventCategory.js
neytz/mamasound.fr
/* * Copyright (c) 2017. Caipi Labs. All rights reserved. * * This File is part of Caipi. You can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * This project is dual licensed under AGPL and Commercial Licence. * * @author : Nathanael Braun * @contact : [email protected] */ /** * @author Nathanael BRAUN * * Date: 24/11/2015 * Time: 19:18 */ import React from 'react'; import {types, validate} from 'App/db/field'; export default { label : "Style d'événements", adminRoute : "Événements/Style d'événements", // apiRoute : "eventType", aliasField : "name", labelField : "name", previewField : "icon", wwwRoute : "genres", schema : { name : [validate.mandatory, validate.noHtml], icon : [validate.mandatory] }, fields : { "_id" : types.indexes, "name" : types.labels(), "eventType" : types.enum( "Type", [ {label : "Concert", value : "Concert"}, {label : "Expo", value : "Expo"}, {label : "Theatre", value : "Theatre"} ] ), "icon" : types.media({allowedTypes : "Image"}, "Preview :"), "color" : types.color('Couleur :') } };
detox/test/src/Screens/Orientation.js
simonracz/detox
import React, { Component } from 'react'; import { Text, View, TouchableOpacity } from 'react-native'; export default class Orientation extends Component { constructor(props) { super(props); this.state = { horizontal: false }; console.log('Orientation react component constructed (console.log test)'); } detectHorizontal({nativeEvent: {layout: {width, height,x,y}}}) { this.setState({ horizontal: width > height }); } render() { return ( <View onLayout={this.detectHorizontal.bind(this)} style={{flex: 1, paddingTop: 20, justifyContent: 'flex-start', alignItems: 'center'}}> <Text testID="currentOrientation" style={{fontSize: 25, marginTop: 50}}> {this.state.horizontal ? 'Landscape' : 'Portrait'} </Text> </View> ); } }
client/src/components/Explorer/Explorer.js
takeflight/wagtail
import PropTypes from 'prop-types'; import React from 'react'; import { connect } from 'react-redux'; import * as actions from './actions'; import ExplorerPanel from './ExplorerPanel'; const Explorer = ({ isVisible, nodes, path, pushPage, popPage, onClose, }) => { const page = nodes[path[path.length - 1]]; return isVisible ? ( <ExplorerPanel path={path} page={page} nodes={nodes} onClose={onClose} popPage={popPage} pushPage={pushPage} /> ) : null; }; Explorer.propTypes = { isVisible: PropTypes.bool.isRequired, path: PropTypes.array.isRequired, nodes: PropTypes.object.isRequired, pushPage: PropTypes.func.isRequired, popPage: PropTypes.func.isRequired, onClose: PropTypes.func.isRequired, }; const mapStateToProps = (state) => ({ isVisible: state.explorer.isVisible, path: state.explorer.path, nodes: state.nodes, }); const mapDispatchToProps = (dispatch) => ({ pushPage: (id) => dispatch(actions.pushPage(id)), popPage: () => dispatch(actions.popPage()), onClose: () => dispatch(actions.closeExplorer()), }); export default connect(mapStateToProps, mapDispatchToProps)(Explorer);
experiment_templates/sliders/_shared/js/jquery-1.11.1.min.js
thegricean/LINGUIST245
/*! jQuery v1.11.1 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.1",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b=a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+-new Date,v=a.document,w=0,x=0,y=gb(),z=gb(),A=gb(),B=function(a,b){return a===b&&(l=!0),0},C="undefined",D=1<<31,E={}.hasOwnProperty,F=[],G=F.pop,H=F.push,I=F.push,J=F.slice,K=F.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},L="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",N="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=N.replace("w","w#"),P="\\["+M+"*("+N+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+O+"))|)"+M+"*\\]",Q=":("+N+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+P+")*)|.*)\\)|)",R=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),S=new RegExp("^"+M+"*,"+M+"*"),T=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),V=new RegExp(Q),W=new RegExp("^"+O+"$"),X={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),TAG:new RegExp("^("+N.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+Q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+L+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{I.apply(F=J.call(v.childNodes),v.childNodes),F[v.childNodes.length].nodeType}catch(eb){I={apply:F.length?function(a,b){H.apply(a,J.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],!a||"string"!=typeof a)return d;if(1!==(k=b.nodeType)&&9!==k)return[];if(p&&!e){if(f=_.exec(a))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return I.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return I.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=9===k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+qb(o[l]);w=ab.test(a)&&ob(b.parentNode)||b,x=o.join(",")}if(x)try{return I.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function gb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function hb(a){return a[u]=!0,a}function ib(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function jb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function kb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||D)-(~a.sourceIndex||D);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function mb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function nb(a){return hb(function(b){return b=+b,hb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function ob(a){return a&&typeof a.getElementsByTagName!==C&&a}c=fb.support={},f=fb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fb.setDocument=function(a){var b,e=a?a.ownerDocument||a:v,g=e.defaultView;return e!==n&&9===e.nodeType&&e.documentElement?(n=e,o=e.documentElement,p=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){m()},!1):g.attachEvent&&g.attachEvent("onunload",function(){m()})),c.attributes=ib(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ib(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(e.getElementsByClassName)&&ib(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=ib(function(a){return o.appendChild(a).id=u,!e.getElementsByName||!e.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==C&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c=typeof a.getAttributeNode!==C&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==C?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==C&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(e.querySelectorAll))&&(ib(function(a){a.innerHTML="<select msallowclip=''><option selected=''></option></select>",a.querySelectorAll("[msallowclip^='']").length&&q.push("[*^$]="+M+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+M+"*(?:value|"+L+")"),a.querySelectorAll(":checked").length||q.push(":checked")}),ib(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+M+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ib(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",Q)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===v&&t(v,a)?-1:b===e||b.ownerDocument===v&&t(v,b)?1:k?K.call(k,a)-K.call(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:k?K.call(k,a)-K.call(k,b):0;if(f===g)return kb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?kb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},e):n},fb.matches=function(a,b){return fb(a,null,null,b)},fb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fb(b,n,null,[a]).length>0},fb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&E.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fb.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fb.selectors={cacheLength:50,createPseudo:hb,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+M+")"+a+"("+M+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==C&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?hb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=K.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:hb(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?hb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:hb(function(a){return function(b){return fb(a,b).length>0}}),contains:hb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:hb(function(a){return W.test(a||"")||fb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:nb(function(){return[0]}),last:nb(function(a,b){return[b-1]}),eq:nb(function(a,b,c){return[0>c?c+b:c]}),even:nb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:nb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:nb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:nb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=lb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=mb(b);function pb(){}pb.prototype=d.filters=d.pseudos,d.setFilters=new pb,g=fb.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?fb.error(a):z(a,i).slice(0)};function qb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function rb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function sb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function tb(a,b,c){for(var d=0,e=b.length;e>d;d++)fb(a,b[d],c);return c}function ub(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function vb(a,b,c,d,e,f){return d&&!d[u]&&(d=vb(d)),e&&!e[u]&&(e=vb(e,f)),hb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ub(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?K.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):I.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return K.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>i;i++)if(c=d.relative[a[i].type])m=[rb(sb(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return vb(i>1&&sb(m),i>1&&qb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&wb(a.slice(i,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=G.call(i));s=ub(s)}I.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&fb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?hb(f):f}return h=fb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xb(e,d)),f.selector=a}return f},i=fb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&ob(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qb(j),!a)return I.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&ob(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ib(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ib(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||jb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ib(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||jb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ib(function(a){return null==a.getAttribute("disabled")})||jb(L,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fb}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h; if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function ab(){return!0}function bb(){return!1}function cb(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},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(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==cb()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===cb()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?ab:bb):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:bb,isPropagationStopped:bb,isImmediatePropagationStopped:bb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=ab,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=ab,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=ab,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=bb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=bb),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function db(a){var b=eb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var eb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fb=/ jQuery\d+="(?:null|\d+)"/g,gb=new RegExp("<(?:"+eb+")[\\s/>]","i"),hb=/^\s+/,ib=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,jb=/<([\w:]+)/,kb=/<tbody/i,lb=/<|&#?\w+;/,mb=/<(?:script|style|link)/i,nb=/checked\s*(?:[^=]|=\s*.checked.)/i,ob=/^$|\/(?:java|ecma)script/i,pb=/^true\/(.*)/,qb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,rb={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>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sb=db(y),tb=sb.appendChild(y.createElement("div"));rb.optgroup=rb.option,rb.tbody=rb.tfoot=rb.colgroup=rb.caption=rb.thead,rb.th=rb.td;function ub(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ub(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function vb(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wb(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xb(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function yb(a){var b=pb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function zb(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Ab(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Bb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xb(b).text=a.text,yb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!gb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(tb.innerHTML=a.outerHTML,tb.removeChild(f=tb.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ub(f),h=ub(a),g=0;null!=(e=h[g]);++g)d[g]&&Bb(e,d[g]);if(b)if(c)for(h=h||ub(a),d=d||ub(f),g=0;null!=(e=h[g]);g++)Ab(e,d[g]);else Ab(a,f);return d=ub(f,"script"),d.length>0&&zb(d,!i&&ub(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=db(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(lb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(jb.exec(f)||["",""])[1].toLowerCase(),l=rb[i]||rb._default,h.innerHTML=l[1]+f.replace(ib,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&hb.test(f)&&p.push(b.createTextNode(hb.exec(f)[0])),!k.tbody){f="table"!==i||kb.test(f)?"<table>"!==l[1]||kb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ub(p,"input"),vb),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ub(o.appendChild(f),"script"),g&&zb(h),c)){e=0;while(f=h[e++])ob.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ub(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&zb(ub(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ub(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ub(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&nb.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ub(i,"script"),xb),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ub(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,yb),j=0;f>j;j++)d=g[j],ob.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qb,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Cb,Db={};function Eb(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fb(a){var b=y,c=Db[a];return c||(c=Eb(a,b),"none"!==c&&c||(Cb=(Cb||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Cb[0].contentWindow||Cb[0].contentDocument).document,b.write(),b.close(),c=Eb(a,b),Cb.detach()),Db[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="-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",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Gb=/^margin/,Hb=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ib,Jb,Kb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ib=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Hb.test(g)&&Gb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ib=function(a){return a.currentStyle},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Hb.test(g)&&!Kb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Lb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.style.cssText="-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",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Mb=/alpha\([^)]*\)/i,Nb=/opacity\s*=\s*([^)]*)/,Ob=/^(none|table(?!-c[ea]).+)/,Pb=new RegExp("^("+S+")(.*)$","i"),Qb=new RegExp("^([+-])=("+S+")","i"),Rb={position:"absolute",visibility:"hidden",display:"block"},Sb={letterSpacing:"0",fontWeight:"400"},Tb=["Webkit","O","Moz","ms"];function Ub(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Tb.length;while(e--)if(b=Tb[e]+c,b in a)return b;return d}function Vb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fb(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wb(a,b,c){var d=Pb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Yb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ib(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Jb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Hb.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xb(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Jb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ub(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ub(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Jb(a,b,d)),"normal"===f&&b in Sb&&(f=Sb[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Ob.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Rb,function(){return Yb(a,b,d)}):Yb(a,b,d):void 0},set:function(a,c,d){var e=d&&Ib(a);return Wb(a,c,d?Xb(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Nb.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Mb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Mb.test(f)?f.replace(Mb,e):f+" "+e)}}),m.cssHooks.marginRight=Lb(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Jb,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Gb.test(a)||(m.cssHooks[a+b].set=Wb)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ib(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Vb(this,!0)},hide:function(){return Vb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Zb(a,b,c,d,e){return new Zb.prototype.init(a,b,c,d,e)}m.Tween=Zb,Zb.prototype={constructor:Zb,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px") },cur:function(){var a=Zb.propHooks[this.prop];return a&&a.get?a.get(this):Zb.propHooks._default.get(this)},run:function(a){var b,c=Zb.propHooks[this.prop];return this.pos=b=this.options.duration?m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Zb.propHooks._default.set(this),this}},Zb.prototype.init.prototype=Zb.prototype,Zb.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Zb.propHooks.scrollTop=Zb.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Zb.prototype.init,m.fx.step={};var $b,_b,ac=/^(?:toggle|show|hide)$/,bc=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cc=/queueHooks$/,dc=[ic],ec={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bc.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bc.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fc(){return setTimeout(function(){$b=void 0}),$b=m.now()}function gc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hc(a,b,c){for(var d,e=(ec[b]||[]).concat(ec["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ic(a,b,c){var d,e,f,g,h,i,j,l,n=this,o={},p=a.style,q=a.nodeType&&U(a),r=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,n.always(function(){n.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=m.css(a,"display"),l="none"===j?m._data(a,"olddisplay")||Fb(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fb(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",k.shrinkWrapBlocks()||n.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ac.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(o))"inline"===("none"===j?Fb(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=m._data(a,"fxshow",{}),f&&(r.hidden=!q),q?m(a).show():n.done(function(){m(a).hide()}),n.done(function(){var b;m._removeData(a,"fxshow");for(b in o)m.style(a,b,o[b])});for(d in o)g=hc(q?r[d]:0,d,n),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jc(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kc(a,b,c){var d,e,f=0,g=dc.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$b||fc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$b||fc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jc(k,j.opts.specialEasing);g>f;f++)if(d=dc[f].call(j,a,k,j.opts))return d;return m.map(k,hc,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kc,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],ec[c]=ec[c]||[],ec[c].unshift(b)},prefilter:function(a,b){b?dc.unshift(a):dc.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kc(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gc(b,!0),a,d,e)}}),m.each({slideDown:gc("show"),slideUp:gc("hide"),slideToggle:gc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($b=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$b=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_b||(_b=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_b),_b=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lc=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lc,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mc,nc,oc=m.expr.attrHandle,pc=/^(?:checked|selected)$/i,qc=k.getSetAttribute,rc=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nc:mc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rc&&qc||!pc.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qc?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nc={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rc&&qc||!pc.test(c)?a.setAttribute(!qc&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=oc[b]||m.find.attr;oc[b]=rc&&qc||!pc.test(b)?function(a,b,d){var e,f;return d||(f=oc[b],oc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,oc[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rc&&qc||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mc&&mc.set(a,b,c)}}),qc||(mc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},oc.id=oc.name=oc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mc.set},m.attrHooks.contenteditable={set:function(a,b,c){mc.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sc=/^(?:input|select|textarea|button|object)$/i,tc=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sc.test(a.nodeName)||tc.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var uc=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(uc," ").indexOf(b)>=0)return!0;return!1}}),m.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(a,b){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vc=m.now(),wc=/\?/,xc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yc,zc,Ac=/#.*$/,Bc=/([?&])_=[^&]*/,Cc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Dc=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Ec=/^(?:GET|HEAD)$/,Fc=/^\/\//,Gc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hc={},Ic={},Jc="*/".concat("*");try{zc=location.href}catch(Kc){zc=y.createElement("a"),zc.href="",zc=zc.href}yc=Gc.exec(zc.toLowerCase())||[];function Lc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mc(a,b,c,d){var e={},f=a===Ic;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nc(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Oc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zc,type:"GET",isLocal:Dc.test(yc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jc,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"},converters:{"* text":String,"text html":!0,"text json":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nc(Nc(a,m.ajaxSettings),b):Nc(m.ajaxSettings,a)},ajaxPrefilter:Lc(Hc),ajaxTransport:Lc(Ic),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zc)+"").replace(Ac,"").replace(Fc,yc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yc[1]&&c[2]===yc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yc[3]||("http:"===yc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mc(Hc,k,b,v),2===t)return v;h=k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Ec.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bc.test(e)?e.replace(Bc,"$1_="+vc++):e+(wc.test(e)?"&":"?")+"_="+vc++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mc(Ic,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Oc(k,v,c)),u=Pc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qc=/%20/g,Rc=/\[\]$/,Sc=/\r?\n/g,Tc=/^(?:submit|button|image|reset|file)$/i,Uc=/^(?:input|select|textarea|keygen)/i;function Vc(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rc.test(a)?d(a,e):Vc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vc(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vc(c,a[c],b,e);return d.join("&").replace(Qc,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Uc.test(this.nodeName)&&!Tc.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sc,"\r\n")}}):{name:b.name,value:c.replace(Sc,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zc()||$c()}:Zc;var Wc=0,Xc={},Yc=m.ajaxSettings.xhr();a.ActiveXObject&&m(a).on("unload",function(){for(var a in Xc)Xc[a](void 0,!0)}),k.cors=!!Yc&&"withCredentials"in Yc,Yc=k.ajax=!!Yc,Yc&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xc[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zc(){try{return new a.XMLHttpRequest}catch(b){}}function $c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _c=[],ad=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_c.pop()||m.expando+"_"+vc++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ad.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ad.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ad,"$1"+e):b.jsonp!==!1&&(b.url+=(wc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_c.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bd=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bd)return bd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cd=a.document.documentElement;function dd(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dd(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cd;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cd})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dd(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=Lb(k.pixelPosition,function(a,c){return c?(c=Jb(a,b),Hb.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ed=a.jQuery,fd=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fd),b&&a.jQuery===m&&(a.jQuery=ed),m},typeof b===K&&(a.jQuery=a.$=m),m});
src/index.js
s89206x/WebpackSemple_map
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import App from './components/app'; import reducers from './reducers'; const createStoreWithMiddleware = applyMiddleware()(createStore); ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <App /> </Provider> , document.querySelector('.container'));
src/icons/TimelineIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class TimelineIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M46 16c0 2.2-1.8 4-4 4-.36 0-.7-.04-1.02-.14l-7.12 7.1c.1.32.14.68.14 1.04 0 2.2-1.8 4-4 4s-4-1.8-4-4c0-.36.04-.72.14-1.04l-5.1-5.1c-.32.1-.68.14-1.04.14s-.72-.04-1.04-.14l-9.1 9.12c.1.32.14.66.14 1.02 0 2.2-1.8 4-4 4s-4-1.8-4-4 1.8-4 4-4c.36 0 .7.04 1.02.14l9.12-9.1c-.1-.32-.14-.68-.14-1.04 0-2.2 1.8-4 4-4s4 1.8 4 4c0 .36-.04.72-.14 1.04l5.1 5.1c.32-.1.68-.14 1.04-.14s.72.04 1.04.14l7.1-7.12c-.1-.32-.14-.66-.14-1.02 0-2.2 1.8-4 4-4s4 1.8 4 4z"/></svg>;} };
Libraries/Image/Image.android.js
gitim/react-native
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Image * @flow */ 'use strict'; var NativeMethodsMixin = require('NativeMethodsMixin'); var NativeModules = require('NativeModules'); var ImageResizeMode = require('ImageResizeMode'); var ImageStylePropTypes = require('ImageStylePropTypes'); var ViewStylePropTypes = require('ViewStylePropTypes'); var React = require('React'); var ReactNativeViewAttributes = require('ReactNativeViewAttributes'); var StyleSheet = require('StyleSheet'); var StyleSheetPropType = require('StyleSheetPropType'); var View = require('View'); var flattenStyle = require('flattenStyle'); var merge = require('merge'); var requireNativeComponent = require('requireNativeComponent'); var resolveAssetSource = require('resolveAssetSource'); var Set = require('Set'); var filterObject = require('fbjs/lib/filterObject'); var PropTypes = React.PropTypes; var { ImageLoader, } = NativeModules; let _requestId = 1; function generateRequestId() { return _requestId++; } /** * <Image> - A react component for displaying different types of images, * including network images, static resources, temporary local images, and * images from local disk, such as the camera roll. Example usage: * * renderImages: function() { * return ( * <View> * <Image * style={styles.icon} * source={require('./myIcon.png')} * /> * <Image * style={styles.logo} * source={{uri: 'http://facebook.github.io/react/img/logo_og.png'}} * /> * </View> * ); * }, * * More example code in ImageExample.js */ var ImageViewAttributes = merge(ReactNativeViewAttributes.UIView, { src: true, loadingIndicatorSrc: true, resizeMethod: true, resizeMode: true, progressiveRenderingEnabled: true, fadeDuration: true, shouldNotifyLoadEvents: true, }); var ViewStyleKeys = new Set(Object.keys(ViewStylePropTypes)); var ImageSpecificStyleKeys = new Set(Object.keys(ImageStylePropTypes).filter(x => !ViewStyleKeys.has(x))); var Image = React.createClass({ propTypes: { ...View.propTypes, style: StyleSheetPropType(ImageStylePropTypes), /** * `uri` is a string representing the resource identifier for the image, which * could be an http address, a local file path, or a static image * resource (which should be wrapped in the `require('./path/to/image.png')` function). * This prop can also contain several remote `uri`, specified together with * their width and height. The native side will then choose the best `uri` to display * based on the measured size of the image container. */ source: PropTypes.oneOfType([ PropTypes.shape({ uri: PropTypes.string, }), // Opaque type returned by require('./image.jpg') PropTypes.number, // Multiple sources PropTypes.arrayOf( PropTypes.shape({ uri: PropTypes.string, width: PropTypes.number, height: PropTypes.number, })) ]), /** * similarly to `source`, this property represents the resource used to render * the loading indicator for the image, displayed until image is ready to be * displayed, typically after when it got downloaded from network. */ loadingIndicatorSource: PropTypes.oneOfType([ PropTypes.shape({ uri: PropTypes.string, }), // Opaque type returned by require('./image.jpg') PropTypes.number, ]), progressiveRenderingEnabled: PropTypes.bool, fadeDuration: PropTypes.number, /** * Invoked on load start */ onLoadStart: PropTypes.func, /** * Invoked on load error */ onError: PropTypes.func, /** * Invoked when load completes successfully */ onLoad: PropTypes.func, /** * Invoked when load either succeeds or fails */ onLoadEnd: PropTypes.func, /** * Used to locate this view in end-to-end tests. */ testID: PropTypes.string, /** * The mechanism that should be used to resize the image when the image's dimensions * differ from the image view's dimensions. Defaults to `auto`. * * - `auto`: Use heuristics to pick between `resize` and `scale`. * * - `resize`: A software operation which changes the encoded image in memory before it * gets decoded. This should be used instead of `scale` when the image is much larger * than the view. * * - `scale`: The image gets drawn downscaled or upscaled. Compared to `resize`, `scale` is * faster (usually hardware accelerated) and produces higher quality images. This * should be used if the image is smaller than the view. It should also be used if the * image is slightly bigger than the view. * * More details about `resize` and `scale` can be found at http://frescolib.org/docs/resizing-rotating.html. * * @platform android */ resizeMethod: PropTypes.oneOf(['auto', 'resize', 'scale']), /** * Determines how to resize the image when the frame doesn't match the raw * image dimensions. * * 'cover': Scale the image uniformly (maintain the image's aspect ratio) * so that both dimensions (width and height) of the image will be equal * to or larger than the corresponding dimension of the view (minus padding). * * 'contain': Scale the image uniformly (maintain the image's aspect ratio) * so that both dimensions (width and height) of the image will be equal to * or less than the corresponding dimension of the view (minus padding). * * 'stretch': Scale width and height independently, This may change the * aspect ratio of the src. * * 'center': Scale the image down so that it is completely visible, * if bigger than the area of the view. * The image will not be scaled up. */ resizeMode: PropTypes.oneOf(['cover', 'contain', 'stretch', 'center']), }, statics: { resizeMode: ImageResizeMode, getSize( url: string, success: (width: number, height: number) => void, failure: (error: any) => void, ) { return ImageLoader.getSize(url) .then(function(sizes) { success(sizes.width, sizes.height); }) .catch(failure || function() { console.warn('Failed to get size for image: ' + url); }); }, /** * Prefetches a remote image for later use by downloading it to the disk * cache */ prefetch(url: string, callback: ?Function) { const requestId = generateRequestId(); callback && callback(requestId); return ImageLoader.prefetchImage(url, requestId); }, /** * Abort prefetch request */ abortPrefetch(requestId: number) { ImageLoader.abortRequest(requestId); }, /** * Perform cache interrogation. * * @param urls the list of image URLs to check the cache for. * @return a mapping from url to cache status, such as "disk" or "memory". If a requested URL is * not in the mapping, it means it's not in the cache. */ async queryCache(urls: Array<string>): Promise<Map<string, 'memory' | 'disk'>> { return await ImageLoader.queryCache(urls); }, /** * Resolves an asset reference into an object which has the properties `uri`, `width`, * and `height`. The input may either be a number (opaque type returned by * require('./foo.png')) or an `ImageSource` like { uri: '<http location || file path>' } */ resolveAssetSource: resolveAssetSource, }, mixins: [NativeMethodsMixin], /** * `NativeMethodsMixin` will look for this when invoking `setNativeProps`. We * make `this` look like an actual native component class. Since it can render * as 3 different native components we need to update viewConfig accordingly */ viewConfig: { uiViewClassName: 'RCTView', validAttributes: ReactNativeViewAttributes.RCTView, }, _updateViewConfig: function(props) { if (props.children) { this.viewConfig = { uiViewClassName: 'RCTView', validAttributes: ReactNativeViewAttributes.RCTView, }; } else { this.viewConfig = { uiViewClassName: 'RCTImageView', validAttributes: ImageViewAttributes, }; } }, componentWillMount: function() { this._updateViewConfig(this.props); }, componentWillReceiveProps: function(nextProps) { this._updateViewConfig(nextProps); }, contextTypes: { isInAParentText: React.PropTypes.bool }, render: function() { const source = resolveAssetSource(this.props.source); const loadingIndicatorSource = resolveAssetSource(this.props.loadingIndicatorSource); // As opposed to the ios version, here we render `null` when there is no source, source.uri // or source array. if (source && source.uri === '') { console.warn('source.uri should not be an empty string'); } if (this.props.src) { console.warn('The <Image> component requires a `source` property rather than `src`.'); } if (source && (source.uri || Array.isArray(source))) { let style; let sources; if (source.uri) { const {width, height} = source; style = flattenStyle([{width, height}, styles.base, this.props.style]); sources = [{uri: source.uri}]; } else { style = flattenStyle([styles.base, this.props.style]); sources = source; } const {onLoadStart, onLoad, onLoadEnd, onError} = this.props; const nativeProps = merge(this.props, { style, shouldNotifyLoadEvents: !!(onLoadStart || onLoad || onLoadEnd || onError), src: sources, loadingIndicatorSrc: loadingIndicatorSource ? loadingIndicatorSource.uri : null, }); if (nativeProps.children) { // TODO(6033040): Consider implementing this as a separate native component const containerStyle = filterObject(style, (val, key) => !ImageSpecificStyleKeys.has(key)); const imageStyle = filterObject(style, (val, key) => ImageSpecificStyleKeys.has(key)); const imageProps = merge(nativeProps, { style: [imageStyle, styles.absoluteImage], children: undefined, }); return ( <View style={containerStyle}> <RKImage {...imageProps}/> {this.props.children} </View> ); } else { if (this.context.isInAParentText) { return <RCTTextInlineImage {...nativeProps}/>; } else { return <RKImage {...nativeProps}/>; } } } return null; } }); var styles = StyleSheet.create({ base: { overflow: 'hidden', }, absoluteImage: { left: 0, right: 0, top: 0, bottom: 0, position: 'absolute' } }); var cfg = { nativeOnly: { src: true, loadingIndicatorSrc: true, shouldNotifyLoadEvents: true, }, }; var RKImage = requireNativeComponent('RCTImageView', Image, cfg); var RCTTextInlineImage = requireNativeComponent('RCTTextInlineImage', Image, cfg); module.exports = Image;
ajax/libs/rxjs/2.2.2/rx.js
viskin/cdnjs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. (function (window, undefined) { var freeExports = typeof exports == 'object' && exports, freeModule = typeof module == 'object' && module && module.exports == freeExports && module, freeGlobal = typeof global == 'object' && global; if (freeGlobal.global === freeGlobal) { window = freeGlobal; } /** * @name Rx * @type Object */ var Rx = { Internals: {} }; // Defaults function noop() { } function identity(x) { return x; } var defaultNow = Date.now; function defaultComparer(x, y) { return isEqual(x, y); } function defaultSubComparer(x, y) { return x - y; } function defaultKeySerializer(x) { return x.toString(); } function defaultError(err) { throw err; } // Errors var sequenceContainsNoElements = 'Sequence contains no elements.'; var argumentOutOfRange = 'Argument out of range'; var objectDisposed = 'Object has been disposed'; function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } /** Used to determine if values are of the language type Object */ var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 suportNodeClass; try { suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch(e) { suportNodeClass = true; } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } function isArguments(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } function isFunction(value) { return typeof value == 'function'; } // fallback for older versions of Chrome and Safari if (isFunction(/x/)) { isFunction = function(value) { return typeof value == 'function' && toString.call(value) == funcClass; }; } var isEqual = Rx.Internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { var result; // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && !(a && objectTypes[type]) && !(b && objectTypes[otherType])) { return false; } // exit early for `null` and `undefined`, avoiding ES3's Function#call behavior // http://es5.github.io/#x15.3.4.4 if (a == null || b == null) { return a === b; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0`, treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b // but treat `+0` vs. `-0` as not equal : (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!suportNodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !supportsArgsClass && isArguments(a) ? Object : a.constructor, ctorB = !supportsArgsClass && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !( isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB )) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { length = a.length; size = b.length; // compare lengths to determine if a deep comparison is necessary result = size == a.length; // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } return result; } // deep compare each object for(var key in b) { if (hasOwnProperty.call(b, key)) { // count properties and deep compare each property value size++; return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], b[key], stackA, stackB)); } } if (result) { // ensure both objects have the same number of properties for (var key in a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } } } stackA.pop(); stackB.pop(); return result; } var slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var hasProp = {}.hasOwnProperty; /** @private */ var inherits = this.inherits = Rx.Internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; /** @private */ var addProperties = Rx.Internals.addProperties = function (obj) { var sources = slice.call(arguments, 1); for (var i = 0, len = sources.length; i < len; i++) { var source = sources[i]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.Internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; // Collection polyfills function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // Collections var IndexedItem = function (id, value) { this.id = id; this.value = value; }; IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); if (c === 0) { c = this.id - other.id; } return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.Internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { if (index === undefined) { index = 0; } if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; delete this.items[this.length]; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { this.disposables = argsOrArray(arguments, 0); this.isDisposed = false; this.length = this.disposables.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. */ CompositeDisposablePrototype.clear = function () { var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } }; /** * Determines whether the CompositeDisposable contains a specific disposable. * @param {Mixed} item Disposable to search for. * @returns {Boolean} true if the disposable was found; otherwise, false. */ CompositeDisposablePrototype.contains = function (item) { return this.disposables.indexOf(item) !== -1; }; /** * Converts the existing CompositeDisposable to an array of disposables * @returns {Array} An array of disposable objects. */ CompositeDisposablePrototype.toArray = function () { return this.disposables.slice(0); }; /** * Provides a set of static methods for creating Disposables. * * @constructor * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; /** * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. * * @constructor */ var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = function () { this.isDisposed = false; this.current = null; }; var SingleAssignmentDisposablePrototype = SingleAssignmentDisposable.prototype; /** * Gets the underlying disposable. After disposal, the result of getting this method is undefined. * @returns {Disposable} The underlying disposable. */ SingleAssignmentDisposablePrototype.getDisposable = function () { return this.current; }; /* @private */ SingleAssignmentDisposable.disposable = function (value) { return arguments.length ? this.getDisposable() : this.setDisposable(value); }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ SingleAssignmentDisposablePrototype.setDisposable = function (value) { if (this.current) { throw new Error('Disposable has already been assigned'); } var shouldDispose = this.isDisposed; if (!shouldDispose) { this.current = value; } if (shouldDispose && value) { value.dispose(); } }; /** * Disposes the underlying disposable. */ SingleAssignmentDisposablePrototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } if (old) { old.dispose(); } }; /** * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. * @constructor */ var SerialDisposable = Rx.SerialDisposable = function () { this.isDisposed = false; this.current = null; }; var serialDisposablePrototype = SerialDisposable.prototype; /** * Gets the underlying disposable. * @return The underlying disposable. */ serialDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ serialDisposablePrototype.setDisposable = function (value) { var shouldDispose = this.isDisposed, old; if (!shouldDispose) { old = this.current; this.current = value; } if (old) { old.dispose(); } if (shouldDispose && value) { value.dispose(); } }; /* @private */ serialDisposablePrototype.disposable = function (value) { if (!value) { return this.getDisposable(); } else { this.setDisposable(value); } }; /** * Disposes the underlying disposable as well as all future replacements. */ serialDisposablePrototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } if (old) { old.dispose(); } }; /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed) { if (!this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed) { if (!this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); /** * @constructor * @private */ function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler, this.disposable = disposable, this.isDisposed = false; } /** * @private * @memberOf ScheduledDisposable# */ ScheduledDisposable.prototype.dispose = function () { var parent = this; this.scheduler.schedule(function () { if (!parent.isDisposed) { parent.isDisposed = true; parent.disposable.dispose(); } }); }; var ScheduledItem = Rx.Internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { /** * @constructor * @private */ function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. */ schedulerProto.catchException = schedulerProto['catch'] = function (handler) { return new CatchScheduler(this, handler); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ schedulerProto.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, function () { action(); }); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ schedulerProto.schedulePeriodicWithState = function (state, period, action) { var s = state, id = window.setInterval(function () { s = action(s); }, period); return disposableCreate(function () { window.clearInterval(id); }); }; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState({ first: state, second: action }, function (s, p) { return invokeRecImmediate(s, p); }); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { if (timeSpan < 0) { timeSpan = 0; } return timeSpan; }; return Scheduler; }()); var SchedulePeriodicRecursive = Rx.Internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); var schedulerNoBlockError = 'Scheduler is not allowed to block the thread'; /** * Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } function scheduleRelative(state, dueTime, action) { if (dueTime > 0) throw new Error(schedulerNoBlockError); return action(this, state); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function Trampoline() { queue = new PriorityQueue(4); } Trampoline.prototype.dispose = function () { queue = null; }; Trampoline.prototype.run = function () { var item; while (queue.length > 0) { item = queue.dequeue(); if (!item.isCancelled()) { while (item.dueTime - Scheduler.now() > 0) { } if (!item.isCancelled()) { item.invoke(); } } } }; function scheduleNow(state, action) { return this.scheduleWithRelativeAndState(state, 0, action); } function scheduleRelative(state, dueTime, action) { var dt = this.now() + Scheduler.normalize(dueTime), si = new ScheduledItem(this, state, action, dt), t; if (!queue) { t = new Trampoline(); try { queue.enqueue(si); t.run(); } catch (e) { throw e; } finally { t.dispose(); } } else { queue.enqueue(si); } return si.disposable; } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); currentScheduler.scheduleRequired = function () { return queue === null; }; currentScheduler.ensureTrampoline = function (action) { if (queue === null) { return this.schedule(action); } else { return action(); } }; return currentScheduler; }()); var scheduleMethod, clearMethod = noop; (function () { function postMessageSupported () { // Ensure not in a worker if (!window.postMessage || window.importScripts) { return false; } var isAsync = false, oldHandler = window.onmessage; // Test for async window.onmessage = function () { isAsync = true; }; window.postMessage('','*'); window.onmessage = oldHandler; return isAsync; } // Check for setImmediate first for Node v0.11+ if (typeof window.setImmediate === 'function') { scheduleMethod = window.setImmediate; clearMethod = clearImmediate; } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), tasks = {}, taskId = 0; function onGlobalPostMessage(event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { var handleId = event.data.substring(MSG_PREFIX.length), action = tasks[handleId]; action(); delete tasks[handleId]; } } if (window.addEventListener) { window.addEventListener('message', onGlobalPostMessage, false); } else { window.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; window.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!window.MessageChannel) { var channel = new window.MessageChannel(), channelTasks = {}, channelTaskId = 0; channel.port1.onmessage = function (event) { var id = event.data, action = channelTasks[id]; action(); delete channelTasks[id]; }; scheduleMethod = function (action) { var id = channelTaskId++; channelTasks[id] = action; channel.port2.postMessage(id); }; } else if ('document' in window && 'onreadystatechange' in window.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = window.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; window.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return window.setTimeout(action, 0); }; clearMethod = window.clearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = window.setTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { window.clearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** @private */ var CatchScheduler = (function (_super) { function localNow() { return this._scheduler.now(); } function scheduleNow(state, action) { return this._scheduler.scheduleWithState(state, this._wrap(action)); } function scheduleRelative(state, dueTime, action) { return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); } function scheduleAbsolute(state, dueTime, action) { return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); } inherits(CatchScheduler, _super); /** @private */ function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } /** @private */ CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; /** @private */ CatchScheduler.prototype._wrap = function (action) { var parent = this; return function (self, state) { try { return action(parent._getRecursiveWrapper(self), state); } catch (e) { if (!parent._handler(e)) { throw e; } return disposableEmpty; } }; }; /** @private */ CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { if (this._recursiveOriginal !== scheduler) { this._recursiveOriginal = scheduler; var wrapper = this._clone(scheduler); wrapper._recursiveOriginal = scheduler; wrapper._recursiveWrapper = wrapper; this._recursiveWrapper = wrapper; } return this._recursiveWrapper; }; /** @private */ CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var self = this, failed = false, d = new SingleAssignmentDisposable(); d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { if (failed) { return null; } try { return action(state1); } catch (e) { failed = true; if (!self._handler(e)) { throw e; } d.dispose(); return null; } })); return d; }; return CatchScheduler; }(Scheduler)); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } var NotificationPrototype = Notification.prototype; /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) { if (arguments.length === 1 && typeof observerOrOnNext === 'object') { return this._acceptObservable(observerOrOnNext); } return this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notification * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ NotificationPrototype.toObservable = function (scheduler) { var notification = this; scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); if (notification.kind === 'N') { observer.onCompleted(); } }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept (onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString () { return 'OnNext(' + this.value + ')'; } return function (value) { var notification = new Notification('N', true); notification.value = value; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (exception) { var notification = new Notification('E'); notification.exception = exception; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { var notification = new Notification('C'); notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * @constructor * @private */ var Enumerator = Rx.Internals.Enumerator = function (moveNext, getCurrent, dispose) { this.moveNext = moveNext; this.getCurrent = getCurrent; this.dispose = dispose; }; /** * @static * @memberOf Enumerator * @private */ var enumeratorCreate = Enumerator.create = function (moveNext, getCurrent, dispose) { var done = false; dispose || (dispose = noop); return new Enumerator(function () { if (done) { return false; } var result = moveNext(); if (!result) { done = true; dispose(); } return result; }, function () { return getCurrent(); }, function () { if (!done) { dispose(); done = true; } }); }; /** @private */ var Enumerable = Rx.Internals.Enumerable = (function () { /** * @constructor * @private */ function Enumerable(getEnumerator) { this.getEnumerator = getEnumerator; } /** * @private * @memberOf Enumerable# */ Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (observer) { var e = sources.getEnumerator(), isDisposed = false, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, ex, hasNext = false; if (!isDisposed) { try { hasNext = e.moveNext(); if (hasNext) { current = e.getCurrent(); } else { e.dispose(); } } catch (exception) { ex = exception; e.dispose(); } } else { return; } if (ex) { observer.onError(ex); return; } if (!hasNext) { observer.onCompleted(); return; } var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { self(); }) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; e.dispose(); })); }); }; /** * @private * @memberOf Enumerable# */ Enumerable.prototype.catchException = function () { var sources = this; return new AnonymousObservable(function (observer) { var e = sources.getEnumerator(), isDisposed = false, lastException; var subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, ex, hasNext; hasNext = false; if (!isDisposed) { try { hasNext = e.moveNext(); if (hasNext) { current = e.getCurrent(); } } catch (exception) { ex = exception; } } else { return; } if (ex) { observer.onError(ex); return; } if (!hasNext) { if (lastException) { observer.onError(lastException); } else { observer.onCompleted(); } return; } var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe( observer.onNext.bind(observer), function (exn) { lastException = exn; self(); }, observer.onCompleted.bind(observer))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; return Enumerable; }()); /** * @static * @private * @memberOf Enumerable */ var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount === undefined) { repeatCount = -1; } return new Enumerable(function () { var current, left = repeatCount; return enumeratorCreate(function () { if (left === 0) { return false; } if (left > 0) { left--; } current = value; return true; }, function () { return current; }); }); }; /** * @static * @private * @memberOf Enumerable */ var enumerableFor = Enumerable.forEach = function (source, selector) { selector || (selector = identity); return new Enumerable(function () { var current, index = -1; return enumeratorCreate( function () { if (++index < source.length) { current = selector(source[index], index); return true; } return false; }, function () { return current; } ); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * * @param observer Observer object. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. * If a violation is detected, an Error is thrown from the offending observer method call. * * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. */ Observer.prototype.checked = function () { return new CheckedObserver(this); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * * @static * @memberOf Observer * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler) { return new AnonymousObserver(function (x) { return handler(notificationCreateOnNext(x)); }, function (exception) { return handler(notificationCreateOnError(exception)); }, function () { return handler(notificationCreateOnCompleted()); }); }; /** * Schedules the invocation of observer methods on the given scheduler. * @param {Scheduler} scheduler Scheduler to schedule observer messages on. * @returns {Observer} Observer whose messages are scheduled on the given scheduler. */ Observer.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.Internals.AbstractObserver = (function (_super) { inherits(AbstractObserver, _super); /** * Creates a new observer in a non-stopped state. * * @constructor */ function AbstractObserver() { this.isStopped = false; _super.call(this); } /** * Notifies the observer of a new element in the sequence. * * @memberOf AbstractObserver * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * * @memberOf AbstractObserver * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { inherits(AnonymousObserver, _super); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * * @constructor * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { _super.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * * @memberOf AnonymousObserver * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * * @memberOf AnonymousObserver * @param {Any{ error The error that has occurred. */ AnonymousObserver.prototype.error = function (exception) { this._onError(exception); }; /** * Calls the onCompleted action. * * @memberOf AnonymousObserver */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var CheckedObserver = (function (_super) { inherits(CheckedObserver, _super); function CheckedObserver(observer) { _super.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); try { this._observer.onNext(value); } catch (e) { throw e; } finally { this._state = 0; } }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); try { this._observer.onError(err); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); try { this._observer.onCompleted(); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); /** @private */ var ScheduledObserver = Rx.Internals.ScheduledObserver = (function (_super) { inherits(ScheduledObserver, _super); function ScheduledObserver(scheduler, observer) { _super.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } /** @private */ ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; /** @private */ ScheduledObserver.prototype.error = function (exception) { var self = this; this.queue.push(function () { self.observer.onError(exception); }); }; /** @private */ ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; /** @private */ ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; /** @private */ ScheduledObserver.prototype.dispose = function () { _super.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); /** @private */ var ObserveOnObserver = (function (_super) { inherits(ObserveOnObserver, _super); /** @private */ function ObserveOnObserver() { _super.apply(this, arguments); } /** @private */ ObserveOnObserver.prototype.next = function (value) { _super.prototype.next.call(this, value); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.error = function (e) { _super.prototype.error.call(this, e); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.completed = function () { _super.prototype.completed.call(this); this.ensureActive(); }; return ObserveOnObserver; })(ScheduledObserver); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { /** * @constructor * @private */ function Observable(subscribe) { this._subscribe = subscribe; } observableProto = Observable.prototype; observableProto.finalValue = function () { var source = this; return new AnonymousObservable(function (observer) { var hasValue = false, value; return source.subscribe(function (x) { hasValue = true; value = x; }, observer.onError.bind(observer), function () { if (!hasValue) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); }; /** * Subscribes an observer to the observable sequence. * * @example * 1 - source.subscribe(); * 2 - source.subscribe(observer); * 3 - source.subscribe(function (x) { console.log(x); }); * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { var subscriber; if (typeof observerOrOnNext === 'object') { subscriber = observerOrOnNext; } else { subscriber = observerCreate(observerOrOnNext, onError, onCompleted); } return this._subscribe(subscriber); }; /** * Creates a list from an observable sequence. * * @memberOf Observable * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { function accumulator(list, i) { var newList = list.slice(0); newList.push(i); return newList; } return this.scan([], accumulator).startWith([]).finalValue(); }; return Observable; })(); /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }); }; /** * Creates an observable sequence from a specified subscribe method implementation. * * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = function (subscribe) { return new AnonymousObservable(function (o) { return disposableCreate(subscribe(o)); }); }; /** * Creates an observable sequence from a specified subscribe method implementation. * * @example * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.createWithDisposable = function (subscribe) { return new AnonymousObservable(subscribe); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * * @example * var res = Rx.Observable.fromArray([1,2,3]); * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0; return scheduler.scheduleRecursive(function (self) { if (count < array.length) { observer.onNext(array[count++]); self(); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @static * @memberOf Observable * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); self(); } else { observer.onCompleted(); } }); }); }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * * @static * @memberOf Observable * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.range(0, 10); * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); * @static * @memberOf Observable * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleRecursiveWithState(0, function (i, self) { if (i < count) { observer.onNext(start + i); self(i + 1); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.repeat(42); * var res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @static * @memberOf Observable * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { scheduler || (scheduler = currentThreadScheduler); if (repeatCount == null) { repeatCount = -1; } return observableReturn(value, scheduler).repeat(repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'returnValue' for browsers <IE9. * * @example * var res = Rx.Observable.return(42); * var res = Rx.Observable.return(42, Rx.Scheduler.timeout); * @static * @memberOf Observable * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.returnValue = function (value, scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwException' for browsers <IE9. * * @example * var res = Rx.Observable.throwException(new Error('Error')); * var res = Rx.Observable.throwException(new Error('Error'), Rx.Scheduler.timeout); * @static * @memberOf Observable * @param {Mixed} exception An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwException = function (exception, scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * * @example * var res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; }); * @static * @memberOf Observable * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); if (resource) { disposable = resource; } source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence that reacts first. * * @memberOf Observable# * @param {Observable} rightSource Second observable sequence. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence that reacts first. * * @example * E.g. winner = Rx.Observable.amb(xs, ys, zs); * @static * @memberOf Observable * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = argsOrArray(arguments, 0); function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (observer) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) { var d, result; try { result = handler(exception); } catch (ex) { observer.onError(ex); return; } d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(observer)); }, observer.onCompleted.bind(observer))); return subscription; }); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @memberOf Observable# * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchException = function (handlerOrSecond) { if (typeof handlerOrSecond === 'function') { return observableCatchHandler(this, handlerOrSecond); } return observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.catchException(xs, ys, zs); * 2 - res = Rx.Observable.catchException([xs, ys, zs]); * @static * @memberOf Observable * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchException = Observable['catch'] = function () { var items = argsOrArray(arguments, 0); return enumerableFor(items).catchException(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @memberOf Observable# * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var args = slice.call(arguments); if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @static * @memberOf Observable * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var args = slice.call(arguments), resultSelector = args.pop(); if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } } function done (i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(args[i].subscribe(function (x) { values[i] = x; next(i); }, observer.onError.bind(observer), function () { done(i); })); }(idx)); } return new CompositeDisposable(subscriptions); }); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * * @example * 1 - concatenated = xs.concat(ys, zs); * 2 - concatenated = xs.concat([ys, zs]); * @memberOf Observable# * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { var items = slice.call(arguments, 0); items.unshift(this); return observableConcat.apply(this, items); }; /** * Concatenates all the observable sequences. * * @example * 1 - res = Rx.Observable.concat(xs, ys, zs); * 2 - res = Rx.Observable.concat([xs, ys, zs]); * @static * @memberOf Observable * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var sources = argsOrArray(arguments, 0); return enumerableFor(sources).concat(); }; /** * Concatenates an observable sequence of observable sequences. * * @memberOf Observable# * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatObservable = observableProto.concatAll =function () { return this.merge(1); }; /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @memberOf Observable# * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); } var sources = this; return new AnonymousObservable(function (observer) { var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = [], subscribe = function (xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { var s; group.remove(subscription); if (q.length > 0) { s = q.shift(); subscribe(s); } else { activeCount--; if (isStopped && activeCount === 0) { observer.onCompleted(); } } })); }; group.add(sources.subscribe(function (innerSource) { if (activeCount < maxConcurrentOrOther) { activeCount++; subscribe(innerSource); } else { q.push(innerSource); } }, observer.onError.bind(observer), function () { isStopped = true; if (activeCount === 0) { observer.onCompleted(); } })); return group; }); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * * @example * 1 - merged = Rx.Observable.merge(xs, ys, zs); * 2 - merged = Rx.Observable.merge([xs, ys, zs]); * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); * * @static * @memberOf Observable * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources; if (!arguments[0]) { scheduler = immediateScheduler; sources = slice.call(arguments, 1); } else if (arguments[0].now) { scheduler = arguments[0]; sources = slice.call(arguments, 1); } else { scheduler = immediateScheduler; sources = slice.call(arguments, 0); } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableFromArray(sources, scheduler).mergeObservable(); }; /** * Merges an observable sequence of observable sequences into an observable sequence. * * @memberOf Observable# * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeObservable = observableProto.mergeAll =function () { var sources = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(), isStopped = false, m = new SingleAssignmentDisposable(); group.add(m); m.setDisposable(sources.subscribe(function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); innerSubscription.setDisposable(innerSource.subscribe(function (x) { observer.onNext(x); }, observer.onError.bind(observer), function () { group.remove(innerSubscription); if (isStopped && group.length === 1) { observer.onCompleted(); } })); }, observer.onError.bind(observer), function () { isStopped = true; if (group.length === 1) { observer.onCompleted(); } })); return group; }); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @memberOf Observable * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @static * @memberOf Observable * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () { self(); }, function () { self(); })); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * * @memberOf Observable# * @param {Observable} other The observable sequence that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { if (isOpen) { observer.onNext(left); } }, observer.onError.bind(observer), function () { if (isOpen) { observer.onCompleted(); } })); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, observer.onError.bind(observer), function () { rightSubscription.dispose(); })); return disposables; }); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * * @memberOf Observable# * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe(function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); d.setDisposable(innerSource.subscribe(function (x) { if (latest === id) { observer.onNext(x); } }, function (e) { if (latest === id) { observer.onError(e); } }, function () { if (latest === id) { hasLatest = false; if (isStopped) { observer.onCompleted(); } } })); }, observer.onError.bind(observer), function () { isStopped = true; if (!hasLatest) { observer.onCompleted(); } }); return new CompositeDisposable(subscription, innerSubscription); }); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * * @memberOf Observable# * @param {Observable} other Observable sequence that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { return new CompositeDisposable( source.subscribe(observer), other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) ); }); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { observer.onError(e); return; } observer.onNext(result); } else { observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @memberOf Observable# * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); sources.unshift(parent); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); var next = function (i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * * @static * @memberOf Observable * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var args = slice.call(arguments, 0), first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * * @static * @memberOf Observable * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources = slice.call(arguments); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); })(idx); } var compositeDisposable = new CompositeDisposable(subscriptions); compositeDisposable.add(disposableCreate(function () { for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { queues[qIdx] = []; } })); return compositeDisposable; }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(observer); }); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (skip === undefined) { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { return x.accept(observer); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var res = var obs = observable.distinctUntilChanged(); * var res = var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * 3 - var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @memberOf Observable# * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; keySelector || (keySelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var comparerEquals = false, key; try { key = keySelector(value); } catch (exception) { observer.onError(exception); return; } if (hasCurrentKey) { try { comparerEquals = comparer(currentKey, key); } catch (exception) { observer.onError(exception); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * * @example * var res = observable.doAction(observer); * var res = observable.doAction(onNext); * 3 - observable.doAction(onNext, onError); * 4 - observable.doAction(onNext, onError, onCompleted); * * @memberOf Observable# * @param {Mixed} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { var source = this, onNextFunc; if (typeof observerOrOnNext === 'function') { onNextFunc = observerOrOnNext; } else { onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); onError = observerOrOnNext.onError.bind(observerOrOnNext); onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); } return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { onNextFunc(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (exception) { if (!onError) { observer.onError(exception); } else { try { onError(exception); } catch (e) { observer.onError(e); } observer.onError(exception); } }, function () { if (!onCompleted) { observer.onCompleted(); } else { try { onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); } }); }); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * * @example * var res = obs = observable.finallyAction(function () { console.log('sequence ended'; }); * * @memberOf Observable# * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.finallyAction = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription = source.subscribe(observer); return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * * @memberOf Observable# * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * * @memberOf Observable# * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (exception) { observer.onNext(notificationCreateOnError(exception)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * * @example * var res = repeated = source.repeat(); * var res = repeated = source.repeat(42); * * @memberOf Observable# * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(42); * * @memberOf Observable# * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchException(); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * * var res = scanned = source.scan(function (acc, x) { return acc + x; }); * var res = scanned = source.scan(0, function (acc, x) { return acc + x; }); * * @memberOf Observable# * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var seed, hasSeed = false, accumulator; if (arguments.length === 2) { seed = arguments[0]; accumulator = arguments[1]; hasSeed = true; } else { accumulator = arguments[0]; } var source = this; return observableDefer(function () { var hasAccumulation = false, accumulation; return source.select(function (x) { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } return accumulation; }); }); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * * @memberOf Observable# * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); if (q.length > count) { observer.onNext(q.shift()); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * * @memberOf Observable# * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && 'now' in Object(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableFor([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue. * * @example * var res = obs = source.takeLast(5); * var res = obs = source.takeLast(5, Rx.Scheduler.timeout); * * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * * @memberOf Observable# * @param {Number} count Number of elements to take from the end of the source sequence. * @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count, scheduler) { return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); }); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * * @memberOf Observable# * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); if (q.length > count) { q.shift(); } }, observer.onError.bind(observer), function () { observer.onNext(q); observer.onCompleted(); }); }); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * * @memberOf Observable# * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; if (count <= 0) { throw new Error(argumentOutOfRange); } if (skip == null) { skip = count; } if (skip <= 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = [], createWindow = function () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); }; createWindow(); m.setDisposable(source.subscribe(function (x) { var s; for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; if (c >= 0 && c % skip === 0) { s = q.shift(); s.onCompleted(); } n++; if (n % skip === 0) { createWindow(); } }, function (exception) { while (q.length > 0) { q.shift().onError(exception); } observer.onError(exception); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * var res = obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; if (defaultValue === undefined) { defaultValue = null; } return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, observer.onError.bind(observer), function () { if (!found) { observer.onNext(defaultValue); } observer.onCompleted(); }); }); }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (x) { return x.toString(); }); * * @memberOf Observable# * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, keySerializer) { var source = this; keySelector || (keySelector = identity); keySerializer || (keySerializer = defaultKeySerializer); return new AnonymousObservable(function (observer) { var hashSet = {}; return source.subscribe(function (x) { var key, serializedKey, otherKey, hasMatch = false; try { key = keySelector(x); serializedKey = keySerializer(key); } catch (exception) { observer.onError(exception); return; } for (otherKey in hashSet) { if (serializedKey === otherKey) { hasMatch = true; break; } } if (!hasMatch) { hashSet[serializedKey] = null; observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. * * @example * var res = observable.groupBy(function (x) { return x.id; }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); * * @memberOf Observable# * @param {Function} keySelector A function to extract the key for each element. * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. */ observableProto.groupBy = function (keySelector, elementSelector, keySerializer) { return this.groupByUntil(keySelector, elementSelector, function () { return observableNever(); }, keySerializer); }; /** * Groups the elements of an observable sequence according to a specified key selector function. * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. * * @example * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); * * @memberOf Observable# * @param {Function} keySelector A function to extract the key for each element. * @param {Function} durationSelector A function to signal the expiration of a group. * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. * @returns {Observable} * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. * */ observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, keySerializer) { var source = this; elementSelector || (elementSelector = identity); keySerializer || (keySerializer = defaultKeySerializer); return new AnonymousObservable(function (observer) { var map = {}, groupDisposable = new CompositeDisposable(), refCountDisposable = new RefCountDisposable(groupDisposable); groupDisposable.add(source.subscribe(function (x) { var duration, durationGroup, element, fireNewMapEntry, group, key, serializedKey, md, writer, w; try { key = keySelector(x); serializedKey = keySerializer(key); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } fireNewMapEntry = false; try { writer = map[serializedKey]; if (!writer) { writer = new Subject(); map[serializedKey] = writer; fireNewMapEntry = true; } } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } if (fireNewMapEntry) { group = new GroupedObservable(key, writer, refCountDisposable); durationGroup = new GroupedObservable(key, writer); try { duration = durationSelector(durationGroup); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } observer.onNext(group); md = new SingleAssignmentDisposable(); groupDisposable.add(md); var expire = function () { if (serializedKey in map) { delete map[serializedKey]; writer.onCompleted(); } groupDisposable.remove(md); }; md.setDisposable(duration.take(1).subscribe(noop, function (exn) { for (w in map) { map[w].onError(exn); } observer.onError(exn); }, function () { expire(); })); } try { element = elementSelector(x); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } writer.onNext(element); }, function (ex) { for (var w in map) { map[w].onError(ex); } observer.onError(ex); }, function () { for (var w in map) { map[w].onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * * @memberOf Observable# * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.select = observableProto.map = function (selector, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var result; try { result = selector.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } observer.onNext(result); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Retrieves the value of a specified property from all elements in the Observable sequence. * * @memberOf Observable# * @param {String} property The property to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function (property) { return this.select(function (x) { return x[property]; }); }; function selectMany(selector) { return this.select(selector).mergeObservable(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector) { if (resultSelector) { return this.selectMany(function (x) { return selector(x).select(function (y) { return resultSelector(x, y); }); }); } if (typeof selector === 'function') { return selectMany.call(this, selector); } return selectMany.call(this, function () { return selector; }); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new Error(argumentOutOfRange); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining <= 0) { observer.onNext(x); } else { remaining--; } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * * @memberOf Observable# * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !predicate.call(thisArg, x, i++, source); } catch (e) { observer.onError(e); return; } } if (running) { observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * 2 - source.take(0, Rx.Scheduler.timeout); * * @memberOf Observable# * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new Error(argumentOutOfRange); } if (count === 0) { return observableEmpty(scheduler); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining > 0) { remaining--; observer.onNext(x); if (remaining === 0) { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * * @example * var res = source.takeWhile(function (value) { return value < 10; }); * var res = source.takeWhile(function (value, index) { return value < 10 || index < 10; }); * * @memberOf Observable# * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var observable = this; return new AnonymousObservable(function (observer) { var i = 0, running = true; return observable.subscribe(function (x) { if (running) { try { running = predicate.call(thisArg, x, i++, observable); } catch (e) { observer.onError(e); return; } if (running) { observer.onNext(x); } else { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * * @example * var res = source.where(function (value) { return value < 10; }); * var res = source.where(function (value, index) { return value < 10 || index < 10; }); * * @memberOf Observable# * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.where = observableProto.filter = function (predicate, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var shouldRun; try { shouldRun = predicate.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } if (shouldRun) { observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; var AnonymousObservable = Rx.Internals.AnonymousObservable = (function (_super) { inherits(AnonymousObservable, _super); function AnonymousObservable(subscribe) { if (!(this instanceof AnonymousObservable)) { return new AnonymousObservable(subscribe); } function s(observer) { var autoDetachObserver = new AutoDetachObserver(observer); if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(function () { try { autoDetachObserver.setDisposable(subscribe(autoDetachObserver)); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } }); } else { try { autoDetachObserver.setDisposable(subscribe(autoDetachObserver)); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } } return autoDetachObserver; } _super.call(this, s); } return AnonymousObservable; }(Observable)); /** @private */ var AutoDetachObserver = (function (_super) { inherits(AutoDetachObserver, _super); function AutoDetachObserver(observer) { _super.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var noError = false; try { this.observer.onNext(value); noError = true; } catch (e) { throw e; } finally { if (!noError) { this.dispose(); } } }; AutoDetachObserverPrototype.error = function (exn) { try { this.observer.onError(exn); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.completed = function () { try { this.observer.onCompleted(); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; /* @private */ AutoDetachObserverPrototype.disposable = function (value) { return arguments.length ? this.getDisposable() : setDisposable(value); }; AutoDetachObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); /** @private */ var GroupedObservable = (function (_super) { inherits(GroupedObservable, _super); function subscribe(observer) { return this.underlyingObservable.subscribe(observer); } /** * @constructor * @private */ function GroupedObservable(key, underlyingObservable, mergedDisposable) { _super.call(this, subscribe); this.key = key; this.underlyingObservable = !mergedDisposable ? underlyingObservable : new AnonymousObservable(function (observer) { return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); }); } return GroupedObservable; }(Observable)); /** @private */ var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; /** * @private * @memberOf InnerSubscription */ InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.exception) { observer.onError(this.exception); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, _super); /** * Creates a subject. * @constructor */ function Subject() { _super.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; } addProperties(Subject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } var ex = this.exception; var hv = this.hasValue; var v = this.value; if (ex) { observer.onError(ex); } else if (hv) { observer.onNext(v); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, _super); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { _super.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.value = null, this.hasValue = false, this.observers = [], this.exception = null; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var o, i, len; checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; var v = this.value; var hv = this.hasValue; if (hv) { for (i = 0, len = os.length; i < len; i++) { o = os[i]; o.onNext(v); o.onCompleted(); } } else { for (i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { this.value = value; this.hasValue = true; } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); /** @private */ var AnonymousSubject = (function (_super) { inherits(AnonymousSubject, _super); function subscribe(observer) { return this.observable.subscribe(observer); } /** * @private * @constructor */ function AnonymousSubject(observer, observable) { _super.call(this, subscribe); this.observer = observer; this.observable = observable; } addProperties(AnonymousSubject.prototype, Observer, { /** * @private * @memberOf AnonymousSubject# */ onCompleted: function () { this.observer.onCompleted(); }, /** * @private * @memberOf AnonymousSubject# */ onError: function (exception) { this.observer.onError(exception); }, /** * @private * @memberOf AnonymousSubject# */ onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); // Check for AMD if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { window.Rx = Rx; return define(function () { return Rx; }); } else if (freeExports) { if (typeof module == 'object' && module && module.exports == freeExports) { module.exports = Rx; } else { freeExports = Rx; } } else { window.Rx = Rx; } }(this));
ajax/libs/flat-ui/2.1.2/js/jquery-1.8.3.min.js
bootcdn/cdnjs
/*! jQuery v1.8.3 jquery.com | jquery.org/license */ (function(e,t){function _(e){var t=M[e]={};return v.each(e.split(y),function(e,n){t[n]=!0}),t}function H(e,n,r){if(r===t&&e.nodeType===1){var i="data-"+n.replace(P,"-$1").toLowerCase();r=e.getAttribute(i);if(typeof r=="string"){try{r=r==="true"?!0:r==="false"?!1:r==="null"?null:+r+""===r?+r:D.test(r)?v.parseJSON(r):r}catch(s){}v.data(e,n,r)}else r=t}return r}function B(e){var t;for(t in e){if(t==="data"&&v.isEmptyObject(e[t]))continue;if(t!=="toJSON")return!1}return!0}function et(){return!1}function tt(){return!0}function ut(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function at(e,t){do e=e[t];while(e&&e.nodeType!==1);return e}function ft(e,t,n){t=t||0;if(v.isFunction(t))return v.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return v.grep(e,function(e,r){return e===t===n});if(typeof t=="string"){var r=v.grep(e,function(e){return e.nodeType===1});if(it.test(t))return v.filter(t,r,!n);t=v.filter(t,r)}return v.grep(e,function(e,r){return v.inArray(e,t)>=0===n})}function lt(e){var t=ct.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function At(e,t){if(t.nodeType!==1||!v.hasData(e))return;var n,r,i,s=v._data(e),o=v._data(t,s),u=s.events;if(u){delete o.handle,o.events={};for(n in u)for(r=0,i=u[n].length;r<i;r++)v.event.add(t,n,u[n][r])}o.data&&(o.data=v.extend({},o.data))}function Ot(e,t){var n;if(t.nodeType!==1)return;t.clearAttributes&&t.clearAttributes(),t.mergeAttributes&&t.mergeAttributes(e),n=t.nodeName.toLowerCase(),n==="object"?(t.parentNode&&(t.outerHTML=e.outerHTML),v.support.html5Clone&&e.innerHTML&&!v.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):n==="input"&&Et.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):n==="option"?t.selected=e.defaultSelected:n==="input"||n==="textarea"?t.defaultValue=e.defaultValue:n==="script"&&t.text!==e.text&&(t.text=e.text),t.removeAttribute(v.expando)}function Mt(e){return typeof e.getElementsByTagName!="undefined"?e.getElementsByTagName("*"):typeof e.querySelectorAll!="undefined"?e.querySelectorAll("*"):[]}function _t(e){Et.test(e.type)&&(e.defaultChecked=e.checked)}function Qt(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=Jt.length;while(i--){t=Jt[i]+n;if(t in e)return t}return r}function Gt(e,t){return e=t||e,v.css(e,"display")==="none"||!v.contains(e.ownerDocument,e)}function Yt(e,t){var n,r,i=[],s=0,o=e.length;for(;s<o;s++){n=e[s];if(!n.style)continue;i[s]=v._data(n,"olddisplay"),t?(!i[s]&&n.style.display==="none"&&(n.style.display=""),n.style.display===""&&Gt(n)&&(i[s]=v._data(n,"olddisplay",nn(n.nodeName)))):(r=Dt(n,"display"),!i[s]&&r!=="none"&&v._data(n,"olddisplay",r))}for(s=0;s<o;s++){n=e[s];if(!n.style)continue;if(!t||n.style.display==="none"||n.style.display==="")n.style.display=t?i[s]||"":"none"}return e}function Zt(e,t,n){var r=Rt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function en(e,t,n,r){var i=n===(r?"border":"content")?4:t==="width"?1:0,s=0;for(;i<4;i+=2)n==="margin"&&(s+=v.css(e,n+$t[i],!0)),r?(n==="content"&&(s-=parseFloat(Dt(e,"padding"+$t[i]))||0),n!=="margin"&&(s-=parseFloat(Dt(e,"border"+$t[i]+"Width"))||0)):(s+=parseFloat(Dt(e,"padding"+$t[i]))||0,n!=="padding"&&(s+=parseFloat(Dt(e,"border"+$t[i]+"Width"))||0));return s}function tn(e,t,n){var r=t==="width"?e.offsetWidth:e.offsetHeight,i=!0,s=v.support.boxSizing&&v.css(e,"boxSizing")==="border-box";if(r<=0||r==null){r=Dt(e,t);if(r<0||r==null)r=e.style[t];if(Ut.test(r))return r;i=s&&(v.support.boxSizingReliable||r===e.style[t]),r=parseFloat(r)||0}return r+en(e,t,n||(s?"border":"content"),i)+"px"}function nn(e){if(Wt[e])return Wt[e];var t=v("<"+e+">").appendTo(i.body),n=t.css("display");t.remove();if(n==="none"||n===""){Pt=i.body.appendChild(Pt||v.extend(i.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!Ht||!Pt.createElement)Ht=(Pt.contentWindow||Pt.contentDocument).document,Ht.write("<!doctype html><html><body>"),Ht.close();t=Ht.body.appendChild(Ht.createElement(e)),n=Dt(t,"display"),i.body.removeChild(Pt)}return Wt[e]=n,n}function fn(e,t,n,r){var i;if(v.isArray(t))v.each(t,function(t,i){n||sn.test(e)?r(e,i):fn(e+"["+(typeof i=="object"?t:"")+"]",i,n,r)});else if(!n&&v.type(t)==="object")for(i in t)fn(e+"["+i+"]",t[i],n,r);else r(e,t)}function Cn(e){return function(t,n){typeof t!="string"&&(n=t,t="*");var r,i,s,o=t.toLowerCase().split(y),u=0,a=o.length;if(v.isFunction(n))for(;u<a;u++)r=o[u],s=/^\+/.test(r),s&&(r=r.substr(1)||"*"),i=e[r]=e[r]||[],i[s?"unshift":"push"](n)}}function kn(e,n,r,i,s,o){s=s||n.dataTypes[0],o=o||{},o[s]=!0;var u,a=e[s],f=0,l=a?a.length:0,c=e===Sn;for(;f<l&&(c||!u);f++)u=a[f](n,r,i),typeof u=="string"&&(!c||o[u]?u=t:(n.dataTypes.unshift(u),u=kn(e,n,r,i,u,o)));return(c||!u)&&!o["*"]&&(u=kn(e,n,r,i,"*",o)),u}function Ln(e,n){var r,i,s=v.ajaxSettings.flatOptions||{};for(r in n)n[r]!==t&&((s[r]?e:i||(i={}))[r]=n[r]);i&&v.extend(!0,e,i)}function An(e,n,r){var i,s,o,u,a=e.contents,f=e.dataTypes,l=e.responseFields;for(s in l)s in r&&(n[l[s]]=r[s]);while(f[0]==="*")f.shift(),i===t&&(i=e.mimeType||n.getResponseHeader("content-type"));if(i)for(s in a)if(a[s]&&a[s].test(i)){f.unshift(s);break}if(f[0]in r)o=f[0];else{for(s in r){if(!f[0]||e.converters[s+" "+f[0]]){o=s;break}u||(u=s)}o=o||u}if(o)return o!==f[0]&&f.unshift(o),r[o]}function On(e,t){var n,r,i,s,o=e.dataTypes.slice(),u=o[0],a={},f=0;e.dataFilter&&(t=e.dataFilter(t,e.dataType));if(o[1])for(n in e.converters)a[n.toLowerCase()]=e.converters[n];for(;i=o[++f];)if(i!=="*"){if(u!=="*"&&u!==i){n=a[u+" "+i]||a["* "+i];if(!n)for(r in a){s=r.split(" ");if(s[1]===i){n=a[u+" "+s[0]]||a["* "+s[0]];if(n){n===!0?n=a[r]:a[r]!==!0&&(i=s[0],o.splice(f--,0,i));break}}}if(n!==!0)if(n&&e["throws"])t=n(t);else try{t=n(t)}catch(l){return{state:"parsererror",error:n?l:"No conversion from "+u+" to "+i}}}u=i}return{state:"success",data:t}}function Fn(){try{return new e.XMLHttpRequest}catch(t){}}function In(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function $n(){return setTimeout(function(){qn=t},0),qn=v.now()}function Jn(e,t){v.each(t,function(t,n){var r=(Vn[t]||[]).concat(Vn["*"]),i=0,s=r.length;for(;i<s;i++)if(r[i].call(e,t,n))return})}function Kn(e,t,n){var r,i=0,s=0,o=Xn.length,u=v.Deferred().always(function(){delete a.elem}),a=function(){var t=qn||$n(),n=Math.max(0,f.startTime+f.duration-t),r=n/f.duration||0,i=1-r,s=0,o=f.tweens.length;for(;s<o;s++)f.tweens[s].run(i);return u.notifyWith(e,[f,i,n]),i<1&&o?n:(u.resolveWith(e,[f]),!1)},f=u.promise({elem:e,props:v.extend({},t),opts:v.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:qn||$n(),duration:n.duration,tweens:[],createTween:function(t,n,r){var i=v.Tween(e,f.opts,t,n,f.opts.specialEasing[t]||f.opts.easing);return f.tweens.push(i),i},stop:function(t){var n=0,r=t?f.tweens.length:0;for(;n<r;n++)f.tweens[n].run(1);return t?u.resolveWith(e,[f,t]):u.rejectWith(e,[f,t]),this}}),l=f.props;Qn(l,f.opts.specialEasing);for(;i<o;i++){r=Xn[i].call(f,e,l,f.opts);if(r)return r}return Jn(f,l),v.isFunction(f.opts.start)&&f.opts.start.call(e,f),v.fx.timer(v.extend(a,{anim:f,queue:f.opts.queue,elem:e})),f.progress(f.opts.progress).done(f.opts.done,f.opts.complete).fail(f.opts.fail).always(f.opts.always)}function Qn(e,t){var n,r,i,s,o;for(n in e){r=v.camelCase(n),i=t[r],s=e[n],v.isArray(s)&&(i=s[1],s=e[n]=s[0]),n!==r&&(e[r]=s,delete e[n]),o=v.cssHooks[r];if(o&&"expand"in o){s=o.expand(s),delete e[r];for(n in s)n in e||(e[n]=s[n],t[n]=i)}else t[r]=i}}function Gn(e,t,n){var r,i,s,o,u,a,f,l,c,h=this,p=e.style,d={},m=[],g=e.nodeType&&Gt(e);n.queue||(l=v._queueHooks(e,"fx"),l.unqueued==null&&(l.unqueued=0,c=l.empty.fire,l.empty.fire=function(){l.unqueued||c()}),l.unqueued++,h.always(function(){h.always(function(){l.unqueued--,v.queue(e,"fx").length||l.empty.fire()})})),e.nodeType===1&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],v.css(e,"display")==="inline"&&v.css(e,"float")==="none"&&(!v.support.inlineBlockNeedsLayout||nn(e.nodeName)==="inline"?p.display="inline-block":p.zoom=1)),n.overflow&&(p.overflow="hidden",v.support.shrinkWrapBlocks||h.done(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t){s=t[r];if(Un.exec(s)){delete t[r],a=a||s==="toggle";if(s===(g?"hide":"show"))continue;m.push(r)}}o=m.length;if(o){u=v._data(e,"fxshow")||v._data(e,"fxshow",{}),"hidden"in u&&(g=u.hidden),a&&(u.hidden=!g),g?v(e).show():h.done(function(){v(e).hide()}),h.done(function(){var t;v.removeData(e,"fxshow",!0);for(t in d)v.style(e,t,d[t])});for(r=0;r<o;r++)i=m[r],f=h.createTween(i,g?u[i]:0),d[i]=u[i]||v.style(e,i),i in u||(u[i]=f.start,g&&(f.end=f.start,f.start=i==="width"||i==="height"?1:0))}}function Yn(e,t,n,r,i){return new Yn.prototype.init(e,t,n,r,i)}function Zn(e,t){var n,r={height:e},i=0;t=t?1:0;for(;i<4;i+=2-t)n=$t[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function tr(e){return v.isWindow(e)?e:e.nodeType===9?e.defaultView||e.parentWindow:!1}var n,r,i=e.document,s=e.location,o=e.navigator,u=e.jQuery,a=e.$,f=Array.prototype.push,l=Array.prototype.slice,c=Array.prototype.indexOf,h=Object.prototype.toString,p=Object.prototype.hasOwnProperty,d=String.prototype.trim,v=function(e,t){return new v.fn.init(e,t,n)},m=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,g=/\S/,y=/\s+/,b=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,w=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,E=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,S=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,T=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,N=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,C=/^-ms-/,k=/-([\da-z])/gi,L=function(e,t){return(t+"").toUpperCase()},A=function(){i.addEventListener?(i.removeEventListener("DOMContentLoaded",A,!1),v.ready()):i.readyState==="complete"&&(i.detachEvent("onreadystatechange",A),v.ready())},O={};v.fn=v.prototype={constructor:v,init:function(e,n,r){var s,o,u,a;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if(typeof e=="string"){e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3?s=[null,e,null]:s=w.exec(e);if(s&&(s[1]||!n)){if(s[1])return n=n instanceof v?n[0]:n,a=n&&n.nodeType?n.ownerDocument||n:i,e=v.parseHTML(s[1],a,!0),E.test(s[1])&&v.isPlainObject(n)&&this.attr.call(e,n,!0),v.merge(this,e);o=i.getElementById(s[2]);if(o&&o.parentNode){if(o.id!==s[2])return r.find(e);this.length=1,this[0]=o}return this.context=i,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return v.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),v.makeArray(e,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return l.call(this)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=v.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,t==="find"?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return v.each(this,e,t)},ready:function(e){return v.ready.promise().done(e),this},eq:function(e){return e=+e,e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(l.apply(this,arguments),"slice",l.call(arguments).join(","))},map:function(e){return this.pushStack(v.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:[].sort,splice:[].splice},v.fn.init.prototype=v.fn,v.extend=v.fn.extend=function(){var e,n,r,i,s,o,u=arguments[0]||{},a=1,f=arguments.length,l=!1;typeof u=="boolean"&&(l=u,u=arguments[1]||{},a=2),typeof u!="object"&&!v.isFunction(u)&&(u={}),f===a&&(u=this,--a);for(;a<f;a++)if((e=arguments[a])!=null)for(n in e){r=u[n],i=e[n];if(u===i)continue;l&&i&&(v.isPlainObject(i)||(s=v.isArray(i)))?(s?(s=!1,o=r&&v.isArray(r)?r:[]):o=r&&v.isPlainObject(r)?r:{},u[n]=v.extend(l,o,i)):i!==t&&(u[n]=i)}return u},v.extend({noConflict:function(t){return e.$===v&&(e.$=a),t&&e.jQuery===v&&(e.jQuery=u),v},isReady:!1,readyWait:1,holdReady:function(e){e?v.readyWait++:v.ready(!0)},ready:function(e){if(e===!0?--v.readyWait:v.isReady)return;if(!i.body)return setTimeout(v.ready,1);v.isReady=!0;if(e!==!0&&--v.readyWait>0)return;r.resolveWith(i,[v]),v.fn.trigger&&v(i).trigger("ready").off("ready")},isFunction:function(e){return v.type(e)==="function"},isArray:Array.isArray||function(e){return v.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):O[h.call(e)]||"object"},isPlainObject:function(e){if(!e||v.type(e)!=="object"||e.nodeType||v.isWindow(e))return!1;try{if(e.constructor&&!p.call(e,"constructor")&&!p.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||p.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return!e||typeof e!="string"?null:(typeof t=="boolean"&&(n=t,t=0),t=t||i,(r=E.exec(e))?[t.createElement(r[1])]:(r=v.buildFragment([e],t,n?null:[]),v.merge([],(r.cacheable?v.clone(r.fragment):r.fragment).childNodes)))},parseJSON:function(t){if(!t||typeof t!="string")return null;t=v.trim(t);if(e.JSON&&e.JSON.parse)return e.JSON.parse(t);if(S.test(t.replace(T,"@").replace(N,"]").replace(x,"")))return(new Function("return "+t))();v.error("Invalid JSON: "+t)},parseXML:function(n){var r,i;if(!n||typeof n!="string")return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(s){r=t}return(!r||!r.documentElement||r.getElementsByTagName("parsererror").length)&&v.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&g.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(C,"ms-").replace(k,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,n,r){var i,s=0,o=e.length,u=o===t||v.isFunction(e);if(r){if(u){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;s<o;)if(n.apply(e[s++],r)===!1)break}else if(u){for(i in e)if(n.call(e[i],i,e[i])===!1)break}else for(;s<o;)if(n.call(e[s],s,e[s++])===!1)break;return e},trim:d&&!d.call("\ufeff\u00a0")?function(e){return e==null?"":d.call(e)}:function(e){return e==null?"":(e+"").replace(b,"")},makeArray:function(e,t){var n,r=t||[];return e!=null&&(n=v.type(e),e.length==null||n==="string"||n==="function"||n==="regexp"||v.isWindow(e)?f.call(r,e):v.merge(r,e)),r},inArray:function(e,t,n){var r;if(t){if(c)return c.call(t,e,n);r=t.length,n=n?n<0?Math.max(0,r+n):n:0;for(;n<r;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,s=0;if(typeof r=="number")for(;s<r;s++)e[i++]=n[s];else while(n[s]!==t)e[i++]=n[s++];return e.length=i,e},grep:function(e,t,n){var r,i=[],s=0,o=e.length;n=!!n;for(;s<o;s++)r=!!t(e[s],s),n!==r&&i.push(e[s]);return i},map:function(e,n,r){var i,s,o=[],u=0,a=e.length,f=e instanceof v||a!==t&&typeof a=="number"&&(a>0&&e[0]&&e[a-1]||a===0||v.isArray(e));if(f)for(;u<a;u++)i=n(e[u],u,r),i!=null&&(o[o.length]=i);else for(s in e)i=n(e[s],s,r),i!=null&&(o[o.length]=i);return o.concat.apply([],o)},guid:1,proxy:function(e,n){var r,i,s;return typeof n=="string"&&(r=e[n],n=e,e=r),v.isFunction(e)?(i=l.call(arguments,2),s=function(){return e.apply(n,i.concat(l.call(arguments)))},s.guid=e.guid=e.guid||v.guid++,s):t},access:function(e,n,r,i,s,o,u){var a,f=r==null,l=0,c=e.length;if(r&&typeof r=="object"){for(l in r)v.access(e,n,l,r[l],1,o,i);s=1}else if(i!==t){a=u===t&&v.isFunction(i),f&&(a?(a=n,n=function(e,t,n){return a.call(v(e),n)}):(n.call(e,i),n=null));if(n)for(;l<c;l++)n(e[l],r,a?i.call(e[l],l,n(e[l],r)):i,u);s=1}return s?e:f?n.call(e):c?n(e[0],r):o},now:function(){return(new Date).getTime()}}),v.ready.promise=function(t){if(!r){r=v.Deferred();if(i.readyState==="complete")setTimeout(v.ready,1);else if(i.addEventListener)i.addEventListener("DOMContentLoaded",A,!1),e.addEventListener("load",v.ready,!1);else{i.attachEvent("onreadystatechange",A),e.attachEvent("onload",v.ready);var n=!1;try{n=e.frameElement==null&&i.documentElement}catch(s){}n&&n.doScroll&&function o(){if(!v.isReady){try{n.doScroll("left")}catch(e){return setTimeout(o,50)}v.ready()}}()}}return r.promise(t)},v.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(e,t){O["[object "+t+"]"]=t.toLowerCase()}),n=v(i);var M={};v.Callbacks=function(e){e=typeof e=="string"?M[e]||_(e):v.extend({},e);var n,r,i,s,o,u,a=[],f=!e.once&&[],l=function(t){n=e.memory&&t,r=!0,u=s||0,s=0,o=a.length,i=!0;for(;a&&u<o;u++)if(a[u].apply(t[0],t[1])===!1&&e.stopOnFalse){n=!1;break}i=!1,a&&(f?f.length&&l(f.shift()):n?a=[]:c.disable())},c={add:function(){if(a){var t=a.length;(function r(t){v.each(t,function(t,n){var i=v.type(n);i==="function"?(!e.unique||!c.has(n))&&a.push(n):n&&n.length&&i!=="string"&&r(n)})})(arguments),i?o=a.length:n&&(s=t,l(n))}return this},remove:function(){return a&&v.each(arguments,function(e,t){var n;while((n=v.inArray(t,a,n))>-1)a.splice(n,1),i&&(n<=o&&o--,n<=u&&u--)}),this},has:function(e){return v.inArray(e,a)>-1},empty:function(){return a=[],this},disable:function(){return a=f=n=t,this},disabled:function(){return!a},lock:function(){return f=t,n||c.disable(),this},locked:function(){return!f},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],a&&(!r||f)&&(i?f.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},v.extend({Deferred:function(e){var t=[["resolve","done",v.Callbacks("once memory"),"resolved"],["reject","fail",v.Callbacks("once memory"),"rejected"],["notify","progress",v.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return v.Deferred(function(n){v.each(t,function(t,r){var s=r[0],o=e[t];i[r[1]](v.isFunction(o)?function(){var e=o.apply(this,arguments);e&&v.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===i?n:this,[e])}:n[s])}),e=null}).promise()},promise:function(e){return e!=null?v.extend(e,r):r}},i={};return r.pipe=r.then,v.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=o.fire,i[s[0]+"With"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=l.call(arguments),r=n.length,i=r!==1||e&&v.isFunction(e.promise)?r:0,s=i===1?e:v.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?l.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t<r;t++)n[t]&&v.isFunction(n[t].promise)?n[t].promise().done(o(t,f,n)).fail(s.reject).progress(o(t,a,u)):--i}return i||s.resolveWith(f,n),s.promise()}}),v.support=function(){var t,n,r,s,o,u,a,f,l,c,h,p=i.createElement("div");p.setAttribute("className","t"),p.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=p.getElementsByTagName("*"),r=p.getElementsByTagName("a")[0];if(!n||!r||!n.length)return{};s=i.createElement("select"),o=s.appendChild(i.createElement("option")),u=p.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:r.getAttribute("href")==="/a",opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:u.value==="on",optSelected:o.selected,getSetAttribute:p.className!=="t",enctype:!!i.createElement("form").enctype,html5Clone:i.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:i.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},u.checked=!0,t.noCloneChecked=u.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!o.disabled;try{delete p.test}catch(d){t.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",h=function(){t.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick"),p.detachEvent("onclick",h)),u=i.createElement("input"),u.value="t",u.setAttribute("type","radio"),t.radioValue=u.value==="t",u.setAttribute("checked","checked"),u.setAttribute("name","t"),p.appendChild(u),a=i.createDocumentFragment(),a.appendChild(p.lastChild),t.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=u.checked,a.removeChild(u),a.appendChild(p);if(p.attachEvent)for(l in{submit:!0,change:!0,focusin:!0})f="on"+l,c=f in p,c||(p.setAttribute(f,"return;"),c=typeof p[f]=="function"),t[l+"Bubbles"]=c;return v(function(){var n,r,s,o,u="padding:0;margin:0;border:0;display:block;overflow:hidden;",a=i.getElementsByTagName("body")[0];if(!a)return;n=i.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",a.insertBefore(n,a.firstChild),r=i.createElement("div"),n.appendChild(r),r.innerHTML="<table><tr><td></td><td>t</td></tr></table>",s=r.getElementsByTagName("td"),s[0].style.cssText="padding:0;margin:0;border:0;display:none",c=s[0].offsetHeight===0,s[0].style.display="",s[1].style.display="none",t.reliableHiddenOffsets=c&&s[0].offsetHeight===0,r.innerHTML="",r.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=r.offsetWidth===4,t.doesNotIncludeMarginInBodyOffset=a.offsetTop!==1,e.getComputedStyle&&(t.pixelPosition=(e.getComputedStyle(r,null)||{}).top!=="1%",t.boxSizingReliable=(e.getComputedStyle(r,null)||{width:"4px"}).width==="4px",o=i.createElement("div"),o.style.cssText=r.style.cssText=u,o.style.marginRight=o.style.width="0",r.style.width="1px",r.appendChild(o),t.reliableMarginRight=!parseFloat((e.getComputedStyle(o,null)||{}).marginRight)),typeof r.style.zoom!="undefined"&&(r.innerHTML="",r.style.cssText=u+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=r.offsetWidth===3,r.style.display="block",r.style.overflow="visible",r.innerHTML="<div></div>",r.firstChild.style.width="5px",t.shrinkWrapBlocks=r.offsetWidth!==3,n.style.zoom=1),a.removeChild(n),n=r=s=o=null}),a.removeChild(p),n=r=s=o=u=a=p=null,t}();var D=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;v.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(v.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?v.cache[e[v.expando]]:e[v.expando],!!e&&!B(e)},data:function(e,n,r,i){if(!v.acceptData(e))return;var s,o,u=v.expando,a=typeof n=="string",f=e.nodeType,l=f?v.cache:e,c=f?e[u]:e[u]&&u;if((!c||!l[c]||!i&&!l[c].data)&&a&&r===t)return;c||(f?e[u]=c=v.deletedIds.pop()||v.guid++:c=u),l[c]||(l[c]={},f||(l[c].toJSON=v.noop));if(typeof n=="object"||typeof n=="function")i?l[c]=v.extend(l[c],n):l[c].data=v.extend(l[c].data,n);return s=l[c],i||(s.data||(s.data={}),s=s.data),r!==t&&(s[v.camelCase(n)]=r),a?(o=s[n],o==null&&(o=s[v.camelCase(n)])):o=s,o},removeData:function(e,t,n){if(!v.acceptData(e))return;var r,i,s,o=e.nodeType,u=o?v.cache:e,a=o?e[v.expando]:v.expando;if(!u[a])return;if(t){r=n?u[a]:u[a].data;if(r){v.isArray(t)||(t in r?t=[t]:(t=v.camelCase(t),t in r?t=[t]:t=t.split(" ")));for(i=0,s=t.length;i<s;i++)delete r[t[i]];if(!(n?B:v.isEmptyObject)(r))return}}if(!n){delete u[a].data;if(!B(u[a]))return}o?v.cleanData([e],!0):v.support.deleteExpando||u!=u.window?delete u[a]:u[a]=null},_data:function(e,t,n){return v.data(e,t,n,!0)},acceptData:function(e){var t=e.nodeName&&v.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),v.fn.extend({data:function(e,n){var r,i,s,o,u,a=this[0],f=0,l=null;if(e===t){if(this.length){l=v.data(a);if(a.nodeType===1&&!v._data(a,"parsedAttrs")){s=a.attributes;for(u=s.length;f<u;f++)o=s[f].name,o.indexOf("data-")||(o=v.camelCase(o.substring(5)),H(a,o,l[o]));v._data(a,"parsedAttrs",!0)}}return l}return typeof e=="object"?this.each(function(){v.data(this,e)}):(r=e.split(".",2),r[1]=r[1]?"."+r[1]:"",i=r[1]+"!",v.access(this,function(n){if(n===t)return l=this.triggerHandler("getData"+i,[r[0]]),l===t&&a&&(l=v.data(a,e),l=H(a,e,l)),l===t&&r[1]?this.data(r[0]):l;r[1]=n,this.each(function(){var t=v(this);t.triggerHandler("setData"+i,r),v.data(this,e,n),t.triggerHandler("changeData"+i,r)})},null,n,arguments.length>1,null,!1))},removeData:function(e){return this.each(function(){v.removeData(this,e)})}}),v.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=v._data(e,t),n&&(!r||v.isArray(n)?r=v._data(e,t,v.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=v.queue(e,t),r=n.length,i=n.shift(),s=v._queueHooks(e,t),o=function(){v.dequeue(e,t)};i==="inprogress"&&(i=n.shift(),r--),i&&(t==="fx"&&n.unshift("inprogress"),delete s.stop,i.call(e,o,s)),!r&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return v._data(e,n)||v._data(e,n,{empty:v.Callbacks("once memory").add(function(){v.removeData(e,t+"queue",!0),v.removeData(e,n,!0)})})}}),v.fn.extend({queue:function(e,n){var r=2;return typeof e!="string"&&(n=e,e="fx",r--),arguments.length<r?v.queue(this[0],e):n===t?this:this.each(function(){var t=v.queue(this,e,n);v._queueHooks(this,e),e==="fx"&&t[0]!=="inprogress"&&v.dequeue(this,e)})},dequeue:function(e){return this.each(function(){v.dequeue(this,e)})},delay:function(e,t){return e=v.fx?v.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,s=v.Deferred(),o=this,u=this.length,a=function(){--i||s.resolveWith(o,[o])};typeof e!="string"&&(n=e,e=t),e=e||"fx";while(u--)r=v._data(o[u],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(a));return a(),s.promise(n)}});var j,F,I,q=/[\t\r\n]/g,R=/\r/g,U=/^(?:button|input)$/i,z=/^(?:button|input|object|select|textarea)$/i,W=/^a(?:rea|)$/i,X=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,V=v.support.getSetAttribute;v.fn.extend({attr:function(e,t){return v.access(this,v.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){v.removeAttr(this,e)})},prop:function(e,t){return v.access(this,v.prop,e,t,arguments.length>1)},removeProp:function(e){return e=v.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,s,o,u;if(v.isFunction(e))return this.each(function(t){v(this).addClass(e.call(this,t,this.className))});if(e&&typeof e=="string"){t=e.split(y);for(n=0,r=this.length;n<r;n++){i=this[n];if(i.nodeType===1)if(!i.className&&t.length===1)i.className=e;else{s=" "+i.className+" ";for(o=0,u=t.length;o<u;o++)s.indexOf(" "+t[o]+" ")<0&&(s+=t[o]+" ");i.className=v.trim(s)}}}return this},removeClass:function(e){var n,r,i,s,o,u,a;if(v.isFunction(e))return this.each(function(t){v(this).removeClass(e.call(this,t,this.className))});if(e&&typeof e=="string"||e===t){n=(e||"").split(y);for(u=0,a=this.length;u<a;u++){i=this[u];if(i.nodeType===1&&i.className){r=(" "+i.className+" ").replace(q," ");for(s=0,o=n.length;s<o;s++)while(r.indexOf(" "+n[s]+" ")>=0)r=r.replace(" "+n[s]+" "," ");i.className=e?v.trim(r):""}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t=="boolean";return v.isFunction(e)?this.each(function(n){v(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n==="string"){var i,s=0,o=v(this),u=t,a=e.split(y);while(i=a[s++])u=r?u:!o.hasClass(i),o[u?"addClass":"removeClass"](i)}else if(n==="undefined"||n==="boolean")this.className&&v._data(this,"__className__",this.className),this.className=this.className||e===!1?"":v._data(this,"__className__")||""})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;n<r;n++)if(this[n].nodeType===1&&(" "+this[n].className+" ").replace(q," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,s=this[0];if(!arguments.length){if(s)return n=v.valHooks[s.type]||v.valHooks[s.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(s,"value"))!==t?r:(r=s.value,typeof r=="string"?r.replace(R,""):r==null?"":r);return}return i=v.isFunction(e),this.each(function(r){var s,o=v(this);if(this.nodeType!==1)return;i?s=e.call(this,r,o.val()):s=e,s==null?s="":typeof s=="number"?s+="":v.isArray(s)&&(s=v.map(s,function(e){return e==null?"":e+""})),n=v.valHooks[this.type]||v.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,s,"value")===t)this.value=s})}}),v.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,s=e.type==="select-one"||i<0,o=s?null:[],u=s?i+1:r.length,a=i<0?u:s?i:0;for(;a<u;a++){n=r[a];if((n.selected||a===i)&&(v.support.optDisabled?!n.disabled:n.getAttribute("disabled")===null)&&(!n.parentNode.disabled||!v.nodeName(n.parentNode,"optgroup"))){t=v(n).val();if(s)return t;o.push(t)}}return o},set:function(e,t){var n=v.makeArray(t);return v(e).find("option").each(function(){this.selected=v.inArray(v(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var s,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2)return;if(i&&v.isFunction(v.fn[n]))return v(e)[n](r);if(typeof e.getAttribute=="undefined")return v.prop(e,n,r);u=a!==1||!v.isXMLDoc(e),u&&(n=n.toLowerCase(),o=v.attrHooks[n]||(X.test(n)?F:j));if(r!==t){if(r===null){v.removeAttr(e,n);return}return o&&"set"in o&&u&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r)}return o&&"get"in o&&u&&(s=o.get(e,n))!==null?s:(s=e.getAttribute(n),s===null?t:s)},removeAttr:function(e,t){var n,r,i,s,o=0;if(t&&e.nodeType===1){r=t.split(y);for(;o<r.length;o++)i=r[o],i&&(n=v.propFix[i]||i,s=X.test(i),s||v.attr(e,i,""),e.removeAttribute(V?i:n),s&&n in e&&(e[n]=!1))}},attrHooks:{type:{set:function(e,t){if(U.test(e.nodeName)&&e.parentNode)v.error("type property can't be changed");else if(!v.support.radioValue&&t==="radio"&&v.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}},value:{get:function(e,t){return j&&v.nodeName(e,"button")?j.get(e,t):t in e?e.value:null},set:function(e,t,n){if(j&&v.nodeName(e,"button"))return j.set(e,t,n);e.value=t}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(e,n,r){var i,s,o,u=e.nodeType;if(!e||u===3||u===8||u===2)return;return o=u!==1||!v.isXMLDoc(e),o&&(n=v.propFix[n]||n,s=v.propHooks[n]),r!==t?s&&"set"in s&&(i=s.set(e,r,n))!==t?i:e[n]=r:s&&"get"in s&&(i=s.get(e,n))!==null?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):z.test(e.nodeName)||W.test(e.nodeName)&&e.href?0:t}}}}),F={get:function(e,n){var r,i=v.prop(e,n);return i===!0||typeof i!="boolean"&&(r=e.getAttributeNode(n))&&r.nodeValue!==!1?n.toLowerCase():t},set:function(e,t,n){var r;return t===!1?v.removeAttr(e,n):(r=v.propFix[n]||n,r in e&&(e[r]=!0),e.setAttribute(n,n.toLowerCase())),n}},V||(I={name:!0,id:!0,coords:!0},j=v.valHooks.button={get:function(e,n){var r;return r=e.getAttributeNode(n),r&&(I[n]?r.value!=="":r.specified)?r.value:t},set:function(e,t,n){var r=e.getAttributeNode(n);return r||(r=i.createAttribute(n),e.setAttributeNode(r)),r.value=t+""}},v.each(["width","height"],function(e,t){v.attrHooks[t]=v.extend(v.attrHooks[t],{set:function(e,n){if(n==="")return e.setAttribute(t,"auto"),n}})}),v.attrHooks.contenteditable={get:j.get,set:function(e,t,n){t===""&&(t="false"),j.set(e,t,n)}}),v.support.hrefNormalized||v.each(["href","src","width","height"],function(e,n){v.attrHooks[n]=v.extend(v.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return r===null?t:r}})}),v.support.style||(v.attrHooks.style={get:function(e){return e.style.cssText.toLowerCase()||t},set:function(e,t){return e.style.cssText=t+""}}),v.support.optSelected||(v.propHooks.selected=v.extend(v.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),v.support.enctype||(v.propFix.enctype="encoding"),v.support.checkOn||v.each(["radio","checkbox"],function(){v.valHooks[this]={get:function(e){return e.getAttribute("value")===null?"on":e.value}}}),v.each(["radio","checkbox"],function(){v.valHooks[this]=v.extend(v.valHooks[this],{set:function(e,t){if(v.isArray(t))return e.checked=v.inArray(v(e).val(),t)>=0}})});var $=/^(?:textarea|input|select)$/i,J=/^([^\.]*|)(?:\.(.+)|)$/,K=/(?:^|\s)hover(\.\S+|)\b/,Q=/^key/,G=/^(?:mouse|contextmenu)|click/,Y=/^(?:focusinfocus|focusoutblur)$/,Z=function(e){return v.event.special.hover?e:e.replace(K,"mouseenter$1 mouseleave$1")};v.event={add:function(e,n,r,i,s){var o,u,a,f,l,c,h,p,d,m,g;if(e.nodeType===3||e.nodeType===8||!n||!r||!(o=v._data(e)))return;r.handler&&(d=r,r=d.handler,s=d.selector),r.guid||(r.guid=v.guid++),a=o.events,a||(o.events=a={}),u=o.handle,u||(o.handle=u=function(e){return typeof v=="undefined"||!!e&&v.event.triggered===e.type?t:v.event.dispatch.apply(u.elem,arguments)},u.elem=e),n=v.trim(Z(n)).split(" ");for(f=0;f<n.length;f++){l=J.exec(n[f])||[],c=l[1],h=(l[2]||"").split(".").sort(),g=v.event.special[c]||{},c=(s?g.delegateType:g.bindType)||c,g=v.event.special[c]||{},p=v.extend({type:c,origType:l[1],data:i,handler:r,guid:r.guid,selector:s,needsContext:s&&v.expr.match.needsContext.test(s),namespace:h.join(".")},d),m=a[c];if(!m){m=a[c]=[],m.delegateCount=0;if(!g.setup||g.setup.call(e,i,h,u)===!1)e.addEventListener?e.addEventListener(c,u,!1):e.attachEvent&&e.attachEvent("on"+c,u)}g.add&&(g.add.call(e,p),p.handler.guid||(p.handler.guid=r.guid)),s?m.splice(m.delegateCount++,0,p):m.push(p),v.event.global[c]=!0}e=null},global:{},remove:function(e,t,n,r,i){var s,o,u,a,f,l,c,h,p,d,m,g=v.hasData(e)&&v._data(e);if(!g||!(h=g.events))return;t=v.trim(Z(t||"")).split(" ");for(s=0;s<t.length;s++){o=J.exec(t[s])||[],u=a=o[1],f=o[2];if(!u){for(u in h)v.event.remove(e,u+t[s],n,r,!0);continue}p=v.event.special[u]||{},u=(r?p.delegateType:p.bindType)||u,d=h[u]||[],l=d.length,f=f?new RegExp("(^|\\.)"+f.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(c=0;c<d.length;c++)m=d[c],(i||a===m.origType)&&(!n||n.guid===m.guid)&&(!f||f.test(m.namespace))&&(!r||r===m.selector||r==="**"&&m.selector)&&(d.splice(c--,1),m.selector&&d.delegateCount--,p.remove&&p.remove.call(e,m));d.length===0&&l!==d.length&&((!p.teardown||p.teardown.call(e,f,g.handle)===!1)&&v.removeEvent(e,u,g.handle),delete h[u])}v.isEmptyObject(h)&&(delete g.handle,v.removeData(e,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(n,r,s,o){if(!s||s.nodeType!==3&&s.nodeType!==8){var u,a,f,l,c,h,p,d,m,g,y=n.type||n,b=[];if(Y.test(y+v.event.triggered))return;y.indexOf("!")>=0&&(y=y.slice(0,-1),a=!0),y.indexOf(".")>=0&&(b=y.split("."),y=b.shift(),b.sort());if((!s||v.event.customEvent[y])&&!v.event.global[y])return;n=typeof n=="object"?n[v.expando]?n:new v.Event(y,n):new v.Event(y),n.type=y,n.isTrigger=!0,n.exclusive=a,n.namespace=b.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+b.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,h=y.indexOf(":")<0?"on"+y:"";if(!s){u=v.cache;for(f in u)u[f].events&&u[f].events[y]&&v.event.trigger(n,r,u[f].handle.elem,!0);return}n.result=t,n.target||(n.target=s),r=r!=null?v.makeArray(r):[],r.unshift(n),p=v.event.special[y]||{};if(p.trigger&&p.trigger.apply(s,r)===!1)return;m=[[s,p.bindType||y]];if(!o&&!p.noBubble&&!v.isWindow(s)){g=p.delegateType||y,l=Y.test(g+y)?s:s.parentNode;for(c=s;l;l=l.parentNode)m.push([l,g]),c=l;c===(s.ownerDocument||i)&&m.push([c.defaultView||c.parentWindow||e,g])}for(f=0;f<m.length&&!n.isPropagationStopped();f++)l=m[f][0],n.type=m[f][1],d=(v._data(l,"events")||{})[n.type]&&v._data(l,"handle"),d&&d.apply(l,r),d=h&&l[h],d&&v.acceptData(l)&&d.apply&&d.apply(l,r)===!1&&n.preventDefault();return n.type=y,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(s.ownerDocument,r)===!1)&&(y!=="click"||!v.nodeName(s,"a"))&&v.acceptData(s)&&h&&s[y]&&(y!=="focus"&&y!=="blur"||n.target.offsetWidth!==0)&&!v.isWindow(s)&&(c=s[h],c&&(s[h]=null),v.event.triggered=y,s[y](),v.event.triggered=t,c&&(s[h]=c)),n.result}return},dispatch:function(n){n=v.event.fix(n||e.event);var r,i,s,o,u,a,f,c,h,p,d=(v._data(this,"events")||{})[n.type]||[],m=d.delegateCount,g=l.call(arguments),y=!n.exclusive&&!n.namespace,b=v.event.special[n.type]||{},w=[];g[0]=n,n.delegateTarget=this;if(b.preDispatch&&b.preDispatch.call(this,n)===!1)return;if(m&&(!n.button||n.type!=="click"))for(s=n.target;s!=this;s=s.parentNode||this)if(s.disabled!==!0||n.type!=="click"){u={},f=[];for(r=0;r<m;r++)c=d[r],h=c.selector,u[h]===t&&(u[h]=c.needsContext?v(h,this).index(s)>=0:v.find(h,this,null,[s]).length),u[h]&&f.push(c);f.length&&w.push({elem:s,matches:f})}d.length>m&&w.push({elem:this,matches:d.slice(m)});for(r=0;r<w.length&&!n.isPropagationStopped();r++){a=w[r],n.currentTarget=a.elem;for(i=0;i<a.matches.length&&!n.isImmediatePropagationStopped();i++){c=a.matches[i];if(y||!n.namespace&&!c.namespace||n.namespace_re&&n.namespace_re.test(c.namespace))n.data=c.data,n.handleObj=c,o=((v.event.special[c.origType]||{}).handle||c.handler).apply(a.elem,g),o!==t&&(n.result=o,o===!1&&(n.preventDefault(),n.stopPropagation()))}}return b.postDispatch&&b.postDispatch.call(this,n),n.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return e.which==null&&(e.which=t.charCode!=null?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,s,o,u=n.button,a=n.fromElement;return e.pageX==null&&n.clientX!=null&&(r=e.target.ownerDocument||i,s=r.documentElement,o=r.body,e.pageX=n.clientX+(s&&s.scrollLeft||o&&o.scrollLeft||0)-(s&&s.clientLeft||o&&o.clientLeft||0),e.pageY=n.clientY+(s&&s.scrollTop||o&&o.scrollTop||0)-(s&&s.clientTop||o&&o.clientTop||0)),!e.relatedTarget&&a&&(e.relatedTarget=a===e.target?n.toElement:a),!e.which&&u!==t&&(e.which=u&1?1:u&2?3:u&4?2:0),e}},fix:function(e){if(e[v.expando])return e;var t,n,r=e,s=v.event.fixHooks[e.type]||{},o=s.props?this.props.concat(s.props):this.props;e=v.Event(r);for(t=o.length;t;)n=o[--t],e[n]=r[n];return e.target||(e.target=r.srcElement||i),e.target.nodeType===3&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,r):e},special:{load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(e,t,n){v.isWindow(this)&&(this.onbeforeunload=n)},teardown:function(e,t){this.onbeforeunload===t&&(this.onbeforeunload=null)}}},simulate:function(e,t,n,r){var i=v.extend(new v.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?v.event.trigger(i,null,t):v.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},v.event.handle=v.event.dispatch,v.removeEvent=i.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]=="undefined"&&(e[r]=null),e.detachEvent(r,n))},v.Event=function(e,t){if(!(this instanceof v.Event))return new v.Event(e,t);e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?tt:et):this.type=e,t&&v.extend(this,t),this.timeStamp=e&&e.timeStamp||v.now(),this[v.expando]=!0},v.Event.prototype={preventDefault:function(){this.isDefaultPrevented=tt;var e=this.originalEvent;if(!e)return;e.preventDefault?e.preventDefault():e.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=tt;var e=this.originalEvent;if(!e)return;e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=tt,this.stopPropagation()},isDefaultPrevented:et,isPropagationStopped:et,isImmediatePropagationStopped:et},v.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){v.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,s=e.handleObj,o=s.selector;if(!i||i!==r&&!v.contains(r,i))e.type=s.origType,n=s.handler.apply(this,arguments),e.type=t;return n}}}),v.support.submitBubbles||(v.event.special.submit={setup:function(){if(v.nodeName(this,"form"))return!1;v.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=v.nodeName(n,"input")||v.nodeName(n,"button")?n.form:t;r&&!v._data(r,"_submit_attached")&&(v.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),v._data(r,"_submit_attached",!0))})},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&v.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){if(v.nodeName(this,"form"))return!1;v.event.remove(this,"._submit")}}),v.support.changeBubbles||(v.event.special.change={setup:function(){if($.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")v.event.add(this,"propertychange._change",function(e){e.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),v.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),v.event.simulate("change",this,e,!0)});return!1}v.event.add(this,"beforeactivate._change",function(e){var t=e.target;$.test(t.nodeName)&&!v._data(t,"_change_attached")&&(v.event.add(t,"change._change",function(e){this.parentNode&&!e.isSimulated&&!e.isTrigger&&v.event.simulate("change",this.parentNode,e,!0)}),v._data(t,"_change_attached",!0))})},handle:function(e){var t=e.target;if(this!==t||e.isSimulated||e.isTrigger||t.type!=="radio"&&t.type!=="checkbox")return e.handleObj.handler.apply(this,arguments)},teardown:function(){return v.event.remove(this,"._change"),!$.test(this.nodeName)}}),v.support.focusinBubbles||v.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){v.event.simulate(t,e.target,v.event.fix(e),!0)};v.event.special[t]={setup:function(){n++===0&&i.addEventListener(e,r,!0)},teardown:function(){--n===0&&i.removeEventListener(e,r,!0)}}}),v.fn.extend({on:function(e,n,r,i,s){var o,u;if(typeof e=="object"){typeof n!="string"&&(r=r||n,n=t);for(u in e)this.on(u,n,r,e[u],s);return this}r==null&&i==null?(i=n,r=n=t):i==null&&(typeof n=="string"?(i=r,r=t):(i=r,r=n,n=t));if(i===!1)i=et;else if(!i)return this;return s===1&&(o=i,i=function(e){return v().off(e),o.apply(this,arguments)},i.guid=o.guid||(o.guid=v.guid++)),this.each(function(){v.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,s;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,v(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if(typeof e=="object"){for(s in e)this.off(s,n,e[s]);return this}if(n===!1||typeof n=="function")r=n,n=t;return r===!1&&(r=et),this.each(function(){v.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},live:function(e,t,n){return v(this.context).on(e,this.selector,t,n),this},die:function(e,t){return v(this.context).off(e,this.selector||"**",t),this},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return arguments.length===1?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){v.event.trigger(e,t,this)})},triggerHandler:function(e,t){if(this[0])return v.event.trigger(e,t,this[0],!0)},toggle:function(e){var t=arguments,n=e.guid||v.guid++,r=0,i=function(n){var i=(v._data(this,"lastToggle"+e.guid)||0)%r;return v._data(this,"lastToggle"+e.guid,i+1),n.preventDefault(),t[i].apply(this,arguments)||!1};i.guid=n;while(r<t.length)t[r++].guid=n;return this.click(i)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),v.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(e,t){v.fn[t]=function(e,n){return n==null&&(n=e,e=null),arguments.length>0?this.on(t,null,e,n):this.trigger(t)},Q.test(t)&&(v.event.fixHooks[t]=v.event.keyHooks),G.test(t)&&(v.event.fixHooks[t]=v.event.mouseHooks)}),function(e,t){function nt(e,t,n,r){n=n||[],t=t||g;var i,s,a,f,l=t.nodeType;if(!e||typeof e!="string")return n;if(l!==1&&l!==9)return[];a=o(t);if(!a&&!r)if(i=R.exec(e))if(f=i[1]){if(l===9){s=t.getElementById(f);if(!s||!s.parentNode)return n;if(s.id===f)return n.push(s),n}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(f))&&u(t,s)&&s.id===f)return n.push(s),n}else{if(i[2])return S.apply(n,x.call(t.getElementsByTagName(e),0)),n;if((f=i[3])&&Z&&t.getElementsByClassName)return S.apply(n,x.call(t.getElementsByClassName(f),0)),n}return vt(e.replace(j,"$1"),t,n,r,a)}function rt(e){return function(t){var n=t.nodeName.toLowerCase();return n==="input"&&t.type===e}}function it(e){return function(t){var n=t.nodeName.toLowerCase();return(n==="input"||n==="button")&&t.type===e}}function st(e){return N(function(t){return t=+t,N(function(n,r){var i,s=e([],n.length,t),o=s.length;while(o--)n[i=s[o]]&&(n[i]=!(r[i]=n[i]))})})}function ot(e,t,n){if(e===t)return n;var r=e.nextSibling;while(r){if(r===t)return-1;r=r.nextSibling}return 1}function ut(e,t){var n,r,s,o,u,a,f,l=L[d][e+" "];if(l)return t?0:l.slice(0);u=e,a=[],f=i.preFilter;while(u){if(!n||(r=F.exec(u)))r&&(u=u.slice(r[0].length)||u),a.push(s=[]);n=!1;if(r=I.exec(u))s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=r[0].replace(j," ");for(o in i.filter)(r=J[o].exec(u))&&(!f[o]||(r=f[o](r)))&&(s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=o,n.matches=r);if(!n)break}return t?u.length:u?nt.error(e):L(e,a).slice(0)}function at(e,t,r){var i=t.dir,s=r&&t.dir==="parentNode",o=w++;return t.first?function(t,n,r){while(t=t[i])if(s||t.nodeType===1)return e(t,n,r)}:function(t,r,u){if(!u){var a,f=b+" "+o+" ",l=f+n;while(t=t[i])if(s||t.nodeType===1){if((a=t[d])===l)return t.sizset;if(typeof a=="string"&&a.indexOf(f)===0){if(t.sizset)return t}else{t[d]=l;if(e(t,r,u))return t.sizset=!0,t;t.sizset=!1}}}else while(t=t[i])if(s||t.nodeType===1)if(e(t,r,u))return t}}function ft(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function lt(e,t,n,r,i){var s,o=[],u=0,a=e.length,f=t!=null;for(;u<a;u++)if(s=e[u])if(!n||n(s,r,i))o.push(s),f&&t.push(u);return o}function ct(e,t,n,r,i,s){return r&&!r[d]&&(r=ct(r)),i&&!i[d]&&(i=ct(i,s)),N(function(s,o,u,a){var f,l,c,h=[],p=[],d=o.length,v=s||dt(t||"*",u.nodeType?[u]:u,[]),m=e&&(s||!t)?lt(v,h,e,u,a):v,g=n?i||(s?e:d||r)?[]:o:m;n&&n(m,g,u,a);if(r){f=lt(g,p),r(f,[],u,a),l=f.length;while(l--)if(c=f[l])g[p[l]]=!(m[p[l]]=c)}if(s){if(i||e){if(i){f=[],l=g.length;while(l--)(c=g[l])&&f.push(m[l]=c);i(null,g=[],f,a)}l=g.length;while(l--)(c=g[l])&&(f=i?T.call(s,c):h[l])>-1&&(s[f]=!(o[f]=c))}}else g=lt(g===o?g.splice(d,g.length):g),i?i(null,o,g,a):S.apply(o,g)})}function ht(e){var t,n,r,s=e.length,o=i.relative[e[0].type],u=o||i.relative[" "],a=o?1:0,f=at(function(e){return e===t},u,!0),l=at(function(e){return T.call(t,e)>-1},u,!0),h=[function(e,n,r){return!o&&(r||n!==c)||((t=n).nodeType?f(e,n,r):l(e,n,r))}];for(;a<s;a++)if(n=i.relative[e[a].type])h=[at(ft(h),n)];else{n=i.filter[e[a].type].apply(null,e[a].matches);if(n[d]){r=++a;for(;r<s;r++)if(i.relative[e[r].type])break;return ct(a>1&&ft(h),a>1&&e.slice(0,a-1).join("").replace(j,"$1"),n,a<r&&ht(e.slice(a,r)),r<s&&ht(e=e.slice(r)),r<s&&e.join(""))}h.push(n)}return ft(h)}function pt(e,t){var r=t.length>0,s=e.length>0,o=function(u,a,f,l,h){var p,d,v,m=[],y=0,w="0",x=u&&[],T=h!=null,N=c,C=u||s&&i.find.TAG("*",h&&a.parentNode||a),k=b+=N==null?1:Math.E;T&&(c=a!==g&&a,n=o.el);for(;(p=C[w])!=null;w++){if(s&&p){for(d=0;v=e[d];d++)if(v(p,a,f)){l.push(p);break}T&&(b=k,n=++o.el)}r&&((p=!v&&p)&&y--,u&&x.push(p))}y+=w;if(r&&w!==y){for(d=0;v=t[d];d++)v(x,m,a,f);if(u){if(y>0)while(w--)!x[w]&&!m[w]&&(m[w]=E.call(l));m=lt(m)}S.apply(l,m),T&&!u&&m.length>0&&y+t.length>1&&nt.uniqueSort(l)}return T&&(b=k,c=N),x};return o.el=0,r?N(o):o}function dt(e,t,n){var r=0,i=t.length;for(;r<i;r++)nt(e,t[r],n);return n}function vt(e,t,n,r,s){var o,u,f,l,c,h=ut(e),p=h.length;if(!r&&h.length===1){u=h[0]=h[0].slice(0);if(u.length>2&&(f=u[0]).type==="ID"&&t.nodeType===9&&!s&&i.relative[u[1].type]){t=i.find.ID(f.matches[0].replace($,""),t,s)[0];if(!t)return n;e=e.slice(u.shift().length)}for(o=J.POS.test(e)?-1:u.length-1;o>=0;o--){f=u[o];if(i.relative[l=f.type])break;if(c=i.find[l])if(r=c(f.matches[0].replace($,""),z.test(u[0].type)&&t.parentNode||t,s)){u.splice(o,1),e=r.length&&u.join("");if(!e)return S.apply(n,x.call(r,0)),n;break}}}return a(e,h)(r,t,s,n,z.test(e)),n}function mt(){}var n,r,i,s,o,u,a,f,l,c,h=!0,p="undefined",d=("sizcache"+Math.random()).replace(".",""),m=String,g=e.document,y=g.documentElement,b=0,w=0,E=[].pop,S=[].push,x=[].slice,T=[].indexOf||function(e){var t=0,n=this.length;for(;t<n;t++)if(this[t]===e)return t;return-1},N=function(e,t){return e[d]=t==null||t,e},C=function(){var e={},t=[];return N(function(n,r){return t.push(n)>i.cacheLength&&delete e[t.shift()],e[n+" "]=r},e)},k=C(),L=C(),A=C(),O="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",_=M.replace("w","w#"),D="([*^$|!~]?=)",P="\\["+O+"*("+M+")"+O+"*(?:"+D+O+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+_+")|)|)"+O+"*\\]",H=":("+M+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+P+")|[^:]|\\\\.)*|.*))\\)|)",B=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+O+"*((?:-\\d)?\\d*)"+O+"*\\)|)(?=[^-]|$)",j=new RegExp("^"+O+"+|((?:^|[^\\\\])(?:\\\\.)*)"+O+"+$","g"),F=new RegExp("^"+O+"*,"+O+"*"),I=new RegExp("^"+O+"*([\\x20\\t\\r\\n\\f>+~])"+O+"*"),q=new RegExp(H),R=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,U=/^:not/,z=/[\x20\t\r\n\f]*[+~]/,W=/:not\($/,X=/h\d/i,V=/input|select|textarea|button/i,$=/\\(?!\\)/g,J={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),NAME:new RegExp("^\\[name=['\"]?("+M+")['\"]?\\]"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+H),POS:new RegExp(B,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+O+"*(even|odd|(([+-]|)(\\d*)n|)"+O+"*(?:([+-]|)"+O+"*(\\d+)|))"+O+"*\\)|)","i"),needsContext:new RegExp("^"+O+"*[>+~]|"+B,"i")},K=function(e){var t=g.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}},Q=K(function(e){return e.appendChild(g.createComment("")),!e.getElementsByTagName("*").length}),G=K(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==p&&e.firstChild.getAttribute("href")==="#"}),Y=K(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return t!=="boolean"&&t!=="string"}),Z=K(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!e.getElementsByClassName||!e.getElementsByClassName("e").length?!1:(e.lastChild.className="e",e.getElementsByClassName("e").length===2)}),et=K(function(e){e.id=d+0,e.innerHTML="<a name='"+d+"'></a><div name='"+d+"'></div>",y.insertBefore(e,y.firstChild);var t=g.getElementsByName&&g.getElementsByName(d).length===2+g.getElementsByName(d+0).length;return r=!g.getElementById(d),y.removeChild(e),t});try{x.call(y.childNodes,0)[0].nodeType}catch(tt){x=function(e){var t,n=[];for(;t=this[e];e++)n.push(t);return n}}nt.matches=function(e,t){return nt(e,null,null,t)},nt.matchesSelector=function(e,t){return nt(t,null,null,[e]).length>0},s=nt.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(i===1||i===9||i===11){if(typeof e.textContent=="string")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=s(e)}else if(i===3||i===4)return e.nodeValue}else for(;t=e[r];r++)n+=s(t);return n},o=nt.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!=="HTML":!1},u=nt.contains=y.contains?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t&&t.parentNode;return e===r||!!(r&&r.nodeType===1&&n.contains&&n.contains(r))}:y.compareDocumentPosition?function(e,t){return t&&!!(e.compareDocumentPosition(t)&16)}:function(e,t){while(t=t.parentNode)if(t===e)return!0;return!1},nt.attr=function(e,t){var n,r=o(e);return r||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):r||Y?e.getAttribute(t):(n=e.getAttributeNode(t),n?typeof e[t]=="boolean"?e[t]?t:null:n.specified?n.value:null:null)},i=nt.selectors={cacheLength:50,createPseudo:N,match:J,attrHandle:G?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:r?function(e,t,n){if(typeof t.getElementById!==p&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==p&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==p&&i.getAttributeNode("id").value===e?[i]:t:[]}},TAG:Q?function(e,t){if(typeof t.getElementsByTagName!==p)return t.getElementsByTagName(e)}:function(e,t){var n=t.getElementsByTagName(e);if(e==="*"){var r,i=[],s=0;for(;r=n[s];s++)r.nodeType===1&&i.push(r);return i}return n},NAME:et&&function(e,t){if(typeof t.getElementsByName!==p)return t.getElementsByName(name)},CLASS:Z&&function(e,t,n){if(typeof t.getElementsByClassName!==p&&!n)return t.getElementsByClassName(e)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace($,""),e[3]=(e[4]||e[5]||"").replace($,""),e[2]==="~="&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1]==="nth"?(e[2]||nt.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd")),e[4]=+(e[6]+e[7]||e[2]==="odd")):e[2]&&nt.error(e[0]),e},PSEUDO:function(e){var t,n;if(J.CHILD.test(e[0]))return null;if(e[3])e[2]=e[3];else if(t=e[4])q.test(t)&&(n=ut(t,!0))&&(n=t.indexOf(")",t.length-n)-t.length)&&(t=t.slice(0,n),e[0]=e[0].slice(0,n)),e[2]=t;return e.slice(0,3)}},filter:{ID:r?function(e){return e=e.replace($,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace($,""),function(t){var n=typeof t.getAttributeNode!==p&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return e==="*"?function(){return!0}:(e=e.replace($,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[d][e+" "];return t||(t=new RegExp("(^|"+O+")"+e+"("+O+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==p&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r,i){var s=nt.attr(r,e);return s==null?t==="!=":t?(s+="",t==="="?s===n:t==="!="?s!==n:t==="^="?n&&s.indexOf(n)===0:t==="*="?n&&s.indexOf(n)>-1:t==="$="?n&&s.substr(s.length-n.length)===n:t==="~="?(" "+s+" ").indexOf(n)>-1:t==="|="?s===n||s.substr(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r){return e==="nth"?function(e){var t,i,s=e.parentNode;if(n===1&&r===0)return!0;if(s){i=0;for(t=s.firstChild;t;t=t.nextSibling)if(t.nodeType===1){i++;if(e===t)break}}return i-=r,i===n||i%n===0&&i/n>=0}:function(t){var n=t;switch(e){case"only":case"first":while(n=n.previousSibling)if(n.nodeType===1)return!1;if(e==="first")return!0;n=t;case"last":while(n=n.nextSibling)if(n.nodeType===1)return!1;return!0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||nt.error("unsupported pseudo: "+e);return r[d]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?N(function(e,n){var i,s=r(e,t),o=s.length;while(o--)i=T.call(e,s[o]),e[i]=!(n[i]=s[o])}):function(e){return r(e,0,n)}):r}},pseudos:{not:N(function(e){var t=[],n=[],r=a(e.replace(j,"$1"));return r[d]?N(function(e,t,n,i){var s,o=r(e,null,i,[]),u=e.length;while(u--)if(s=o[u])e[u]=!(t[u]=s)}):function(e,i,s){return t[0]=e,r(t,null,s,n),!n.pop()}}),has:N(function(e){return function(t){return nt(e,t).length>0}}),contains:N(function(e){return function(t){return(t.textContent||t.innerText||s(t)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&!!e.checked||t==="option"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!i.pseudos.empty(e)},empty:function(e){var t;e=e.firstChild;while(e){if(e.nodeName>"@"||(t=e.nodeType)===3||t===4)return!1;e=e.nextSibling}return!0},header:function(e){return X.test(e.nodeName)},text:function(e){var t,n;return e.nodeName.toLowerCase()==="input"&&(t=e.type)==="text"&&((n=e.getAttribute("type"))==null||n.toLowerCase()===t)},radio:rt("radio"),checkbox:rt("checkbox"),file:rt("file"),password:rt("password"),image:rt("image"),submit:it("submit"),reset:it("reset"),button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&e.type==="button"||t==="button"},input:function(e){return V.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:st(function(){return[0]}),last:st(function(e,t){return[t-1]}),eq:st(function(e,t,n){return[n<0?n+t:n]}),even:st(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:st(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:st(function(e,t,n){for(var r=n<0?n+t:n;--r>=0;)e.push(r);return e}),gt:st(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}},f=y.compareDocumentPosition?function(e,t){return e===t?(l=!0,0):(!e.compareDocumentPosition||!t.compareDocumentPosition?e.compareDocumentPosition:e.compareDocumentPosition(t)&4)?-1:1}:function(e,t){if(e===t)return l=!0,0;if(e.sourceIndex&&t.sourceIndex)return e.sourceIndex-t.sourceIndex;var n,r,i=[],s=[],o=e.parentNode,u=t.parentNode,a=o;if(o===u)return ot(e,t);if(!o)return-1;if(!u)return 1;while(a)i.unshift(a),a=a.parentNode;a=u;while(a)s.unshift(a),a=a.parentNode;n=i.length,r=s.length;for(var f=0;f<n&&f<r;f++)if(i[f]!==s[f])return ot(i[f],s[f]);return f===n?ot(e,s[f],-1):ot(i[f],t,1)},[0,0].sort(f),h=!l,nt.uniqueSort=function(e){var t,n=[],r=1,i=0;l=h,e.sort(f);if(l){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e},nt.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},a=nt.compile=function(e,t){var n,r=[],i=[],s=A[d][e+" "];if(!s){t||(t=ut(e)),n=t.length;while(n--)s=ht(t[n]),s[d]?r.push(s):i.push(s);s=A(e,pt(i,r))}return s},g.querySelectorAll&&function(){var e,t=vt,n=/'|\\/g,r=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,i=[":focus"],s=[":active"],u=y.matchesSelector||y.mozMatchesSelector||y.webkitMatchesSelector||y.oMatchesSelector||y.msMatchesSelector;K(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||i.push("\\["+O+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||i.push(":checked")}),K(function(e){e.innerHTML="<p test=''></p>",e.querySelectorAll("[test^='']").length&&i.push("[*^$]="+O+"*(?:\"\"|'')"),e.innerHTML="<input type='hidden'/>",e.querySelectorAll(":enabled").length||i.push(":enabled",":disabled")}),i=new RegExp(i.join("|")),vt=function(e,r,s,o,u){if(!o&&!u&&!i.test(e)){var a,f,l=!0,c=d,h=r,p=r.nodeType===9&&e;if(r.nodeType===1&&r.nodeName.toLowerCase()!=="object"){a=ut(e),(l=r.getAttribute("id"))?c=l.replace(n,"\\$&"):r.setAttribute("id",c),c="[id='"+c+"'] ",f=a.length;while(f--)a[f]=c+a[f].join("");h=z.test(e)&&r.parentNode||r,p=a.join(",")}if(p)try{return S.apply(s,x.call(h.querySelectorAll(p),0)),s}catch(v){}finally{l||r.removeAttribute("id")}}return t(e,r,s,o,u)},u&&(K(function(t){e=u.call(t,"div");try{u.call(t,"[test!='']:sizzle"),s.push("!=",H)}catch(n){}}),s=new RegExp(s.join("|")),nt.matchesSelector=function(t,n){n=n.replace(r,"='$1']");if(!o(t)&&!s.test(n)&&!i.test(n))try{var a=u.call(t,n);if(a||e||t.document&&t.document.nodeType!==11)return a}catch(f){}return nt(n,null,null,[t]).length>0})}(),i.pseudos.nth=i.pseudos.eq,i.filters=mt.prototype=i.pseudos,i.setFilters=new mt,nt.attr=v.attr,v.find=nt,v.expr=nt.selectors,v.expr[":"]=v.expr.pseudos,v.unique=nt.uniqueSort,v.text=nt.getText,v.isXMLDoc=nt.isXML,v.contains=nt.contains}(e);var nt=/Until$/,rt=/^(?:parents|prev(?:Until|All))/,it=/^.[^:#\[\.,]*$/,st=v.expr.match.needsContext,ot={children:!0,contents:!0,next:!0,prev:!0};v.fn.extend({find:function(e){var t,n,r,i,s,o,u=this;if(typeof e!="string")return v(e).filter(function(){for(t=0,n=u.length;t<n;t++)if(v.contains(u[t],this))return!0});o=this.pushStack("","find",e);for(t=0,n=this.length;t<n;t++){r=o.length,v.find(e,this[t],o);if(t>0)for(i=r;i<o.length;i++)for(s=0;s<r;s++)if(o[s]===o[i]){o.splice(i--,1);break}}return o},has:function(e){var t,n=v(e,this),r=n.length;return this.filter(function(){for(t=0;t<r;t++)if(v.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1),"not",e)},filter:function(e){return this.pushStack(ft(this,e,!0),"filter",e)},is:function(e){return!!e&&(typeof e=="string"?st.test(e)?v(e,this.context).index(this[0])>=0:v.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,s=[],o=st.test(e)||typeof e!="string"?v(e,t||this.context):0;for(;r<i;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&n.nodeType!==11){if(o?o.index(n)>-1:v.find.matchesSelector(n,e)){s.push(n);break}n=n.parentNode}}return s=s.length>1?v.unique(s):s,this.pushStack(s,"closest",e)},index:function(e){return e?typeof e=="string"?v.inArray(this[0],v(e)):v.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n=typeof e=="string"?v(e,t):v.makeArray(e&&e.nodeType?[e]:e),r=v.merge(this.get(),n);return this.pushStack(ut(n[0])||ut(r[0])?r:v.unique(r))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),v.fn.andSelf=v.fn.addBack,v.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return v.dir(e,"parentNode")},parentsUntil:function(e,t,n){return v.dir(e,"parentNode",n)},next:function(e){return at(e,"nextSibling")},prev:function(e){return at(e,"previousSibling")},nextAll:function(e){return v.dir(e,"nextSibling")},prevAll:function(e){return v.dir(e,"previousSibling")},nextUntil:function(e,t,n){return v.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return v.dir(e,"previousSibling",n)},siblings:function(e){return v.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return v.sibling(e.firstChild)},contents:function(e){return v.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:v.merge([],e.childNodes)}},function(e,t){v.fn[e]=function(n,r){var i=v.map(this,t,n);return nt.test(e)||(r=n),r&&typeof r=="string"&&(i=v.filter(r,i)),i=this.length>1&&!ot[e]?v.unique(i):i,this.length>1&&rt.test(e)&&(i=i.reverse()),this.pushStack(i,e,l.call(arguments).join(","))}}),v.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),t.length===1?v.find.matchesSelector(t[0],e)?[t[0]]:[]:v.find.matches(e,t)},dir:function(e,n,r){var i=[],s=e[n];while(s&&s.nodeType!==9&&(r===t||s.nodeType!==1||!v(s).is(r)))s.nodeType===1&&i.push(s),s=s[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}});var ct="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",ht=/ jQuery\d+="(?:null|\d+)"/g,pt=/^\s+/,dt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,vt=/<([\w:]+)/,mt=/<tbody/i,gt=/<|&#?\w+;/,yt=/<(?:script|style|link)/i,bt=/<(?:script|object|embed|option|style)/i,wt=new RegExp("<(?:"+ct+")[\\s/>]","i"),Et=/^(?:checkbox|radio)$/,St=/checked\s*(?:[^=]|=\s*.checked.)/i,xt=/\/(java|ecma)script/i,Tt=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,Nt={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},Ct=lt(i),kt=Ct.appendChild(i.createElement("div"));Nt.optgroup=Nt.option,Nt.tbody=Nt.tfoot=Nt.colgroup=Nt.caption=Nt.thead,Nt.th=Nt.td,v.support.htmlSerialize||(Nt._default=[1,"X<div>","</div>"]),v.fn.extend({text:function(e){return v.access(this,function(e){return e===t?v.text(this):this.empty().append((this[0]&&this[0].ownerDocument||i).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(v.isFunction(e))return this.each(function(t){v(this).wrapAll(e.call(this,t))});if(this[0]){var t=v(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&e.firstChild.nodeType===1)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return v.isFunction(e)?this.each(function(t){v(this).wrapInner(e.call(this,t))}):this.each(function(){var t=v(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=v.isFunction(e);return this.each(function(n){v(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){v.nodeName(this,"body")||v(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(e,this),"before",this.selector)}},after:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(this,e),"after",this.selector)}},remove:function(e,t){var n,r=0;for(;(n=this[r])!=null;r++)if(!e||v.filter(e,[n]).length)!t&&n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),v.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n);return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++){e.nodeType===1&&v.cleanData(e.getElementsByTagName("*"));while(e.firstChild)e.removeChild(e.firstChild)}return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return v.clone(this,e,t)})},html:function(e){return v.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return n.nodeType===1?n.innerHTML.replace(ht,""):t;if(typeof e=="string"&&!yt.test(e)&&(v.support.htmlSerialize||!wt.test(e))&&(v.support.leadingWhitespace||!pt.test(e))&&!Nt[(vt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(dt,"<$1></$2>");try{for(;r<i;r++)n=this[r]||{},n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),n.innerHTML=e);n=0}catch(s){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){return ut(this[0])?this.length?this.pushStack(v(v.isFunction(e)?e():e),"replaceWith",e):this:v.isFunction(e)?this.each(function(t){var n=v(this),r=n.html();n.replaceWith(e.call(this,t,r))}):(typeof e!="string"&&(e=v(e).detach()),this.each(function(){var t=this.nextSibling,n=this.parentNode;v(this).remove(),t?v(t).before(e):v(n).append(e)}))},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=[].concat.apply([],e);var i,s,o,u,a=0,f=e[0],l=[],c=this.length;if(!v.support.checkClone&&c>1&&typeof f=="string"&&St.test(f))return this.each(function(){v(this).domManip(e,n,r)});if(v.isFunction(f))return this.each(function(i){var s=v(this);e[0]=f.call(this,i,n?s.html():t),s.domManip(e,n,r)});if(this[0]){i=v.buildFragment(e,this,l),o=i.fragment,s=o.firstChild,o.childNodes.length===1&&(o=s);if(s){n=n&&v.nodeName(s,"tr");for(u=i.cacheable||c-1;a<c;a++)r.call(n&&v.nodeName(this[a],"table")?Lt(this[a],"tbody"):this[a],a===u?o:v.clone(o,!0,!0))}o=s=null,l.length&&v.each(l,function(e,t){t.src?v.ajax?v.ajax({url:t.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):v.error("no ajax"):v.globalEval((t.text||t.textContent||t.innerHTML||"").replace(Tt,"")),t.parentNode&&t.parentNode.removeChild(t)})}return this}}),v.buildFragment=function(e,n,r){var s,o,u,a=e[0];return n=n||i,n=!n.nodeType&&n[0]||n,n=n.ownerDocument||n,e.length===1&&typeof a=="string"&&a.length<512&&n===i&&a.charAt(0)==="<"&&!bt.test(a)&&(v.support.checkClone||!St.test(a))&&(v.support.html5Clone||!wt.test(a))&&(o=!0,s=v.fragments[a],u=s!==t),s||(s=n.createDocumentFragment(),v.clean(e,n,s,r),o&&(v.fragments[a]=u&&s)),{fragment:s,cacheable:o}},v.fragments={},v.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){v.fn[e]=function(n){var r,i=0,s=[],o=v(n),u=o.length,a=this.length===1&&this[0].parentNode;if((a==null||a&&a.nodeType===11&&a.childNodes.length===1)&&u===1)return o[t](this[0]),this;for(;i<u;i++)r=(i>0?this.clone(!0):this).get(),v(o[i])[t](r),s=s.concat(r);return this.pushStack(s,e,o.selector)}}),v.extend({clone:function(e,t,n){var r,i,s,o;v.support.html5Clone||v.isXMLDoc(e)||!wt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(kt.innerHTML=e.outerHTML,kt.removeChild(o=kt.firstChild));if((!v.support.noCloneEvent||!v.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!v.isXMLDoc(e)){Ot(e,o),r=Mt(e),i=Mt(o);for(s=0;r[s];++s)i[s]&&Ot(r[s],i[s])}if(t){At(e,o);if(n){r=Mt(e),i=Mt(o);for(s=0;r[s];++s)At(r[s],i[s])}}return r=i=null,o},clean:function(e,t,n,r){var s,o,u,a,f,l,c,h,p,d,m,g,y=t===i&&Ct,b=[];if(!t||typeof t.createDocumentFragment=="undefined")t=i;for(s=0;(u=e[s])!=null;s++){typeof u=="number"&&(u+="");if(!u)continue;if(typeof u=="string")if(!gt.test(u))u=t.createTextNode(u);else{y=y||lt(t),c=t.createElement("div"),y.appendChild(c),u=u.replace(dt,"<$1></$2>"),a=(vt.exec(u)||["",""])[1].toLowerCase(),f=Nt[a]||Nt._default,l=f[0],c.innerHTML=f[1]+u+f[2];while(l--)c=c.lastChild;if(!v.support.tbody){h=mt.test(u),p=a==="table"&&!h?c.firstChild&&c.firstChild.childNodes:f[1]==="<table>"&&!h?c.childNodes:[];for(o=p.length-1;o>=0;--o)v.nodeName(p[o],"tbody")&&!p[o].childNodes.length&&p[o].parentNode.removeChild(p[o])}!v.support.leadingWhitespace&&pt.test(u)&&c.insertBefore(t.createTextNode(pt.exec(u)[0]),c.firstChild),u=c.childNodes,c.parentNode.removeChild(c)}u.nodeType?b.push(u):v.merge(b,u)}c&&(u=c=y=null);if(!v.support.appendChecked)for(s=0;(u=b[s])!=null;s++)v.nodeName(u,"input")?_t(u):typeof u.getElementsByTagName!="undefined"&&v.grep(u.getElementsByTagName("input"),_t);if(n){m=function(e){if(!e.type||xt.test(e.type))return r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e)};for(s=0;(u=b[s])!=null;s++)if(!v.nodeName(u,"script")||!m(u))n.appendChild(u),typeof u.getElementsByTagName!="undefined"&&(g=v.grep(v.merge([],u.getElementsByTagName("script")),m),b.splice.apply(b,[s+1,0].concat(g)),s+=g.length)}return b},cleanData:function(e,t){var n,r,i,s,o=0,u=v.expando,a=v.cache,f=v.support.deleteExpando,l=v.event.special;for(;(i=e[o])!=null;o++)if(t||v.acceptData(i)){r=i[u],n=r&&a[r];if(n){if(n.events)for(s in n.events)l[s]?v.event.remove(i,s):v.removeEvent(i,s,n.handle);a[r]&&(delete a[r],f?delete i[u]:i.removeAttribute?i.removeAttribute(u):i[u]=null,v.deletedIds.push(r))}}}}),function(){var e,t;v.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=v.uaMatch(o.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),v.browser=t,v.sub=function(){function e(t,n){return new e.fn.init(t,n)}v.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(r,i){return i&&i instanceof v&&!(i instanceof e)&&(i=e(i)),v.fn.init.call(this,r,i,t)},e.fn.init.prototype=e.fn;var t=e(i);return e}}();var Dt,Pt,Ht,Bt=/alpha\([^)]*\)/i,jt=/opacity=([^)]*)/,Ft=/^(top|right|bottom|left)$/,It=/^(none|table(?!-c[ea]).+)/,qt=/^margin/,Rt=new RegExp("^("+m+")(.*)$","i"),Ut=new RegExp("^("+m+")(?!px)[a-z%]+$","i"),zt=new RegExp("^([-+])=("+m+")","i"),Wt={BODY:"block"},Xt={position:"absolute",visibility:"hidden",display:"block"},Vt={letterSpacing:0,fontWeight:400},$t=["Top","Right","Bottom","Left"],Jt=["Webkit","O","Moz","ms"],Kt=v.fn.toggle;v.fn.extend({css:function(e,n){return v.access(this,function(e,n,r){return r!==t?v.style(e,n,r):v.css(e,n)},e,n,arguments.length>1)},show:function(){return Yt(this,!0)},hide:function(){return Yt(this)},toggle:function(e,t){var n=typeof e=="boolean";return v.isFunction(e)&&v.isFunction(t)?Kt.apply(this,arguments):this.each(function(){(n?e:Gt(this))?v(this).show():v(this).hide()})}}),v.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Dt(e,"opacity");return n===""?"1":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":v.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var s,o,u,a=v.camelCase(n),f=e.style;n=v.cssProps[a]||(v.cssProps[a]=Qt(f,a)),u=v.cssHooks[n]||v.cssHooks[a];if(r===t)return u&&"get"in u&&(s=u.get(e,!1,i))!==t?s:f[n];o=typeof r,o==="string"&&(s=zt.exec(r))&&(r=(s[1]+1)*s[2]+parseFloat(v.css(e,n)),o="number");if(r==null||o==="number"&&isNaN(r))return;o==="number"&&!v.cssNumber[a]&&(r+="px");if(!u||!("set"in u)||(r=u.set(e,r,i))!==t)try{f[n]=r}catch(l){}},css:function(e,n,r,i){var s,o,u,a=v.camelCase(n);return n=v.cssProps[a]||(v.cssProps[a]=Qt(e.style,a)),u=v.cssHooks[n]||v.cssHooks[a],u&&"get"in u&&(s=u.get(e,!0,i)),s===t&&(s=Dt(e,n)),s==="normal"&&n in Vt&&(s=Vt[n]),r||i!==t?(o=parseFloat(s),r||v.isNumeric(o)?o||0:s):s},swap:function(e,t,n){var r,i,s={};for(i in t)s[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=s[i];return r}}),e.getComputedStyle?Dt=function(t,n){var r,i,s,o,u=e.getComputedStyle(t,null),a=t.style;return u&&(r=u.getPropertyValue(n)||u[n],r===""&&!v.contains(t.ownerDocument,t)&&(r=v.style(t,n)),Ut.test(r)&&qt.test(n)&&(i=a.width,s=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=r,r=u.width,a.width=i,a.minWidth=s,a.maxWidth=o)),r}:i.documentElement.currentStyle&&(Dt=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],s=e.style;return i==null&&s&&s[t]&&(i=s[t]),Ut.test(i)&&!Ft.test(t)&&(n=s.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),s.left=t==="fontSize"?"1em":i,i=s.pixelLeft+"px",s.left=n,r&&(e.runtimeStyle.left=r)),i===""?"auto":i}),v.each(["height","width"],function(e,t){v.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth===0&&It.test(Dt(e,"display"))?v.swap(e,Xt,function(){return tn(e,t,r)}):tn(e,t,r)},set:function(e,n,r){return Zt(e,n,r?en(e,t,r,v.support.boxSizing&&v.css(e,"boxSizing")==="border-box"):0)}}}),v.support.opacity||(v.cssHooks.opacity={get:function(e,t){return jt.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=v.isNumeric(t)?"alpha(opacity="+t*100+")":"",s=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&v.trim(s.replace(Bt,""))===""&&n.removeAttribute){n.removeAttribute("filter");if(r&&!r.filter)return}n.filter=Bt.test(s)?s.replace(Bt,i):s+" "+i}}),v(function(){v.support.reliableMarginRight||(v.cssHooks.marginRight={get:function(e,t){return v.swap(e,{display:"inline-block"},function(){if(t)return Dt(e,"marginRight")})}}),!v.support.pixelPosition&&v.fn.position&&v.each(["top","left"],function(e,t){v.cssHooks[t]={get:function(e,n){if(n){var r=Dt(e,t);return Ut.test(r)?v(e).position()[t]+"px":r}}}})}),v.expr&&v.expr.filters&&(v.expr.filters.hidden=function(e){return e.offsetWidth===0&&e.offsetHeight===0||!v.support.reliableHiddenOffsets&&(e.style&&e.style.display||Dt(e,"display"))==="none"},v.expr.filters.visible=function(e){return!v.expr.filters.hidden(e)}),v.each({margin:"",padding:"",border:"Width"},function(e,t){v.cssHooks[e+t]={expand:function(n){var r,i=typeof n=="string"?n.split(" "):[n],s={};for(r=0;r<4;r++)s[e+$t[r]+t]=i[r]||i[r-2]||i[0];return s}},qt.test(e)||(v.cssHooks[e+t].set=Zt)});var rn=/%20/g,sn=/\[\]$/,on=/\r?\n/g,un=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,an=/^(?:select|textarea)/i;v.fn.extend({serialize:function(){return v.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?v.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||an.test(this.nodeName)||un.test(this.type))}).map(function(e,t){var n=v(this).val();return n==null?null:v.isArray(n)?v.map(n,function(e,n){return{name:t.name,value:e.replace(on,"\r\n")}}):{name:t.name,value:n.replace(on,"\r\n")}}).get()}}),v.param=function(e,n){var r,i=[],s=function(e,t){t=v.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=v.ajaxSettings&&v.ajaxSettings.traditional);if(v.isArray(e)||e.jquery&&!v.isPlainObject(e))v.each(e,function(){s(this.name,this.value)});else for(r in e)fn(r,e[r],n,s);return i.join("&").replace(rn,"+")};var ln,cn,hn=/#.*$/,pn=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,dn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,vn=/^(?:GET|HEAD)$/,mn=/^\/\//,gn=/\?/,yn=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bn=/([?&])_=[^&]*/,wn=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,En=v.fn.load,Sn={},xn={},Tn=["*/"]+["*"];try{cn=s.href}catch(Nn){cn=i.createElement("a"),cn.href="",cn=cn.href}ln=wn.exec(cn.toLowerCase())||[],v.fn.load=function(e,n,r){if(typeof e!="string"&&En)return En.apply(this,arguments);if(!this.length)return this;var i,s,o,u=this,a=e.indexOf(" ");return a>=0&&(i=e.slice(a,e.length),e=e.slice(0,a)),v.isFunction(n)?(r=n,n=t):n&&typeof n=="object"&&(s="POST"),v.ajax({url:e,type:s,dataType:"html",data:n,complete:function(e,t){r&&u.each(r,o||[e.responseText,t,e])}}).done(function(e){o=arguments,u.html(i?v("<div>").append(e.replace(yn,"")).find(i):e)}),this},v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){v.fn[t]=function(e){return this.on(t,e)}}),v.each(["get","post"],function(e,n){v[n]=function(e,r,i,s){return v.isFunction(r)&&(s=s||i,i=r,r=t),v.ajax({type:n,url:e,data:r,success:i,dataType:s})}}),v.extend({getScript:function(e,n){return v.get(e,t,n,"script")},getJSON:function(e,t,n){return v.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?Ln(e,v.ajaxSettings):(t=e,e=v.ajaxSettings),Ln(e,t),e},ajaxSettings:{url:cn,isLocal:dn.test(ln[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":Tn},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":v.parseJSON,"text xml":v.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:Cn(Sn),ajaxTransport:Cn(xn),ajax:function(e,n){function T(e,n,s,a){var l,y,b,w,S,T=n;if(E===2)return;E=2,u&&clearTimeout(u),o=t,i=a||"",x.readyState=e>0?4:0,s&&(w=An(c,x,s));if(e>=200&&e<300||e===304)c.ifModified&&(S=x.getResponseHeader("Last-Modified"),S&&(v.lastModified[r]=S),S=x.getResponseHeader("Etag"),S&&(v.etag[r]=S)),e===304?(T="notmodified",l=!0):(l=On(c,w),T=l.state,y=l.data,b=l.error,l=!b);else{b=T;if(!T||e)T="error",e<0&&(e=0)}x.status=e,x.statusText=(n||T)+"",l?d.resolveWith(h,[y,T,x]):d.rejectWith(h,[x,T,b]),x.statusCode(g),g=t,f&&p.trigger("ajax"+(l?"Success":"Error"),[x,c,l?y:b]),m.fireWith(h,[x,T]),f&&(p.trigger("ajaxComplete",[x,c]),--v.active||v.event.trigger("ajaxStop"))}typeof e=="object"&&(n=e,e=t),n=n||{};var r,i,s,o,u,a,f,l,c=v.ajaxSetup({},n),h=c.context||c,p=h!==c&&(h.nodeType||h instanceof v)?v(h):v.event,d=v.Deferred(),m=v.Callbacks("once memory"),g=c.statusCode||{},b={},w={},E=0,S="canceled",x={readyState:0,setRequestHeader:function(e,t){if(!E){var n=e.toLowerCase();e=w[n]=w[n]||e,b[e]=t}return this},getAllResponseHeaders:function(){return E===2?i:null},getResponseHeader:function(e){var n;if(E===2){if(!s){s={};while(n=pn.exec(i))s[n[1].toLowerCase()]=n[2]}n=s[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return E||(c.mimeType=e),this},abort:function(e){return e=e||S,o&&o.abort(e),T(0,e),this}};d.promise(x),x.success=x.done,x.error=x.fail,x.complete=m.add,x.statusCode=function(e){if(e){var t;if(E<2)for(t in e)g[t]=[g[t],e[t]];else t=e[x.status],x.always(t)}return this},c.url=((e||c.url)+"").replace(hn,"").replace(mn,ln[1]+"//"),c.dataTypes=v.trim(c.dataType||"*").toLowerCase().split(y),c.crossDomain==null&&(a=wn.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===ln[1]&&a[2]===ln[2]&&(a[3]||(a[1]==="http:"?80:443))==(ln[3]||(ln[1]==="http:"?80:443)))),c.data&&c.processData&&typeof c.data!="string"&&(c.data=v.param(c.data,c.traditional)),kn(Sn,c,n,x);if(E===2)return x;f=c.global,c.type=c.type.toUpperCase(),c.hasContent=!vn.test(c.type),f&&v.active++===0&&v.event.trigger("ajaxStart");if(!c.hasContent){c.data&&(c.url+=(gn.test(c.url)?"&":"?")+c.data,delete c.data),r=c.url;if(c.cache===!1){var N=v.now(),C=c.url.replace(bn,"$1_="+N);c.url=C+(C===c.url?(gn.test(c.url)?"&":"?")+"_="+N:"")}}(c.data&&c.hasContent&&c.contentType!==!1||n.contentType)&&x.setRequestHeader("Content-Type",c.contentType),c.ifModified&&(r=r||c.url,v.lastModified[r]&&x.setRequestHeader("If-Modified-Since",v.lastModified[r]),v.etag[r]&&x.setRequestHeader("If-None-Match",v.etag[r])),x.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+(c.dataTypes[0]!=="*"?", "+Tn+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)x.setRequestHeader(l,c.headers[l]);if(!c.beforeSend||c.beforeSend.call(h,x,c)!==!1&&E!==2){S="abort";for(l in{success:1,error:1,complete:1})x[l](c[l]);o=kn(xn,c,n,x);if(!o)T(-1,"No Transport");else{x.readyState=1,f&&p.trigger("ajaxSend",[x,c]),c.async&&c.timeout>0&&(u=setTimeout(function(){x.abort("timeout")},c.timeout));try{E=1,o.send(b,T)}catch(k){if(!(E<2))throw k;T(-1,k)}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var Mn=[],_n=/\?/,Dn=/(=)\?(?=&|$)|\?\?/,Pn=v.now();v.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Mn.pop()||v.expando+"_"+Pn++;return this[e]=!0,e}}),v.ajaxPrefilter("json jsonp",function(n,r,i){var s,o,u,a=n.data,f=n.url,l=n.jsonp!==!1,c=l&&Dn.test(f),h=l&&!c&&typeof a=="string"&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Dn.test(a);if(n.dataTypes[0]==="jsonp"||c||h)return s=n.jsonpCallback=v.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,o=e[s],c?n.url=f.replace(Dn,"$1"+s):h?n.data=a.replace(Dn,"$1"+s):l&&(n.url+=(_n.test(f)?"&":"?")+n.jsonp+"="+s),n.converters["script json"]=function(){return u||v.error(s+" was not called"),u[0]},n.dataTypes[0]="json",e[s]=function(){u=arguments},i.always(function(){e[s]=o,n[s]&&(n.jsonpCallback=r.jsonpCallback,Mn.push(s)),u&&v.isFunction(o)&&o(u[0]),u=o=t}),"script"}),v.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return v.globalEval(e),e}}}),v.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),v.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=i.head||i.getElementsByTagName("head")[0]||i.documentElement;return{send:function(s,o){n=i.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){if(i||!n.readyState||/loaded|complete/.test(n.readyState))n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||o(200,"success")},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var Hn,Bn=e.ActiveXObject?function(){for(var e in Hn)Hn[e](0,1)}:!1,jn=0;v.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&Fn()||In()}:Fn,function(e){v.extend(v.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(v.ajaxSettings.xhr()),v.support.ajax&&v.ajaxTransport(function(n){if(!n.crossDomain||v.support.cors){var r;return{send:function(i,s){var o,u,a=n.xhr();n.username?a.open(n.type,n.url,n.async,n.username,n.password):a.open(n.type,n.url,n.async);if(n.xhrFields)for(u in n.xhrFields)a[u]=n.xhrFields[u];n.mimeType&&a.overrideMimeType&&a.overrideMimeType(n.mimeType),!n.crossDomain&&!i["X-Requested-With"]&&(i["X-Requested-With"]="XMLHttpRequest");try{for(u in i)a.setRequestHeader(u,i[u])}catch(f){}a.send(n.hasContent&&n.data||null),r=function(e,i){var u,f,l,c,h;try{if(r&&(i||a.readyState===4)){r=t,o&&(a.onreadystatechange=v.noop,Bn&&delete Hn[o]);if(i)a.readyState!==4&&a.abort();else{u=a.status,l=a.getAllResponseHeaders(),c={},h=a.responseXML,h&&h.documentElement&&(c.xml=h);try{c.text=a.responseText}catch(p){}try{f=a.statusText}catch(p){f=""}!u&&n.isLocal&&!n.crossDomain?u=c.text?200:404:u===1223&&(u=204)}}}catch(d){i||s(-1,d)}c&&s(u,f,c,l)},n.async?a.readyState===4?setTimeout(r,0):(o=++jn,Bn&&(Hn||(Hn={},v(e).unload(Bn)),Hn[o]=r),a.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var qn,Rn,Un=/^(?:toggle|show|hide)$/,zn=new RegExp("^(?:([-+])=|)("+m+")([a-z%]*)$","i"),Wn=/queueHooks$/,Xn=[Gn],Vn={"*":[function(e,t){var n,r,i=this.createTween(e,t),s=zn.exec(t),o=i.cur(),u=+o||0,a=1,f=20;if(s){n=+s[2],r=s[3]||(v.cssNumber[e]?"":"px");if(r!=="px"&&u){u=v.css(i.elem,e,!0)||n||1;do a=a||".5",u/=a,v.style(i.elem,e,u+r);while(a!==(a=i.cur()/o)&&a!==1&&--f)}i.unit=r,i.start=u,i.end=s[1]?u+(s[1]+1)*n:n}return i}]};v.Animation=v.extend(Kn,{tweener:function(e,t){v.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;r<i;r++)n=e[r],Vn[n]=Vn[n]||[],Vn[n].unshift(t)},prefilter:function(e,t){t?Xn.unshift(e):Xn.push(e)}}),v.Tween=Yn,Yn.prototype={constructor:Yn,init:function(e,t,n,r,i,s){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=s||(v.cssNumber[n]?"":"px")},cur:function(){var e=Yn.propHooks[this.prop];return e&&e.get?e.get(this):Yn.propHooks._default.get(this)},run:function(e){var t,n=Yn.propHooks[this.prop];return this.options.duration?this.pos=t=v.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):Yn.propHooks._default.set(this),this}},Yn.prototype.init.prototype=Yn.prototype,Yn.propHooks={_default:{get:function(e){var t;return e.elem[e.prop]==null||!!e.elem.style&&e.elem.style[e.prop]!=null?(t=v.css(e.elem,e.prop,!1,""),!t||t==="auto"?0:t):e.elem[e.prop]},set:function(e){v.fx.step[e.prop]?v.fx.step[e.prop](e):e.elem.style&&(e.elem.style[v.cssProps[e.prop]]!=null||v.cssHooks[e.prop])?v.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},Yn.propHooks.scrollTop=Yn.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},v.each(["toggle","show","hide"],function(e,t){var n=v.fn[t];v.fn[t]=function(r,i,s){return r==null||typeof r=="boolean"||!e&&v.isFunction(r)&&v.isFunction(i)?n.apply(this,arguments):this.animate(Zn(t,!0),r,i,s)}}),v.fn.extend({fadeTo:function(e,t,n,r){return this.filter(Gt).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=v.isEmptyObject(e),s=v.speed(t,n,r),o=function(){var t=Kn(this,v.extend({},e),s);i&&t.stop(!0)};return i||s.queue===!1?this.each(o):this.queue(s.queue,o)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return typeof e!="string"&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=e!=null&&e+"queueHooks",s=v.timers,o=v._data(this);if(n)o[n]&&o[n].stop&&i(o[n]);else for(n in o)o[n]&&o[n].stop&&Wn.test(n)&&i(o[n]);for(n=s.length;n--;)s[n].elem===this&&(e==null||s[n].queue===e)&&(s[n].anim.stop(r),t=!1,s.splice(n,1));(t||!r)&&v.dequeue(this,e)})}}),v.each({slideDown:Zn("show"),slideUp:Zn("hide"),slideToggle:Zn("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){v.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),v.speed=function(e,t,n){var r=e&&typeof e=="object"?v.extend({},e):{complete:n||!n&&t||v.isFunction(e)&&e,duration:e,easing:n&&t||t&&!v.isFunction(t)&&t};r.duration=v.fx.off?0:typeof r.duration=="number"?r.duration:r.duration in v.fx.speeds?v.fx.speeds[r.duration]:v.fx.speeds._default;if(r.queue==null||r.queue===!0)r.queue="fx";return r.old=r.complete,r.complete=function(){v.isFunction(r.old)&&r.old.call(this),r.queue&&v.dequeue(this,r.queue)},r},v.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},v.timers=[],v.fx=Yn.prototype.init,v.fx.tick=function(){var e,n=v.timers,r=0;qn=v.now();for(;r<n.length;r++)e=n[r],!e()&&n[r]===e&&n.splice(r--,1);n.length||v.fx.stop(),qn=t},v.fx.timer=function(e){e()&&v.timers.push(e)&&!Rn&&(Rn=setInterval(v.fx.tick,v.fx.interval))},v.fx.interval=13,v.fx.stop=function(){clearInterval(Rn),Rn=null},v.fx.speeds={slow:600,fast:200,_default:400},v.fx.step={},v.expr&&v.expr.filters&&(v.expr.filters.animated=function(e){return v.grep(v.timers,function(t){return e===t.elem}).length});var er=/^(?:body|html)$/i;v.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){v.offset.setOffset(this,e,t)});var n,r,i,s,o,u,a,f={top:0,left:0},l=this[0],c=l&&l.ownerDocument;if(!c)return;return(r=c.body)===l?v.offset.bodyOffset(l):(n=c.documentElement,v.contains(n,l)?(typeof l.getBoundingClientRect!="undefined"&&(f=l.getBoundingClientRect()),i=tr(c),s=n.clientTop||r.clientTop||0,o=n.clientLeft||r.clientLeft||0,u=i.pageYOffset||n.scrollTop,a=i.pageXOffset||n.scrollLeft,{top:f.top+u-s,left:f.left+a-o}):f)},v.offset={bodyOffset:function(e){var t=e.offsetTop,n=e.offsetLeft;return v.support.doesNotIncludeMarginInBodyOffset&&(t+=parseFloat(v.css(e,"marginTop"))||0,n+=parseFloat(v.css(e,"marginLeft"))||0),{top:t,left:n}},setOffset:function(e,t,n){var r=v.css(e,"position");r==="static"&&(e.style.position="relative");var i=v(e),s=i.offset(),o=v.css(e,"top"),u=v.css(e,"left"),a=(r==="absolute"||r==="fixed")&&v.inArray("auto",[o,u])>-1,f={},l={},c,h;a?(l=i.position(),c=l.top,h=l.left):(c=parseFloat(o)||0,h=parseFloat(u)||0),v.isFunction(t)&&(t=t.call(e,n,s)),t.top!=null&&(f.top=t.top-s.top+c),t.left!=null&&(f.left=t.left-s.left+h),"using"in t?t.using.call(e,f):i.css(f)}},v.fn.extend({position:function(){if(!this[0])return;var e=this[0],t=this.offsetParent(),n=this.offset(),r=er.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(v.css(e,"marginTop"))||0,n.left-=parseFloat(v.css(e,"marginLeft"))||0,r.top+=parseFloat(v.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(v.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||i.body;while(e&&!er.test(e.nodeName)&&v.css(e,"position")==="static")e=e.offsetParent;return e||i.body})}}),v.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);v.fn[e]=function(i){return v.access(this,function(e,i,s){var o=tr(e);if(s===t)return o?n in o?o[n]:o.document.documentElement[i]:e[i];o?o.scrollTo(r?v(o).scrollLeft():s,r?s:v(o).scrollTop()):e[i]=s},e,i,arguments.length,null)}}),v.each({Height:"height",Width:"width"},function(e,n){v.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){v.fn[i]=function(i,s){var o=arguments.length&&(r||typeof i!="boolean"),u=r||(i===!0||s===!0?"margin":"border");return v.access(this,function(n,r,i){var s;return v.isWindow(n)?n.document.documentElement["client"+e]:n.nodeType===9?(s=n.documentElement,Math.max(n.body["scroll"+e],s["scroll"+e],n.body["offset"+e],s["offset"+e],s["client"+e])):i===t?v.css(n,r,i,u):v.style(n,r,i,u)},n,o?i:t,o,null)}})}),e.jQuery=e.$=v,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return v})})(window);
app/native/containers/AppContainer.native.js
Nakan4u/pokemons-finder
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { StyleSheet, View } from 'react-native'; import { Route } from 'react-router-native'; import Header from './Header.native'; import { ActionCreators } from '../../actions'; import routes from '../routes.config.js'; import RouteWithSubRoutes from '../../helpers.js'; import stylesGlobal from '../styles.general.css.js'; const styles = StyleSheet.create(stylesGlobal); class AppContainer extends React.Component { render () { return ( <View style={styles['.appContainer']}> <Header /> {routes.map((route, i) => <RouteWithSubRoutes key={i} {...route} /> )} </View> ); } } function mapDispatchToProps (dispatch) { return bindActionCreators(ActionCreators, dispatch); } export default connect(state => ({}), mapDispatchToProps)(AppContainer);
src/components/Comments.js
Iktwo/readable
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import * as Constants from '../utils/constants'; import * as Styles from '../utils/styles'; import SortOptions from './SortOptions'; class Comments extends Component { static filterComments(comments, displayDeleted) { if (!displayDeleted && comments) { return comments.filter((comment) => (!comment.deleted)); } else { return comments || []; } } render() { const { comments, sortMode, displayDeleted, upVoteComment, downVoteComment, sortComments, onSubmitForm, editComment, deleteComment } = this.props; return ( <div className="mt-2"> <SortOptions sortContent={(sortBy) => { sortComments(sortBy) }}/> { Comments.filterComments(comments, displayDeleted || false).sort((c1, c2) => { switch (sortMode) { case Constants.SORT_BY_SCORE: default: return c1.voteScore < c2.voteScore ? 1 : -1; case Constants.SORT_BY_NEWEST: return c1.timestamp < c2.timestamp ? 1 : -1; } }).map((comment) => ( <div className="row" key={comment.id}> <div className="col-sm-4 col-md-2 d-flex flex-column text-truncate align-self-center"> <a style={{...Styles.mainText}} className="d-flex align-self-center" href="#up" onClick={() => { upVoteComment(comment.id) }} > <i className="material-icons">keyboard_arrow_up</i> </a> <p className="mb-0 text-truncate" style={{...Styles.mainText, ...Styles.centeredText}}>{comment.voteScore}</p> <a style={{...Styles.mainText}} className="d-flex align-self-center" href="#down" onClick={() => { downVoteComment(comment.id) }} > <i className="material-icons">keyboard_arrow_down</i> </a> </div> <div className="card mt-2 col-sm-8 col-md-10"> <div className="card-body"> <p className="card-text">{comment.body}</p> <h6 className="card-subtitle mb-2 text-muted">By <a href="#!">{` ${comment.author}`}</a> </h6> <p className="card-text"> <small className="text-muted">{`${new Date(comment.timestamp).toString()}`}</small> </p> <a href="#edit" className="card-link btn btn-outline-warning" onClick={ () => { editComment(comment) } }> Edit </a> <a href="#delete" className="card-link btn btn-outline-danger" onClick={ () => { deleteComment(comment) } }> Delete </a> </div> </div> </div> ) ) } <form onSubmit={(e) => { e.preventDefault(); onSubmitForm({ body: this.body.value, author: this.author.value || 'Anon' }) }}> <div className="form-group"> <label htmlFor="body">Content</label> <textarea type="text" className="form-control" id="body" placeholder="Content" rows={3} required ref={(body) => this.body = body}/> </div> <div className="form-group"> <label htmlFor="author">Author</label> <input type="text" className="form-control" id="author" placeholder="Author" ref={(author) => this.author = author}/> </div> <button type="submit" className="btn btn-primary">Add comment</button> </form> </div> ); } } Comments.propTypes = { comments: PropTypes.array.isRequired, sortMode: PropTypes.string.isRequired, upVoteComment: PropTypes.func.isRequired, downVoteComment: PropTypes.func.isRequired, editComment: PropTypes.func.isRequired, deleteComment: PropTypes.func.isRequired, sortComments: PropTypes.func.isRequired, onSubmitForm: PropTypes.func.isRequired, displayDeleted: PropTypes.bool }; export default Comments;
packages/core/src/components/Calendar/DayRangePicker/DayRangePicker.js
appearhere/bloom
// @flow import React from 'react'; import keyMirror from 'key-mirror'; import momentPropTypes from 'react-moment-proptypes'; import noop from '../../../utils/noop'; import DayPicker from '../DayPicker/DayPicker'; import { defaultDayState } from '../DayPicker/DayPickerItem'; export const SELECT_DATE = keyMirror({ START: null, END: null, }); export const dayInRange = ( day: momentPropTypes.momentObj, startDate: momentPropTypes.momentObj, endDate: momentPropTypes.momentObj, ) => { if (!day) return false; const isEqualToStart = day.isSame(startDate, 'day'); const isEqualToEnd = day.isSame(endDate, 'day'); const isAfterStart = day.isAfter(startDate, 'day'); const isBeforeEnd = day.isBefore(endDate, 'day'); const isEqualToOrAfterStart = isEqualToStart || isAfterStart; const isEqualToOrBeforeEnd = isEqualToEnd || isBeforeEnd; if (!startDate && isEqualToEnd) return true; if (!endDate && isEqualToStart) return true; return isEqualToOrAfterStart && isEqualToOrBeforeEnd; }; const defaultIsDisabledDay = () => false; type Props = { startDate: momentPropTypes.momentObj, endDate: momentPropTypes.momentObj, selectDate: SELECT_DATE.START | SELECT_DATE.END, onInteraction: Function, onMonthChange: Function, isDisabled: Function, }; type State = { endHighlight: momentPropTypes.momentObj, }; export default class DayRangePicker extends React.Component<Props, State> { static defaultProps = { startDate: null, endDate: null, selectDate: SELECT_DATE.START, onInteraction: noop, onMonthChange: noop, isDisabled: defaultIsDisabledDay, }; state = { endHighlight: null, }; getDayState = (day: momentPropTypes.momentObj) => { const { startDate, endDate, isDisabled } = this.props; const { endHighlight } = this.state; if (!day) return defaultDayState; return { isDisabled: isDisabled(day), isSelected: dayInRange(day, startDate, endDate), isFirstSelected: day.isSame(startDate, 'day') || (startDate && !endDate) || (!startDate && endDate), isLastSelected: day.isSame(endDate, 'day') || (startDate && !endDate) || (!startDate && endDate), isHighlighted: dayInRange(day, startDate, endHighlight), isFirstHighlighted: day.isSame(startDate, 'day'), isLastHighlighted: day.isSame(endHighlight, 'day'), }; }; handleInteraction = (e: SyntheticKeyboardEvent<>, date: momentPropTypes.momentObj) => { const { startDate, endDate, selectDate, onInteraction } = this.props; if (selectDate === SELECT_DATE.START) { if (date.isAfter(endDate, 'day')) { onInteraction(e, date, null); } else { onInteraction(e, date, endDate); } } else if (selectDate === SELECT_DATE.END) { if ( (startDate && endDate && date.isSame(endDate, 'day')) || (startDate && date.isBefore(startDate, 'day')) ) { onInteraction(e, date, null); } else { onInteraction(e, startDate, date); } } }; handleHighlight = (e: SyntheticKeyboardEvent<>, date: momentPropTypes.momentObj) => { this.setState((currentState, props) => { if (props.startDate && props.endDate) { return { endHighlight: null, }; } if (props.startDate && !props.endDate) { return { endHighlight: date, }; } return null; }); }; render() { const { startDate: _startDate, endDate: _endDate, onMonthChange, ...rest } = this.props; return ( <DayPicker {...(rest: any)} dayProps={{ getDayState: this.getDayState, onHighlight: this.handleHighlight, }} onInteraction={this.handleInteraction} onMonthChange={onMonthChange} /> ); } }
frontend/src/Components/Page/Header/MovieSearchResult.js
Radarr/Radarr
import PropTypes from 'prop-types'; import React from 'react'; import Label from 'Components/Label'; import { kinds } from 'Helpers/Props'; import MoviePoster from 'Movie/MoviePoster'; import styles from './MovieSearchResult.css'; function MovieSearchResult(props) { const { match, title, year, images, alternateTitles, tags } = props; let alternateTitle = null; let tag = null; if (match.key === 'alternateTitles.title') { alternateTitle = alternateTitles[match.refIndex]; } else if (match.key === 'tags.label') { tag = tags[match.refIndex]; } return ( <div className={styles.result}> <MoviePoster className={styles.poster} images={images} size={250} lazy={false} overflow={true} /> <div className={styles.titles}> <div className={styles.title}> {title} { year > 0 ? `(${year})` : ''} </div> { alternateTitle ? <div className={styles.alternateTitle}> {alternateTitle.title} </div> : null } { tag ? <div className={styles.tagContainer}> <Label key={tag.id} kind={kinds.INFO} > {tag.label} </Label> </div> : null } </div> </div> ); } MovieSearchResult.propTypes = { title: PropTypes.string.isRequired, year: PropTypes.number.isRequired, images: PropTypes.arrayOf(PropTypes.object).isRequired, alternateTitles: PropTypes.arrayOf(PropTypes.object).isRequired, tags: PropTypes.arrayOf(PropTypes.object).isRequired, match: PropTypes.object.isRequired }; export default MovieSearchResult;
public/src/demo.js
codelegant/react-action
/** * Author: CodeLai * Email: [email protected] * DateTime: 2016/7/15 16:58 */ import '../css/product.css'; import React from 'react'; import ReactDOM from 'react-dom'; import Component from './demo/SpreadAttributes'; import Avatar from './demo/Avatar'; import CustomOl from './demo/MulitipleComponents'; import { PropValid, TransferProp } from './demo/ReusableComponents'; import TransferringProps from './demo/TransferringProps'; import MoreAboutRefs from './demo/MoreAboutRefs'; import { TodoList } from './demo/Animation'; import UserGist from './demo/InitialAjax'; import Todos from './demo/ExposeComponentFunctions'; /** * id 获取元素简便方法 * @param id */ const getById = id=>document.getElementById(id); const props = {}; props.foo = 'lai'; props.bar = 'chuanfeng'; ReactDOM.render(<Component {...props} foo={'override'} />, getById('div_1')); /*ReactDOM.render(<Avatar username="[email protected]"/>, getById()('div_3'));*/ ReactDOM.render( <CustomOl results={[{ id: 1, text: 'First list' }, { id: 2, text: 'Second list' }]} />, getById('div_4')); const invalidData = [1, 2, 3]; ReactDOM.render( <PropValid invalidData={invalidData} span={<span> This is a span childre. </span>} name={<span>This is a name</span>} />, getById('div_5')); //Stateless Functions ReactDOM.render(<TransferProp title="Go to Baidu" href="https://baidu.com" />, getById('div_6')); ReactDOM.render( <TransferringProps checked name="laichuanfeng" tabIndex="2" title="Tranferring Props" data-food="good" onClick={console.log.bind(console)} />, getById('div_7')); ReactDOM.render(<MoreAboutRefs />, getById('div_7')); ReactDOM.render(<TodoList />, getById('div_8')); ReactDOM.render(<UserGist source="https://api.github.com/users/octocat/gists" />, getById('div_9')); ReactDOM.render(<Todos />,getById('div_10'));
src/RoomInfo.js
RobertMcCoy/CodeCollaborator
import React, { Component } from 'react'; import Users from './Users'; import './RoomInfo.css'; import Toggle from './Toggle.js'; class RoomInfo extends Component { constructor(props) { super(props); this.state = { roomId: this.props.roomId, collaborators: this.props.collaborators, currentMode: this.props.currentMode, lineWrapping: this.props.lineWrapping } } componentWillReceiveProps(newProps) { this.setState({ collaborators: newProps.collaborators, currentMode: newProps.currentMode, lineWrapping: newProps.lineWrapping }); } render() { return ( <div className="room-info"> <Users collaborators={this.state.collaborators} /> <hr/> <div className="new-selection"> <h1 className="whiteText">Current Selection</h1> <select value={this.state.currentMode} onChange={this.props.modeChange}> <option value="javascript">JavaScript</option> <option value="htmlmixed">HTML</option> </select> <button>Confirm Choice</button> <hr /> <div className="whiteText">Text Wrap</div> <Toggle lineWrapCallback={this.props.lineWrapCallback} /> </div> </div> ); } } export default RoomInfo;
modules/IndexRoute.js
jdelight/react-router
import React from 'react'; import invariant from 'invariant'; import { createRouteFromReactElement } from './RouteUtils'; import { component, components, falsy } from './PropTypes'; var { bool, func } = React.PropTypes; /** * An <IndexRoute> is used to specify its parent's <Route indexRoute> in * a JSX route config. */ var IndexRoute = React.createClass({ statics: { createRouteFromReactElement(element, parentRoute) { if (parentRoute) { parentRoute.indexRoute = createRouteFromReactElement(element); } else { warning( false, 'An <IndexRoute> does not make sense at the root of your route config' ); } } }, propTypes: { path: falsy, ignoreScrollBehavior: bool, component, components, getComponents: func }, render() { invariant( false, '<IndexRoute> elements are for router configuration only and should not be rendered' ); } }); export default IndexRoute;
src/render.js
sphinxominator/councils-feathers
import 'isomorphic-fetch' import React from 'react' import { StaticRouter } from 'react-router-dom' import { Provider } from 'react-redux' import { ServerStyleSheet } from 'styled-components' import { createStore, combineReducers, applyMiddleware, compose } from 'redux' import { ApolloClient, createNetworkInterface, ApolloProvider, renderToStringWithData } from 'react-apollo' import { groups as groupsReducer, auth as authReducer, auth0 as auth0Reducer } from './app/reducers' import App from './app/App' import html from './html' let assets = {} if (process.env.RAZZLE_ASSETS_MANIFEST) { assets = require(process.env.RAZZLE_ASSETS_MANIFEST) } else { assets = require('../build/assets.json') } export default async (req, res) => { const client = new ApolloClient({ ssrMode: true, networkInterface: createNetworkInterface({ uri: process.env.RAZZLE_URI + '/graphql', opts: { credentials: 'same-origin', headers: req.headers } }) }) const store = createStore( combineReducers({ apollo: client.reducer(), groups: groupsReducer, auth: authReducer, auth0: auth0Reducer }), { // initial state auth: req.user }, compose(applyMiddleware(client.middleware())) ) const sheet = new ServerStyleSheet() const app = sheet.collectStyles( <Provider store={store}> <ApolloProvider client={client} store={store}> <StaticRouter location={req.url} context={{}}> <App /> </StaticRouter> </ApolloProvider> </Provider> ) const content = await renderToStringWithData(app) const initialState = JSON.stringify({ auth: req.user, apollo: client.getInitialState() }).replace(/</g, '\\u003c') const js = (assets && assets.client && assets.client.js) || '' const styles = sheet.getStyleTags() const markup = html(js, styles, content, initialState) res.status(200) res.send(markup) res.end() }
packages/material-ui-icons/src/Forward5TwoTone.js
Kagami/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M17.95 13c0 3.31-2.69 6-6 6s-6-2.69-6-6 2.69-6 6-6v4l5-5-5-5v4c-4.42 0-8 3.58-8 8s3.58 8 8 8 8-3.58 8-8h-2z" /><path d="M12.43 15.15c-.05.07-.11.13-.18.17s-.17.06-.27.06c-.17 0-.31-.05-.42-.15s-.17-.24-.19-.41h-.84c.01.2.05.37.13.53s.19.28.32.39.29.19.46.24.35.08.53.08c.24 0 .46-.04.64-.12s.33-.18.45-.31.21-.28.27-.45.09-.35.09-.54c0-.22-.03-.43-.09-.6s-.14-.33-.25-.45-.25-.22-.41-.28-.34-.1-.55-.1c-.07 0-.14.01-.2.02s-.13.02-.18.04-.1.03-.15.05-.08.04-.11.05l.11-.92h1.7v-.71H10.9l-.25 2.17.67.17c.03-.03.06-.06.1-.09s.07-.05.12-.07.1-.04.15-.05.13-.02.2-.02c.12 0 .22.02.3.05s.16.09.21.15.1.14.13.24.04.19.04.31-.01.22-.03.31-.06.17-.11.24z" /></React.Fragment> , 'Forward5TwoTone');
app/components/specificComponents/SocialBanner/SocialIcon.js
romainquellec/cuistot
import React from 'react'; const { PropTypes } = React; const SocialIcon = (props) => ( <svg width="32" height="32" viewBox={props.viewBox}> <path d={props.icon} /> </svg> ); SocialIcon.propTypes = { icon: PropTypes.string.isRequired, }; export default SocialIcon;
ajax/libs/abcjs/3.1.1/abcjs_plugin.user.js
maruilian11/cdnjs
// ==UserScript== // @name abcjs // @namespace http://code.google.com/p/abcjs // @description This searches any page you load for ABC-formatted music and inserts the standard notation for it. // ==/UserScript== // Because the js files are concatenated, these variables will be visible to the ones in abcjs_plugin user script. // However, this file is not included in the regular abcjs_plugin, so that won't be affected. var abcjs_is_user_script = true; var scripts = document.getElementsByTagName('script'); var abcjs_plugin_autostart = true; for (var i = 0; i < scripts.length; i++) { var src = scripts[i].src; if (src.indexOf('abcjs') > 0) abcjs_plugin_autostart = false; } /*! jQuery v1.11.3 | (c) 2005, 2015 jQuery Foundation, Inc. | jquery.org/license */ !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.3",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)+1>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b="length"in a&&a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N=M.replace("w","w#"),O="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+N+"))|)"+L+"*\\]",P=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+O+")*)|.*)\\)|)",Q=new RegExp(L+"+","g"),R=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),S=new RegExp("^"+L+"*,"+L+"*"),T=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),U=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),V=new RegExp(P),W=new RegExp("^"+N+"$"),X={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+O),PSEUDO:new RegExp("^"+P),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,aa=/[+~]/,ba=/'|\\/g,ca=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),da=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ea=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(fa){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],k=b.nodeType,"string"!=typeof a||!a||1!==k&&9!==k&&11!==k)return d;if(!e&&p){if(11!==k&&(f=_.exec(a)))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return H.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName)return H.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=1!==k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(ba,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+ra(o[l]);w=aa.test(a)&&pa(b.parentNode)||b,x=o.join(",")}if(x)try{return H.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function pa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=g.documentElement,e=g.defaultView,e&&e!==e.top&&(e.addEventListener?e.addEventListener("unload",ea,!1):e.attachEvent&&e.attachEvent("onunload",ea)),p=!f(g),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(g.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(g.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!g.getElementsByName||!g.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(g.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\f]' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){var b=g.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",P)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===g||a.ownerDocument===v&&t(v,a)?-1:b===g||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,h=[a],i=[b];if(!e||!f)return a===g?-1:b===g?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?la(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},g):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ca,da),a[3]=(a[3]||a[4]||a[5]||"").replace(ca,da),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ca,da).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(Q," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(ca,da),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return W.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(ca,da).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:oa(function(){return[0]}),last:oa(function(a,b){return[b-1]}),eq:oa(function(a,b,c){return[0>c?c+b:c]}),even:oa(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:oa(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:oa(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:oa(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=ma(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=na(b);function qa(){}qa.prototype=d.filters=d.pseudos,d.setFilters=new qa,g=ga.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?ga.error(a):z(a,i).slice(0)};function ra(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function sa(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function ta(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ua(a,b,c){for(var d=0,e=b.length;e>d;d++)ga(a,b[d],c);return c}function va(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function wa(a,b,c,d,e,f){return d&&!d[u]&&(d=wa(d)),e&&!e[u]&&(e=wa(e,f)),ia(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ua(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:va(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=va(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=va(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function xa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=sa(function(a){return a===b},h,!0),l=sa(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[sa(ta(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return wa(i>1&&ta(m),i>1&&ra(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&xa(a.slice(i,e)),f>e&&xa(a=a.slice(e)),f>e&&ra(a))}m.push(c)}return ta(m)}function ya(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=F.call(i));s=va(s)}H.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&ga.uniqueSort(i)}return k&&(w=v,j=t),r};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=xa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,ya(e,d)),f.selector=a}return f},i=ga.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ca,da),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ca,da),aa.test(j[0].type)&&pa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&ra(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,aa.test(a)&&pa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ja(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1; return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function aa(){return!0}function ba(){return!1}function ca(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},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(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==ca()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===ca()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?aa:ba):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:ba,isPropagationStopped:ba,isImmediatePropagationStopped:ba,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=aa,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=aa,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=aa,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=ba;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=ba),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function da(a){var b=ea.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var ea="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fa=/ jQuery\d+="(?:null|\d+)"/g,ga=new RegExp("<(?:"+ea+")[\\s/>]","i"),ha=/^\s+/,ia=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,ja=/<([\w:]+)/,ka=/<tbody/i,la=/<|&#?\w+;/,ma=/<(?:script|style|link)/i,na=/checked\s*(?:[^=]|=\s*.checked.)/i,oa=/^$|\/(?:java|ecma)script/i,pa=/^true\/(.*)/,qa=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,ra={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>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sa=da(y),ta=sa.appendChild(y.createElement("div"));ra.optgroup=ra.option,ra.tbody=ra.tfoot=ra.colgroup=ra.caption=ra.thead,ra.th=ra.td;function ua(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ua(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function va(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wa(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xa(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function ya(a){var b=pa.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function za(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Aa(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Ba(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xa(b).text=a.text,ya(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!ga.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ta.innerHTML=a.outerHTML,ta.removeChild(f=ta.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ua(f),h=ua(a),g=0;null!=(e=h[g]);++g)d[g]&&Ba(e,d[g]);if(b)if(c)for(h=h||ua(a),d=d||ua(f),g=0;null!=(e=h[g]);g++)Aa(e,d[g]);else Aa(a,f);return d=ua(f,"script"),d.length>0&&za(d,!i&&ua(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=da(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(la.test(f)){h=h||o.appendChild(b.createElement("div")),i=(ja.exec(f)||["",""])[1].toLowerCase(),l=ra[i]||ra._default,h.innerHTML=l[1]+f.replace(ia,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&ha.test(f)&&p.push(b.createTextNode(ha.exec(f)[0])),!k.tbody){f="table"!==i||ka.test(f)?"<table>"!==l[1]||ka.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ua(p,"input"),va),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ua(o.appendChild(f),"script"),g&&za(h),c)){e=0;while(f=h[e++])oa.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wa(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wa(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ua(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&za(ua(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ua(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fa,""):void 0;if(!("string"!=typeof a||ma.test(a)||!k.htmlSerialize&&ga.test(a)||!k.leadingWhitespace&&ha.test(a)||ra[(ja.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ia,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ua(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ua(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&na.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ua(i,"script"),xa),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ua(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,ya),j=0;f>j;j++)d=g[j],oa.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qa,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Ca,Da={};function Ea(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fa(a){var b=y,c=Da[a];return c||(c=Ea(a,b),"none"!==c&&c||(Ca=(Ca||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Ca[0].contentWindow||Ca[0].contentDocument).document,b.write(),b.close(),c=Ea(a,b),Ca.detach()),Da[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="-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",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Ga=/^margin/,Ha=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ia,Ja,Ka=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ia=function(b){return b.ownerDocument.defaultView.opener?b.ownerDocument.defaultView.getComputedStyle(b,null):a.getComputedStyle(b,null)},Ja=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ia(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Ha.test(g)&&Ga.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ia=function(a){return a.currentStyle},Ja=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ia(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ha.test(g)&&!Ka.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function La(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.style.cssText="-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",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight),b.removeChild(i)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Ma=/alpha\([^)]*\)/i,Na=/opacity\s*=\s*([^)]*)/,Oa=/^(none|table(?!-c[ea]).+)/,Pa=new RegExp("^("+S+")(.*)$","i"),Qa=new RegExp("^([+-])=("+S+")","i"),Ra={position:"absolute",visibility:"hidden",display:"block"},Sa={letterSpacing:"0",fontWeight:"400"},Ta=["Webkit","O","Moz","ms"];function Ua(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ta.length;while(e--)if(b=Ta[e]+c,b in a)return b;return d}function Va(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fa(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wa(a,b,c){var d=Pa.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xa(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Ya(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ia(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Ja(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ha.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xa(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Ja(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ua(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qa.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ua(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Ja(a,b,d)),"normal"===f&&b in Sa&&(f=Sa[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Oa.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Ra,function(){return Ya(a,b,d)}):Ya(a,b,d):void 0},set:function(a,c,d){var e=d&&Ia(a);return Wa(a,c,d?Xa(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Na.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Ma,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Ma.test(f)?f.replace(Ma,e):f+" "+e)}}),m.cssHooks.marginRight=La(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Ja,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Ga.test(a)||(m.cssHooks[a+b].set=Wa)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ia(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Va(this,!0)},hide:function(){return Va(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Za(a,b,c,d,e){ return new Za.prototype.init(a,b,c,d,e)}m.Tween=Za,Za.prototype={constructor:Za,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px")},cur:function(){var a=Za.propHooks[this.prop];return a&&a.get?a.get(this):Za.propHooks._default.get(this)},run:function(a){var b,c=Za.propHooks[this.prop];return this.options.duration?this.pos=b=m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Za.propHooks._default.set(this),this}},Za.prototype.init.prototype=Za.prototype,Za.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Za.propHooks.scrollTop=Za.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Za.prototype.init,m.fx.step={};var $a,_a,ab=/^(?:toggle|show|hide)$/,bb=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cb=/queueHooks$/,db=[ib],eb={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bb.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bb.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fb(){return setTimeout(function(){$a=void 0}),$a=m.now()}function gb(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hb(a,b,c){for(var d,e=(eb[b]||[]).concat(eb["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ib(a,b,c){var d,e,f,g,h,i,j,l,n=this,o={},p=a.style,q=a.nodeType&&U(a),r=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,n.always(function(){n.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=m.css(a,"display"),l="none"===j?m._data(a,"olddisplay")||Fa(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fa(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",k.shrinkWrapBlocks()||n.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ab.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(o))"inline"===("none"===j?Fa(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=m._data(a,"fxshow",{}),f&&(r.hidden=!q),q?m(a).show():n.done(function(){m(a).hide()}),n.done(function(){var b;m._removeData(a,"fxshow");for(b in o)m.style(a,b,o[b])});for(d in o)g=hb(q?r[d]:0,d,n),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jb(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kb(a,b,c){var d,e,f=0,g=db.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$a||fb(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$a||fb(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jb(k,j.opts.specialEasing);g>f;f++)if(d=db[f].call(j,a,k,j.opts))return d;return m.map(k,hb,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kb,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],eb[c]=eb[c]||[],eb[c].unshift(b)},prefilter:function(a,b){b?db.unshift(a):db.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kb(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cb.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gb(b,!0),a,d,e)}}),m.each({slideDown:gb("show"),slideUp:gb("hide"),slideToggle:gb("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($a=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$a=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_a||(_a=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_a),_a=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lb=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lb,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mb,nb,ob=m.expr.attrHandle,pb=/^(?:checked|selected)$/i,qb=k.getSetAttribute,rb=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nb:mb)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rb&&qb||!pb.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qb?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nb={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rb&&qb||!pb.test(c)?a.setAttribute(!qb&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=ob[b]||m.find.attr;ob[b]=rb&&qb||!pb.test(b)?function(a,b,d){var e,f;return d||(f=ob[b],ob[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,ob[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rb&&qb||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mb&&mb.set(a,b,c)}}),qb||(mb={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},ob.id=ob.name=ob.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mb.set},m.attrHooks.contenteditable={set:function(a,b,c){mb.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sb=/^(?:input|select|textarea|button|object)$/i,tb=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sb.test(a.nodeName)||tb.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var ub=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ub," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ub," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(ub," ").indexOf(b)>=0)return!0;return!1}}),m.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(a,b){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vb=m.now(),wb=/\?/,xb=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xb,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yb,zb,Ab=/#.*$/,Bb=/([?&])_=[^&]*/,Cb=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Db=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Eb=/^(?:GET|HEAD)$/,Fb=/^\/\//,Gb=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hb={},Ib={},Jb="*/".concat("*");try{zb=location.href}catch(Kb){zb=y.createElement("a"),zb.href="",zb=zb.href}yb=Gb.exec(zb.toLowerCase())||[];function Lb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mb(a,b,c,d){var e={},f=a===Ib;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nb(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Ob(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pb(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zb,type:"GET",isLocal:Db.test(yb[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jb,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"},converters:{"* text":String,"text html":!0,"text json":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nb(Nb(a,m.ajaxSettings),b):Nb(m.ajaxSettings,a)},ajaxPrefilter:Lb(Hb),ajaxTransport:Lb(Ib),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cb.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zb)+"").replace(Ab,"").replace(Fb,yb[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gb.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yb[1]&&c[2]===yb[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yb[3]||("http:"===yb[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mb(Hb,k,b,v),2===t)return v;h=m.event&&k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Eb.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wb.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bb.test(e)?e.replace(Bb,"$1_="+vb++):e+(wb.test(e)?"&":"?")+"_="+vb++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jb+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mb(Ib,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Ob(k,v,c)),u=Pb(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qb=/%20/g,Rb=/\[\]$/,Sb=/\r?\n/g,Tb=/^(?:submit|button|image|reset|file)$/i,Ub=/^(?:input|select|textarea|keygen)/i;function Vb(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rb.test(a)?d(a,e):Vb(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vb(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vb(c,a[c],b,e);return d.join("&").replace(Qb,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Ub.test(this.nodeName)&&!Tb.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sb,"\r\n")}}):{name:b.name,value:c.replace(Sb,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zb()||$b()}:Zb;var Wb=0,Xb={},Yb=m.ajaxSettings.xhr();a.attachEvent&&a.attachEvent("onunload",function(){for(var a in Xb)Xb[a](void 0,!0)}),k.cors=!!Yb&&"withCredentials"in Yb,Yb=k.ajax=!!Yb,Yb&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wb;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xb[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xb[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zb(){try{return new a.XMLHttpRequest}catch(b){}}function $b(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _b=[],ac=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_b.pop()||m.expando+"_"+vb++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ac.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ac.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ac,"$1"+e):b.jsonp!==!1&&(b.url+=(wb.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_b.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bc=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bc)return bc.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cc=a.document.documentElement;function dc(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dc(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cc;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cc})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dc(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=La(k.pixelPosition,function(a,c){return c?(c=Ja(a,b),Ha.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ec=a.jQuery,fc=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fc),b&&a.jQuery===m&&(a.jQuery=ec),m},typeof b===K&&(a.jQuery=a.$=m),m}); /*! abcjs v3.1.1 Copyright © 2009-2016 Paul Rosen and Gregory Dyke (http://abcjs.net) */ function calcHorizontalSpacing(isLastLine,stretchLast,targetWidth,lineWidth,spacing,spacingUnits,minSpace){if(isLastLine&&lineWidth/targetWidth<.66&&!stretchLast)return null;if(Math.abs(targetWidth-lineWidth)<2)return null;var relSpace=spacingUnits*spacing,constSpace=lineWidth-relSpace;return spacingUnits>0?(spacing=(targetWidth-constSpace)/spacingUnits,spacing*minSpace>50&&(spacing=50/minSpace),spacing):null}function centerWholeRests(voices){for(var i=0;i<voices.length;i++)for(var voice=voices[i],j=1;j<voice.children.length-1;j++){var absElem=voice.children[j];if(absElem.abcelem.rest&&"whole"===absElem.abcelem.rest.type){var before=voice.children[j-1],after=voice.children[j+1],midpoint=(after.x-before.x)/2+before.x;absElem.x=midpoint-absElem.w/2;for(var k=0;k<absElem.children.length;k++)absElem.children[k].x=absElem.x}}}function kernSymbols(lastSymbol,thisSymbol,lastSymbolWidth){var width=lastSymbolWidth;return"f"===lastSymbol&&"f"===thisSymbol&&(width=2*width/3),"p"===lastSymbol&&"p"===thisSymbol&&(width=5*width/6),"f"===lastSymbol&&"z"===thisSymbol&&(width=5*width/8),width}!function(glob){var current_event,stop,version="0.4.2",has="hasOwnProperty",separator=/[\.\/]/,wildcard="*",fun=function(){},numsort=function(a,b){return a-b},events={n:{}},eve=function(name,scope){name=String(name);var l,oldstop=stop,args=Array.prototype.slice.call(arguments,2),listeners=eve.listeners(name),z=0,indexed=[],queue={},out=[],ce=current_event;current_event=name,stop=0;for(var i=0,ii=listeners.length;i<ii;i++)"zIndex"in listeners[i]&&(indexed.push(listeners[i].zIndex),listeners[i].zIndex<0&&(queue[listeners[i].zIndex]=listeners[i]));for(indexed.sort(numsort);indexed[z]<0;)if(l=queue[indexed[z++]],out.push(l.apply(scope,args)),stop)return stop=oldstop,out;for(i=0;i<ii;i++)if(l=listeners[i],"zIndex"in l)if(l.zIndex==indexed[z]){if(out.push(l.apply(scope,args)),stop)break;do if(z++,l=queue[indexed[z]],l&&out.push(l.apply(scope,args)),stop)break;while(l)}else queue[l.zIndex]=l;else if(out.push(l.apply(scope,args)),stop)break;return stop=oldstop,current_event=ce,out.length?out:null};eve._events=events,eve.listeners=function(name){var item,items,k,i,ii,j,jj,nes,names=name.split(separator),e=events,es=[e],out=[];for(i=0,ii=names.length;i<ii;i++){for(nes=[],j=0,jj=es.length;j<jj;j++)for(e=es[j].n,items=[e[names[i]],e[wildcard]],k=2;k--;)item=items[k],item&&(nes.push(item),out=out.concat(item.f||[]));es=nes}return out},eve.on=function(name,f){if(name=String(name),"function"!=typeof f)return function(){};for(var names=name.split(separator),e=events,i=0,ii=names.length;i<ii;i++)e=e.n,e=e.hasOwnProperty(names[i])&&e[names[i]]||(e[names[i]]={n:{}});for(e.f=e.f||[],i=0,ii=e.f.length;i<ii;i++)if(e.f[i]==f)return fun;return e.f.push(f),function(zIndex){+zIndex==+zIndex&&(f.zIndex=+zIndex)}},eve.f=function(event){var attrs=[].slice.call(arguments,1);return function(){eve.apply(null,[event,null].concat(attrs).concat([].slice.call(arguments,0)))}},eve.stop=function(){stop=1},eve.nt=function(subname){return subname?new RegExp("(?:\\.|\\/|^)"+subname+"(?:\\.|\\/|$)").test(current_event):current_event},eve.nts=function(){return current_event.split(separator)},eve.off=eve.unbind=function(name,f){if(!name)return void(eve._events=events={n:{}});var e,key,splice,i,ii,j,jj,names=name.split(separator),cur=[events];for(i=0,ii=names.length;i<ii;i++)for(j=0;j<cur.length;j+=splice.length-2){if(splice=[j,1],e=cur[j].n,names[i]!=wildcard)e[names[i]]&&splice.push(e[names[i]]);else for(key in e)e[has](key)&&splice.push(e[key]);cur.splice.apply(cur,splice)}for(i=0,ii=cur.length;i<ii;i++)for(e=cur[i];e.n;){if(f){if(e.f){for(j=0,jj=e.f.length;j<jj;j++)if(e.f[j]==f){e.f.splice(j,1);break}!e.f.length&&delete e.f}for(key in e.n)if(e.n[has](key)&&e.n[key].f){var funcs=e.n[key].f;for(j=0,jj=funcs.length;j<jj;j++)if(funcs[j]==f){funcs.splice(j,1);break}!funcs.length&&delete e.n[key].f}}else{delete e.f;for(key in e.n)e.n[has](key)&&e.n[key].f&&delete e.n[key].f}e=e.n}},eve.once=function(name,f){var f2=function(){return eve.unbind(name,f2),f.apply(this,arguments)};return eve.on(name,f2)},eve.version=version,eve.toString=function(){return"You are running Eve "+version},"undefined"!=typeof module&&module.exports?module.exports=eve:"undefined"!=typeof define?define("eve",[],function(){return eve}):glob.eve=eve}(this),function(glob,factory){"function"==typeof define&&define.amd?define(["eve"],function(eve){return factory(glob,eve)}):factory(glob,glob.eve)}(this,function(window,eve){function R(first){if(R.is(first,"function"))return loaded?first():eve.on("raphael.DOMload",first);if(R.is(first,array))return R._engine.create[apply](R,first.splice(0,3+R.is(first[0],nu))).add(first);var args=Array.prototype.slice.call(arguments,0);if(R.is(args[args.length-1],"function")){var f=args.pop();return loaded?f.call(R._engine.create[apply](R,args)):eve.on("raphael.DOMload",function(){f.call(R._engine.create[apply](R,args))})}return R._engine.create[apply](R,arguments)}function clone(obj){if("function"==typeof obj||Object(obj)!==obj)return obj;var res=new obj.constructor;for(var key in obj)obj[has](key)&&(res[key]=clone(obj[key]));return res}function repush(array,item){for(var i=0,ii=array.length;i<ii;i++)if(array[i]===item)return array.push(array.splice(i,1)[0])}function cacher(f,scope,postprocessor){function newf(){var arg=Array.prototype.slice.call(arguments,0),args=arg.join("␀"),cache=newf.cache=newf.cache||{},count=newf.count=newf.count||[];return cache[has](args)?(repush(count,args),postprocessor?postprocessor(cache[args]):cache[args]):(count.length>=1e3&&delete cache[count.shift()],count.push(args),cache[args]=f[apply](scope,arg),postprocessor?postprocessor(cache[args]):cache[args])}return newf}function clrToString(){return this.hex}function catmullRom2bezier(crp,z){for(var d=[],i=0,iLen=crp.length;iLen-2*!z>i;i+=2){var p=[{x:+crp[i-2],y:+crp[i-1]},{x:+crp[i],y:+crp[i+1]},{x:+crp[i+2],y:+crp[i+3]},{x:+crp[i+4],y:+crp[i+5]}];z?i?iLen-4==i?p[3]={x:+crp[0],y:+crp[1]}:iLen-2==i&&(p[2]={x:+crp[0],y:+crp[1]},p[3]={x:+crp[2],y:+crp[3]}):p[0]={x:+crp[iLen-2],y:+crp[iLen-1]}:iLen-4==i?p[3]=p[2]:i||(p[0]={x:+crp[i],y:+crp[i+1]}),d.push(["C",(-p[0].x+6*p[1].x+p[2].x)/6,(-p[0].y+6*p[1].y+p[2].y)/6,(p[1].x+6*p[2].x-p[3].x)/6,(p[1].y+6*p[2].y-p[3].y)/6,p[2].x,p[2].y])}return d}function base3(t,p1,p2,p3,p4){var t1=-3*p1+9*p2-9*p3+3*p4,t2=t*t1+6*p1-12*p2+6*p3;return t*t2-3*p1+3*p2}function bezlen(x1,y1,x2,y2,x3,y3,x4,y4,z){null==z&&(z=1),z=z>1?1:z<0?0:z;for(var z2=z/2,n=12,Tvalues=[-.1252,.1252,-.3678,.3678,-.5873,.5873,-.7699,.7699,-.9041,.9041,-.9816,.9816],Cvalues=[.2491,.2491,.2335,.2335,.2032,.2032,.1601,.1601,.1069,.1069,.0472,.0472],sum=0,i=0;i<n;i++){var ct=z2*Tvalues[i]+z2,xbase=base3(ct,x1,x2,x3,x4),ybase=base3(ct,y1,y2,y3,y4),comb=xbase*xbase+ybase*ybase;sum+=Cvalues[i]*math.sqrt(comb)}return z2*sum}function getTatLen(x1,y1,x2,y2,x3,y3,x4,y4,ll){if(!(ll<0||bezlen(x1,y1,x2,y2,x3,y3,x4,y4)<ll)){var l,t=1,step=t/2,t2=t-step,e=.01;for(l=bezlen(x1,y1,x2,y2,x3,y3,x4,y4,t2);abs(l-ll)>e;)step/=2,t2+=(l<ll?1:-1)*step,l=bezlen(x1,y1,x2,y2,x3,y3,x4,y4,t2);return t2}}function intersect(x1,y1,x2,y2,x3,y3,x4,y4){if(!(mmax(x1,x2)<mmin(x3,x4)||mmin(x1,x2)>mmax(x3,x4)||mmax(y1,y2)<mmin(y3,y4)||mmin(y1,y2)>mmax(y3,y4))){var nx=(x1*y2-y1*x2)*(x3-x4)-(x1-x2)*(x3*y4-y3*x4),ny=(x1*y2-y1*x2)*(y3-y4)-(y1-y2)*(x3*y4-y3*x4),denominator=(x1-x2)*(y3-y4)-(y1-y2)*(x3-x4);if(denominator){var px=nx/denominator,py=ny/denominator,px2=+px.toFixed(2),py2=+py.toFixed(2);if(!(px2<+mmin(x1,x2).toFixed(2)||px2>+mmax(x1,x2).toFixed(2)||px2<+mmin(x3,x4).toFixed(2)||px2>+mmax(x3,x4).toFixed(2)||py2<+mmin(y1,y2).toFixed(2)||py2>+mmax(y1,y2).toFixed(2)||py2<+mmin(y3,y4).toFixed(2)||py2>+mmax(y3,y4).toFixed(2)))return{x:px,y:py}}}}function interHelper(bez1,bez2,justCount){var bbox1=R.bezierBBox(bez1),bbox2=R.bezierBBox(bez2);if(!R.isBBoxIntersect(bbox1,bbox2))return justCount?0:[];for(var l1=bezlen.apply(0,bez1),l2=bezlen.apply(0,bez2),n1=mmax(~~(l1/5),1),n2=mmax(~~(l2/5),1),dots1=[],dots2=[],xy={},res=justCount?0:[],i=0;i<n1+1;i++){var p=R.findDotsAtSegment.apply(R,bez1.concat(i/n1));dots1.push({x:p.x,y:p.y,t:i/n1})}for(i=0;i<n2+1;i++)p=R.findDotsAtSegment.apply(R,bez2.concat(i/n2)),dots2.push({x:p.x,y:p.y,t:i/n2});for(i=0;i<n1;i++)for(var j=0;j<n2;j++){var di=dots1[i],di1=dots1[i+1],dj=dots2[j],dj1=dots2[j+1],ci=abs(di1.x-di.x)<.001?"y":"x",cj=abs(dj1.x-dj.x)<.001?"y":"x",is=intersect(di.x,di.y,di1.x,di1.y,dj.x,dj.y,dj1.x,dj1.y);if(is){if(xy[is.x.toFixed(4)]==is.y.toFixed(4))continue;xy[is.x.toFixed(4)]=is.y.toFixed(4);var t1=di.t+abs((is[ci]-di[ci])/(di1[ci]-di[ci]))*(di1.t-di.t),t2=dj.t+abs((is[cj]-dj[cj])/(dj1[cj]-dj[cj]))*(dj1.t-dj.t);t1>=0&&t1<=1.001&&t2>=0&&t2<=1.001&&(justCount?res++:res.push({x:is.x,y:is.y,t1:mmin(t1,1),t2:mmin(t2,1)}))}}return res}function interPathHelper(path1,path2,justCount){path1=R._path2curve(path1),path2=R._path2curve(path2);for(var x1,y1,x2,y2,x1m,y1m,x2m,y2m,bez1,bez2,res=justCount?0:[],i=0,ii=path1.length;i<ii;i++){var pi=path1[i];if("M"==pi[0])x1=x1m=pi[1],y1=y1m=pi[2];else{"C"==pi[0]?(bez1=[x1,y1].concat(pi.slice(1)),x1=bez1[6],y1=bez1[7]):(bez1=[x1,y1,x1,y1,x1m,y1m,x1m,y1m],x1=x1m,y1=y1m);for(var j=0,jj=path2.length;j<jj;j++){var pj=path2[j];if("M"==pj[0])x2=x2m=pj[1],y2=y2m=pj[2];else{"C"==pj[0]?(bez2=[x2,y2].concat(pj.slice(1)),x2=bez2[6],y2=bez2[7]):(bez2=[x2,y2,x2,y2,x2m,y2m,x2m,y2m],x2=x2m,y2=y2m);var intr=interHelper(bez1,bez2,justCount);if(justCount)res+=intr;else{for(var k=0,kk=intr.length;k<kk;k++)intr[k].segment1=i,intr[k].segment2=j,intr[k].bez1=bez1,intr[k].bez2=bez2;res=res.concat(intr)}}}}}return res}function Matrix(a,b,c,d,e,f){null!=a?(this.a=+a,this.b=+b,this.c=+c,this.d=+d,this.e=+e,this.f=+f):(this.a=1,this.b=0,this.c=0,this.d=1,this.e=0,this.f=0)}function x_y_w_h(){return this.x+S+this.y+S+this.width+" × "+this.height}function CubicBezierAtTime(t,p1x,p1y,p2x,p2y,duration){function sampleCurveX(t){return((ax*t+bx)*t+cx)*t}function solve(x,epsilon){var t=solveCurveX(x,epsilon);return((ay*t+by)*t+cy)*t}function solveCurveX(x,epsilon){var t0,t1,t2,x2,d2,i;for(t2=x,i=0;i<8;i++){if(x2=sampleCurveX(t2)-x,abs(x2)<epsilon)return t2;if(d2=(3*ax*t2+2*bx)*t2+cx,abs(d2)<1e-6)break;t2-=x2/d2}if(t0=0,t1=1,t2=x,t2<t0)return t0;if(t2>t1)return t1;for(;t0<t1;){if(x2=sampleCurveX(t2),abs(x2-x)<epsilon)return t2;x>x2?t0=t2:t1=t2,t2=(t1-t0)/2+t0}return t2}var cx=3*p1x,bx=3*(p2x-p1x)-cx,ax=1-cx-bx,cy=3*p1y,by=3*(p2y-p1y)-cy,ay=1-cy-by;return solve(t,1/(200*duration))}function Animation(anim,ms){var percents=[],newAnim={};if(this.ms=ms,this.times=1,anim){for(var attr in anim)anim[has](attr)&&(newAnim[toFloat(attr)]=anim[attr],percents.push(toFloat(attr)));percents.sort(sortByNumber)}this.anim=newAnim,this.top=percents[percents.length-1],this.percents=percents}function runAnimation(anim,element,percent,status,totalOrigin,times){percent=toFloat(percent);var params,isInAnim,isInAnimSet,next,prev,timestamp,ms=anim.ms,from={},to={},diff={};if(status)for(i=0,ii=animationElements.length;i<ii;i++){var e=animationElements[i];if(e.el.id==element.id&&e.anim==anim){e.percent!=percent?(animationElements.splice(i,1),isInAnimSet=1):isInAnim=e,element.attr(e.totalOrigin);break}}else status=+to;for(var i=0,ii=anim.percents.length;i<ii;i++){if(anim.percents[i]==percent||anim.percents[i]>status*anim.top){percent=anim.percents[i],prev=anim.percents[i-1]||0,ms=ms/anim.top*(percent-prev),next=anim.percents[i+1],params=anim.anim[percent];break}status&&element.attr(anim.anim[anim.percents[i]])}if(params){if(isInAnim)isInAnim.initstatus=status,isInAnim.start=new Date-isInAnim.ms*status;else{for(var attr in params)if(params[has](attr)&&(availableAnimAttrs[has](attr)||element.paper.customAttributes[has](attr)))switch(from[attr]=element.attr(attr),null==from[attr]&&(from[attr]=availableAttrs[attr]),to[attr]=params[attr],availableAnimAttrs[attr]){case nu:diff[attr]=(to[attr]-from[attr])/ms;break;case"colour":from[attr]=R.getRGB(from[attr]);var toColour=R.getRGB(to[attr]);diff[attr]={r:(toColour.r-from[attr].r)/ms,g:(toColour.g-from[attr].g)/ms,b:(toColour.b-from[attr].b)/ms};break;case"path":var pathes=path2curve(from[attr],to[attr]),toPath=pathes[1];for(from[attr]=pathes[0],diff[attr]=[],i=0,ii=from[attr].length;i<ii;i++){diff[attr][i]=[0];for(var j=1,jj=from[attr][i].length;j<jj;j++)diff[attr][i][j]=(toPath[i][j]-from[attr][i][j])/ms}break;case"transform":var _=element._,eq=equaliseTransform(_[attr],to[attr]);if(eq)for(from[attr]=eq.from,to[attr]=eq.to,diff[attr]=[],diff[attr].real=!0,i=0,ii=from[attr].length;i<ii;i++)for(diff[attr][i]=[from[attr][i][0]],j=1,jj=from[attr][i].length;j<jj;j++)diff[attr][i][j]=(to[attr][i][j]-from[attr][i][j])/ms;else{var m=element.matrix||new Matrix,to2={_:{transform:_.transform},getBBox:function(){return element.getBBox(1)}};from[attr]=[m.a,m.b,m.c,m.d,m.e,m.f],extractTransform(to2,to[attr]),to[attr]=to2._.transform,diff[attr]=[(to2.matrix.a-m.a)/ms,(to2.matrix.b-m.b)/ms,(to2.matrix.c-m.c)/ms,(to2.matrix.d-m.d)/ms,(to2.matrix.e-m.e)/ms,(to2.matrix.f-m.f)/ms]}break;case"csv":var values=Str(params[attr])[split](separator),from2=Str(from[attr])[split](separator);if("clip-rect"==attr)for(from[attr]=from2,diff[attr]=[],i=from2.length;i--;)diff[attr][i]=(values[i]-from[attr][i])/ms;to[attr]=values;break;default:for(values=[][concat](params[attr]),from2=[][concat](from[attr]),diff[attr]=[],i=element.paper.customAttributes[attr].length;i--;)diff[attr][i]=((values[i]||0)-(from2[i]||0))/ms}var easing=params.easing,easyeasy=R.easing_formulas[easing];if(!easyeasy)if(easyeasy=Str(easing).match(bezierrg),easyeasy&&5==easyeasy.length){var curve=easyeasy;easyeasy=function(t){return CubicBezierAtTime(t,+curve[1],+curve[2],+curve[3],+curve[4],ms)}}else easyeasy=pipe;if(timestamp=params.start||anim.start||+new Date,e={anim:anim,percent:percent,timestamp:timestamp,start:timestamp+(anim.del||0),status:0,initstatus:status||0,stop:!1,ms:ms,easing:easyeasy,from:from,diff:diff,to:to,el:element,callback:params.callback,prev:prev,next:next,repeat:times||anim.times,origin:element.attr(),totalOrigin:totalOrigin},animationElements.push(e),status&&!isInAnim&&!isInAnimSet&&(e.stop=!0,e.start=new Date-ms*status,1==animationElements.length))return animation();isInAnimSet&&(e.start=new Date-e.ms*status),1==animationElements.length&&requestAnimFrame(animation)}eve("raphael.anim.start."+element.id,element,anim)}}function stopAnimation(paper){for(var i=0;i<animationElements.length;i++)animationElements[i].el.paper==paper&&animationElements.splice(i--,1)}R.version="2.1.2",R.eve=eve;var loaded,paperproto,separator=/[, ]+/,elements={circle:1,rect:1,path:1,ellipse:1,text:1,image:1},formatrg=/\{(\d+)\}/g,has="hasOwnProperty",g={doc:document,win:window},oldRaphael={was:Object.prototype[has].call(g.win,"Raphael"),is:g.win.Raphael},Paper=function(){this.ca=this.customAttributes={}},apply="apply",concat="concat",supportsTouch="ontouchstart"in g.win||g.win.DocumentTouch&&g.doc instanceof DocumentTouch,E="",S=" ",Str=String,split="split",events="click dblclick mousedown mousemove mouseout mouseover mouseup touchstart touchmove touchend touchcancel"[split](S),touchMap={mousedown:"touchstart",mousemove:"touchmove",mouseup:"touchend"},lowerCase=Str.prototype.toLowerCase,math=Math,mmax=math.max,mmin=math.min,abs=math.abs,pow=math.pow,PI=math.PI,nu="number",string="string",array="array",objectToString=Object.prototype.toString,colourRegExp=(R._ISURL=/^url\(['"]?([^\)]+?)['"]?\)$/i,/^\s*((#[a-f\d]{6})|(#[a-f\d]{3})|rgba?\(\s*([\d\.]+%?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+%?(?:\s*,\s*[\d\.]+%?)?)\s*\)|hsba?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\)|hsla?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\))\s*$/i),isnan={NaN:1,Infinity:1,"-Infinity":1},bezierrg=/^(?:cubic-)?bezier\(([^,]+),([^,]+),([^,]+),([^\)]+)\)/,round=math.round,toFloat=parseFloat,toInt=parseInt,upperCase=Str.prototype.toUpperCase,availableAttrs=R._availableAttrs={"arrow-end":"none","arrow-start":"none",blur:0,"clip-rect":"0 0 1e9 1e9",cursor:"default",cx:0,cy:0,fill:"#fff","fill-opacity":1,font:'10px "Arial"',"font-family":'"Arial"',"font-size":"10","font-style":"normal","font-weight":400,gradient:0,height:0,href:"http://raphaeljs.com/","letter-spacing":0,opacity:1,path:"M0,0",r:0,rx:0,ry:0,src:"",stroke:"#000","stroke-dasharray":"","stroke-linecap":"butt","stroke-linejoin":"butt","stroke-miterlimit":0,"stroke-opacity":1,"stroke-width":1,target:"_blank","text-anchor":"middle",title:"Raphael",transform:"",width:0,x:0,y:0},availableAnimAttrs=R._availableAnimAttrs={blur:nu,"clip-rect":"csv",cx:nu,cy:nu,fill:"colour","fill-opacity":nu,"font-size":nu,height:nu,opacity:nu,path:"path",r:nu,rx:nu,ry:nu,stroke:"colour","stroke-opacity":nu,"stroke-width":nu,transform:"transform",width:nu,x:nu,y:nu},commaSpaces=/[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*/,hsrg={hs:1,rg:1},p2s=/,?([achlmqrstvxz]),?/gi,pathCommand=/([achlmrqstvz])[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*)+)/gi,tCommand=/([rstm])[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*)+)/gi,pathValues=/(-?\d*\.?\d*(?:e[\-+]?\d+)?)[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*/gi,eldata=(R._radial_gradient=/^r(?:\(([^,]+?)[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*([^\)]+?)\))?/,{}),sortByNumber=function(a,b){return toFloat(a)-toFloat(b)},fun=function(){},pipe=function(x){return x},rectPath=R._rectPath=function(x,y,w,h,r){return r?[["M",x+r,y],["l",w-2*r,0],["a",r,r,0,0,1,r,r],["l",0,h-2*r],["a",r,r,0,0,1,-r,r],["l",2*r-w,0],["a",r,r,0,0,1,-r,-r],["l",0,2*r-h],["a",r,r,0,0,1,r,-r],["z"]]:[["M",x,y],["l",w,0],["l",0,h],["l",-w,0],["z"]]},ellipsePath=function(x,y,rx,ry){return null==ry&&(ry=rx),[["M",x,y],["m",0,-ry],["a",rx,ry,0,1,1,0,2*ry],["a",rx,ry,0,1,1,0,-2*ry],["z"]]},getPath=R._getPath={path:function(el){return el.attr("path")},circle:function(el){var a=el.attrs;return ellipsePath(a.cx,a.cy,a.r)},ellipse:function(el){var a=el.attrs;return ellipsePath(a.cx,a.cy,a.rx,a.ry)},rect:function(el){var a=el.attrs;return rectPath(a.x,a.y,a.width,a.height,a.r)},image:function(el){var a=el.attrs;return rectPath(a.x,a.y,a.width,a.height)},text:function(el){var bbox=el._getBBox();return rectPath(bbox.x,bbox.y,bbox.width,bbox.height)},set:function(el){var bbox=el._getBBox();return rectPath(bbox.x,bbox.y,bbox.width,bbox.height)}},mapPath=R.mapPath=function(path,matrix){if(!matrix)return path;var x,y,i,j,ii,jj,pathi;for(path=path2curve(path),i=0,ii=path.length;i<ii;i++)for(pathi=path[i],j=1,jj=pathi.length;j<jj;j+=2)x=matrix.x(pathi[j],pathi[j+1]),y=matrix.y(pathi[j],pathi[j+1]),pathi[j]=x,pathi[j+1]=y;return path};if(R._g=g,R.type=g.win.SVGAngle||g.doc.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1")?"SVG":"VML","VML"==R.type){var b,d=g.doc.createElement("div");if(d.innerHTML='<v:shape adj="1"/>',b=d.firstChild,b.style.behavior="url(#default#VML)",!b||"object"!=typeof b.adj)return R.type=E;d=null}R.svg=!(R.vml="VML"==R.type),R._Paper=Paper,R.fn=paperproto=Paper.prototype=R.prototype,R._id=0,R._oid=0,R.is=function(o,type){return type=lowerCase.call(type),"finite"==type?!isnan[has](+o):"array"==type?o instanceof Array:"null"==type&&null===o||type==typeof o&&null!==o||"object"==type&&o===Object(o)||"array"==type&&Array.isArray&&Array.isArray(o)||objectToString.call(o).slice(8,-1).toLowerCase()==type},R.angle=function(x1,y1,x2,y2,x3,y3){if(null==x3){var x=x1-x2,y=y1-y2;return x||y?(180+180*math.atan2(-y,-x)/PI+360)%360:0}return R.angle(x1,y1,x3,y3)-R.angle(x2,y2,x3,y3)},R.rad=function(deg){return deg%360*PI/180},R.deg=function(rad){return 180*rad/PI%360},R.snapTo=function(values,value,tolerance){if(tolerance=R.is(tolerance,"finite")?tolerance:10,R.is(values,array)){for(var i=values.length;i--;)if(abs(values[i]-value)<=tolerance)return values[i]}else{values=+values;var rem=value%values;if(rem<tolerance)return value-rem;if(rem>values-tolerance)return value-rem+values}return value};R.createUUID=function(uuidRegEx,uuidReplacer){return function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(uuidRegEx,uuidReplacer).toUpperCase()}}(/[xy]/g,function(c){var r=16*math.random()|0,v="x"==c?r:3&r|8;return v.toString(16)});R.setWindow=function(newwin){eve("raphael.setWindow",R,g.win,newwin),g.win=newwin,g.doc=g.win.document,R._engine.initWin&&R._engine.initWin(g.win)};var toHex=function(color){if(R.vml){var bod,trim=/^\s+|\s+$/g;try{var docum=new ActiveXObject("htmlfile");docum.write("<body>"),docum.close(),bod=docum.body}catch(e){bod=createPopup().document.body}var range=bod.createTextRange();toHex=cacher(function(color){try{bod.style.color=Str(color).replace(trim,E);var value=range.queryCommandValue("ForeColor");return value=(255&value)<<16|65280&value|(16711680&value)>>>16,"#"+("000000"+value.toString(16)).slice(-6)}catch(e){return"none"}})}else{var i=g.doc.createElement("i");i.title="Raphaël Colour Picker",i.style.display="none",g.doc.body.appendChild(i),toHex=cacher(function(color){return i.style.color=color,g.doc.defaultView.getComputedStyle(i,E).getPropertyValue("color")})}return toHex(color)},hsbtoString=function(){return"hsb("+[this.h,this.s,this.b]+")"},hsltoString=function(){return"hsl("+[this.h,this.s,this.l]+")"},rgbtoString=function(){return this.hex},prepareRGB=function(r,g,b){if(null==g&&R.is(r,"object")&&"r"in r&&"g"in r&&"b"in r&&(b=r.b,g=r.g,r=r.r),null==g&&R.is(r,string)){var clr=R.getRGB(r);r=clr.r,g=clr.g,b=clr.b}return(r>1||g>1||b>1)&&(r/=255,g/=255,b/=255),[r,g,b]},packageRGB=function(r,g,b,o){r*=255,g*=255,b*=255;var rgb={r:r,g:g,b:b,hex:R.rgb(r,g,b),toString:rgbtoString};return R.is(o,"finite")&&(rgb.opacity=o),rgb};R.color=function(clr){var rgb;return R.is(clr,"object")&&"h"in clr&&"s"in clr&&"b"in clr?(rgb=R.hsb2rgb(clr),clr.r=rgb.r,clr.g=rgb.g,clr.b=rgb.b,clr.hex=rgb.hex):R.is(clr,"object")&&"h"in clr&&"s"in clr&&"l"in clr?(rgb=R.hsl2rgb(clr),clr.r=rgb.r,clr.g=rgb.g,clr.b=rgb.b,clr.hex=rgb.hex):(R.is(clr,"string")&&(clr=R.getRGB(clr)),R.is(clr,"object")&&"r"in clr&&"g"in clr&&"b"in clr?(rgb=R.rgb2hsl(clr),clr.h=rgb.h,clr.s=rgb.s,clr.l=rgb.l,rgb=R.rgb2hsb(clr),clr.v=rgb.b):(clr={hex:"none"},clr.r=clr.g=clr.b=clr.h=clr.s=clr.v=clr.l=-1)),clr.toString=rgbtoString,clr},R.hsb2rgb=function(h,s,v,o){this.is(h,"object")&&"h"in h&&"s"in h&&"b"in h&&(v=h.b,s=h.s,h=h.h,o=h.o),h*=360;var R,G,B,X,C;return h=h%360/60,C=v*s,X=C*(1-abs(h%2-1)),R=G=B=v-C,h=~~h,R+=[C,X,0,0,X,C][h],G+=[X,C,C,X,0,0][h],B+=[0,0,X,C,C,X][h],packageRGB(R,G,B,o)},R.hsl2rgb=function(h,s,l,o){this.is(h,"object")&&"h"in h&&"s"in h&&"l"in h&&(l=h.l,s=h.s,h=h.h),(h>1||s>1||l>1)&&(h/=360,s/=100,l/=100),h*=360;var R,G,B,X,C;return h=h%360/60,C=2*s*(l<.5?l:1-l),X=C*(1-abs(h%2-1)),R=G=B=l-C/2,h=~~h,R+=[C,X,0,0,X,C][h],G+=[X,C,C,X,0,0][h],B+=[0,0,X,C,C,X][h],packageRGB(R,G,B,o)},R.rgb2hsb=function(r,g,b){b=prepareRGB(r,g,b),r=b[0],g=b[1],b=b[2];var H,S,V,C;return V=mmax(r,g,b),C=V-mmin(r,g,b),H=0==C?null:V==r?(g-b)/C:V==g?(b-r)/C+2:(r-g)/C+4,H=(H+360)%6*60/360,S=0==C?0:C/V,{h:H,s:S,b:V,toString:hsbtoString}},R.rgb2hsl=function(r,g,b){b=prepareRGB(r,g,b),r=b[0],g=b[1],b=b[2];var H,S,L,M,m,C;return M=mmax(r,g,b),m=mmin(r,g,b),C=M-m,H=0==C?null:M==r?(g-b)/C:M==g?(b-r)/C+2:(r-g)/C+4,H=(H+360)%6*60/360,L=(M+m)/2,S=0==C?0:L<.5?C/(2*L):C/(2-2*L),{h:H,s:S,l:L,toString:hsltoString}},R._path2string=function(){return this.join(",").replace(p2s,"$1")};R._preload=function(src,f){var img=g.doc.createElement("img");img.style.cssText="position:absolute;left:-9999em;top:-9999em",img.onload=function(){f.call(this),this.onload=null,g.doc.body.removeChild(this)},img.onerror=function(){g.doc.body.removeChild(this)},g.doc.body.appendChild(img),img.src=src};R.getRGB=cacher(function(colour){if(!colour||(colour=Str(colour)).indexOf("-")+1)return{r:-1,g:-1,b:-1,hex:"none",error:1,toString:clrToString};if("none"==colour)return{r:-1,g:-1,b:-1,hex:"none",toString:clrToString};!(hsrg[has](colour.toLowerCase().substring(0,2))||"#"==colour.charAt())&&(colour=toHex(colour));var red,green,blue,opacity,t,values,rgb=colour.match(colourRegExp);return rgb?(rgb[2]&&(blue=toInt(rgb[2].substring(5),16),green=toInt(rgb[2].substring(3,5),16),red=toInt(rgb[2].substring(1,3),16)),rgb[3]&&(blue=toInt((t=rgb[3].charAt(3))+t,16),green=toInt((t=rgb[3].charAt(2))+t,16),red=toInt((t=rgb[3].charAt(1))+t,16)),rgb[4]&&(values=rgb[4][split](commaSpaces),red=toFloat(values[0]),"%"==values[0].slice(-1)&&(red*=2.55),green=toFloat(values[1]),"%"==values[1].slice(-1)&&(green*=2.55),blue=toFloat(values[2]),"%"==values[2].slice(-1)&&(blue*=2.55),"rgba"==rgb[1].toLowerCase().slice(0,4)&&(opacity=toFloat(values[3])),values[3]&&"%"==values[3].slice(-1)&&(opacity/=100)),rgb[5]?(values=rgb[5][split](commaSpaces),red=toFloat(values[0]),"%"==values[0].slice(-1)&&(red*=2.55),green=toFloat(values[1]),"%"==values[1].slice(-1)&&(green*=2.55),blue=toFloat(values[2]),"%"==values[2].slice(-1)&&(blue*=2.55),("deg"==values[0].slice(-3)||"°"==values[0].slice(-1))&&(red/=360),"hsba"==rgb[1].toLowerCase().slice(0,4)&&(opacity=toFloat(values[3])),values[3]&&"%"==values[3].slice(-1)&&(opacity/=100),R.hsb2rgb(red,green,blue,opacity)):rgb[6]?(values=rgb[6][split](commaSpaces),red=toFloat(values[0]),"%"==values[0].slice(-1)&&(red*=2.55),green=toFloat(values[1]),"%"==values[1].slice(-1)&&(green*=2.55),blue=toFloat(values[2]),"%"==values[2].slice(-1)&&(blue*=2.55),("deg"==values[0].slice(-3)||"°"==values[0].slice(-1))&&(red/=360),"hsla"==rgb[1].toLowerCase().slice(0,4)&&(opacity=toFloat(values[3])),values[3]&&"%"==values[3].slice(-1)&&(opacity/=100),R.hsl2rgb(red,green,blue,opacity)):(rgb={r:red,g:green,b:blue,toString:clrToString},rgb.hex="#"+(16777216|blue|green<<8|red<<16).toString(16).slice(1),R.is(opacity,"finite")&&(rgb.opacity=opacity),rgb)):{r:-1,g:-1,b:-1,hex:"none",error:1,toString:clrToString}},R),R.hsb=cacher(function(h,s,b){return R.hsb2rgb(h,s,b).hex}),R.hsl=cacher(function(h,s,l){return R.hsl2rgb(h,s,l).hex}),R.rgb=cacher(function(r,g,b){return"#"+(16777216|b|g<<8|r<<16).toString(16).slice(1)}),R.getColor=function(value){var start=this.getColor.start=this.getColor.start||{h:0,s:1,b:value||.75},rgb=this.hsb2rgb(start.h,start.s,start.b);return start.h+=.075,start.h>1&&(start.h=0,start.s-=.2,start.s<=0&&(this.getColor.start={h:0,s:1,b:start.b})),rgb.hex},R.getColor.reset=function(){delete this.start},R.parsePathString=function(pathString){if(!pathString)return null;var pth=paths(pathString);if(pth.arr)return pathClone(pth.arr);var paramCounts={a:7,c:6,h:1,l:2,m:2,r:4,q:4,s:4,t:2,v:1,z:0},data=[];return R.is(pathString,array)&&R.is(pathString[0],array)&&(data=pathClone(pathString)),data.length||Str(pathString).replace(pathCommand,function(a,b,c){var params=[],name=b.toLowerCase();if(c.replace(pathValues,function(a,b){b&&params.push(+b)}),"m"==name&&params.length>2&&(data.push([b][concat](params.splice(0,2))),name="l",b="m"==b?"l":"L"),"r"==name)data.push([b][concat](params));else for(;params.length>=paramCounts[name]&&(data.push([b][concat](params.splice(0,paramCounts[name]))),paramCounts[name]););}),data.toString=R._path2string,pth.arr=pathClone(data),data},R.parseTransformString=cacher(function(TString){if(!TString)return null;var data=[];return R.is(TString,array)&&R.is(TString[0],array)&&(data=pathClone(TString)),data.length||Str(TString).replace(tCommand,function(a,b,c){var params=[];lowerCase.call(b);c.replace(pathValues,function(a,b){b&&params.push(+b)}),data.push([b][concat](params))}),data.toString=R._path2string,data});var paths=function(ps){var p=paths.ps=paths.ps||{};return p[ps]?p[ps].sleep=1:p[ps]={sleep:1},setTimeout(function(){for(var key in p)p[has](key)&&key!=ps&&(p[key].sleep--,!p[key].sleep&&delete p[key])}),p[ps]};R.findDotsAtSegment=function(p1x,p1y,c1x,c1y,c2x,c2y,p2x,p2y,t){var t1=1-t,t13=pow(t1,3),t12=pow(t1,2),t2=t*t,t3=t2*t,x=t13*p1x+3*t12*t*c1x+3*t1*t*t*c2x+t3*p2x,y=t13*p1y+3*t12*t*c1y+3*t1*t*t*c2y+t3*p2y,mx=p1x+2*t*(c1x-p1x)+t2*(c2x-2*c1x+p1x),my=p1y+2*t*(c1y-p1y)+t2*(c2y-2*c1y+p1y),nx=c1x+2*t*(c2x-c1x)+t2*(p2x-2*c2x+c1x),ny=c1y+2*t*(c2y-c1y)+t2*(p2y-2*c2y+c1y),ax=t1*p1x+t*c1x,ay=t1*p1y+t*c1y,cx=t1*c2x+t*p2x,cy=t1*c2y+t*p2y,alpha=90-180*math.atan2(mx-nx,my-ny)/PI;return(mx>nx||my<ny)&&(alpha+=180),{x:x,y:y,m:{x:mx,y:my},n:{x:nx,y:ny},start:{x:ax,y:ay},end:{x:cx,y:cy},alpha:alpha}},R.bezierBBox=function(p1x,p1y,c1x,c1y,c2x,c2y,p2x,p2y){R.is(p1x,"array")||(p1x=[p1x,p1y,c1x,c1y,c2x,c2y,p2x,p2y]);var bbox=curveDim.apply(null,p1x);return{x:bbox.min.x,y:bbox.min.y,x2:bbox.max.x,y2:bbox.max.y,width:bbox.max.x-bbox.min.x,height:bbox.max.y-bbox.min.y}},R.isPointInsideBBox=function(bbox,x,y){return x>=bbox.x&&x<=bbox.x2&&y>=bbox.y&&y<=bbox.y2},R.isBBoxIntersect=function(bbox1,bbox2){var i=R.isPointInsideBBox;return i(bbox2,bbox1.x,bbox1.y)||i(bbox2,bbox1.x2,bbox1.y)||i(bbox2,bbox1.x,bbox1.y2)||i(bbox2,bbox1.x2,bbox1.y2)||i(bbox1,bbox2.x,bbox2.y)||i(bbox1,bbox2.x2,bbox2.y)||i(bbox1,bbox2.x,bbox2.y2)||i(bbox1,bbox2.x2,bbox2.y2)||(bbox1.x<bbox2.x2&&bbox1.x>bbox2.x||bbox2.x<bbox1.x2&&bbox2.x>bbox1.x)&&(bbox1.y<bbox2.y2&&bbox1.y>bbox2.y||bbox2.y<bbox1.y2&&bbox2.y>bbox1.y)},R.pathIntersection=function(path1,path2){return interPathHelper(path1,path2)},R.pathIntersectionNumber=function(path1,path2){return interPathHelper(path1,path2,1)},R.isPointInsidePath=function(path,x,y){var bbox=R.pathBBox(path);return R.isPointInsideBBox(bbox,x,y)&&interPathHelper(path,[["M",x,y],["H",bbox.x2+10]],1)%2==1},R._removedFactory=function(methodname){return function(){eve("raphael.log",null,"Raphaël: you are calling to method “"+methodname+"” of removed object",methodname)}};var pathDimensions=R.pathBBox=function(path){var pth=paths(path);if(pth.bbox)return clone(pth.bbox);if(!path)return{x:0,y:0,width:0,height:0,x2:0,y2:0};path=path2curve(path);for(var p,x=0,y=0,X=[],Y=[],i=0,ii=path.length;i<ii;i++)if(p=path[i],"M"==p[0])x=p[1],y=p[2],X.push(x),Y.push(y);else{var dim=curveDim(x,y,p[1],p[2],p[3],p[4],p[5],p[6]);X=X[concat](dim.min.x,dim.max.x),Y=Y[concat](dim.min.y,dim.max.y),x=p[5],y=p[6]}var xmin=mmin[apply](0,X),ymin=mmin[apply](0,Y),xmax=mmax[apply](0,X),ymax=mmax[apply](0,Y),width=xmax-xmin,height=ymax-ymin,bb={x:xmin,y:ymin,x2:xmax,y2:ymax,width:width,height:height,cx:xmin+width/2,cy:ymin+height/2};return pth.bbox=clone(bb),bb},pathClone=function(pathArray){var res=clone(pathArray);return res.toString=R._path2string,res},pathToRelative=R._pathToRelative=function(pathArray){var pth=paths(pathArray);if(pth.rel)return pathClone(pth.rel);R.is(pathArray,array)&&R.is(pathArray&&pathArray[0],array)||(pathArray=R.parsePathString(pathArray)); var res=[],x=0,y=0,mx=0,my=0,start=0;"M"==pathArray[0][0]&&(x=pathArray[0][1],y=pathArray[0][2],mx=x,my=y,start++,res.push(["M",x,y]));for(var i=start,ii=pathArray.length;i<ii;i++){var r=res[i]=[],pa=pathArray[i];if(pa[0]!=lowerCase.call(pa[0]))switch(r[0]=lowerCase.call(pa[0]),r[0]){case"a":r[1]=pa[1],r[2]=pa[2],r[3]=pa[3],r[4]=pa[4],r[5]=pa[5],r[6]=+(pa[6]-x).toFixed(3),r[7]=+(pa[7]-y).toFixed(3);break;case"v":r[1]=+(pa[1]-y).toFixed(3);break;case"m":mx=pa[1],my=pa[2];default:for(var j=1,jj=pa.length;j<jj;j++)r[j]=+(pa[j]-(j%2?x:y)).toFixed(3)}else{r=res[i]=[],"m"==pa[0]&&(mx=pa[1]+x,my=pa[2]+y);for(var k=0,kk=pa.length;k<kk;k++)res[i][k]=pa[k]}var len=res[i].length;switch(res[i][0]){case"z":x=mx,y=my;break;case"h":x+=+res[i][len-1];break;case"v":y+=+res[i][len-1];break;default:x+=+res[i][len-2],y+=+res[i][len-1]}}return res.toString=R._path2string,pth.rel=pathClone(res),res},pathToAbsolute=R._pathToAbsolute=function(pathArray){var pth=paths(pathArray);if(pth.abs)return pathClone(pth.abs);if(R.is(pathArray,array)&&R.is(pathArray&&pathArray[0],array)||(pathArray=R.parsePathString(pathArray)),!pathArray||!pathArray.length)return[["M",0,0]];var res=[],x=0,y=0,mx=0,my=0,start=0;"M"==pathArray[0][0]&&(x=+pathArray[0][1],y=+pathArray[0][2],mx=x,my=y,start++,res[0]=["M",x,y]);for(var r,pa,crz=3==pathArray.length&&"M"==pathArray[0][0]&&"R"==pathArray[1][0].toUpperCase()&&"Z"==pathArray[2][0].toUpperCase(),i=start,ii=pathArray.length;i<ii;i++){if(res.push(r=[]),pa=pathArray[i],pa[0]!=upperCase.call(pa[0]))switch(r[0]=upperCase.call(pa[0]),r[0]){case"A":r[1]=pa[1],r[2]=pa[2],r[3]=pa[3],r[4]=pa[4],r[5]=pa[5],r[6]=+(pa[6]+x),r[7]=+(pa[7]+y);break;case"V":r[1]=+pa[1]+y;break;case"H":r[1]=+pa[1]+x;break;case"R":for(var dots=[x,y][concat](pa.slice(1)),j=2,jj=dots.length;j<jj;j++)dots[j]=+dots[j]+x,dots[++j]=+dots[j]+y;res.pop(),res=res[concat](catmullRom2bezier(dots,crz));break;case"M":mx=+pa[1]+x,my=+pa[2]+y;default:for(j=1,jj=pa.length;j<jj;j++)r[j]=+pa[j]+(j%2?x:y)}else if("R"==pa[0])dots=[x,y][concat](pa.slice(1)),res.pop(),res=res[concat](catmullRom2bezier(dots,crz)),r=["R"][concat](pa.slice(-2));else for(var k=0,kk=pa.length;k<kk;k++)r[k]=pa[k];switch(r[0]){case"Z":x=mx,y=my;break;case"H":x=r[1];break;case"V":y=r[1];break;case"M":mx=r[r.length-2],my=r[r.length-1];default:x=r[r.length-2],y=r[r.length-1]}}return res.toString=R._path2string,pth.abs=pathClone(res),res},l2c=function(x1,y1,x2,y2){return[x1,y1,x2,y2,x2,y2]},q2c=function(x1,y1,ax,ay,x2,y2){var _13=1/3,_23=2/3;return[_13*x1+_23*ax,_13*y1+_23*ay,_13*x2+_23*ax,_13*y2+_23*ay,x2,y2]},a2c=function(x1,y1,rx,ry,angle,large_arc_flag,sweep_flag,x2,y2,recursive){var xy,_120=120*PI/180,rad=PI/180*(+angle||0),res=[],rotate=cacher(function(x,y,rad){var X=x*math.cos(rad)-y*math.sin(rad),Y=x*math.sin(rad)+y*math.cos(rad);return{x:X,y:Y}});if(recursive)f1=recursive[0],f2=recursive[1],cx=recursive[2],cy=recursive[3];else{xy=rotate(x1,y1,-rad),x1=xy.x,y1=xy.y,xy=rotate(x2,y2,-rad),x2=xy.x,y2=xy.y;var x=(math.cos(PI/180*angle),math.sin(PI/180*angle),(x1-x2)/2),y=(y1-y2)/2,h=x*x/(rx*rx)+y*y/(ry*ry);h>1&&(h=math.sqrt(h),rx*=h,ry*=h);var rx2=rx*rx,ry2=ry*ry,k=(large_arc_flag==sweep_flag?-1:1)*math.sqrt(abs((rx2*ry2-rx2*y*y-ry2*x*x)/(rx2*y*y+ry2*x*x))),cx=k*rx*y/ry+(x1+x2)/2,cy=k*-ry*x/rx+(y1+y2)/2,f1=math.asin(((y1-cy)/ry).toFixed(9)),f2=math.asin(((y2-cy)/ry).toFixed(9));f1=x1<cx?PI-f1:f1,f2=x2<cx?PI-f2:f2,f1<0&&(f1=2*PI+f1),f2<0&&(f2=2*PI+f2),sweep_flag&&f1>f2&&(f1-=2*PI),!sweep_flag&&f2>f1&&(f2-=2*PI)}var df=f2-f1;if(abs(df)>_120){var f2old=f2,x2old=x2,y2old=y2;f2=f1+_120*(sweep_flag&&f2>f1?1:-1),x2=cx+rx*math.cos(f2),y2=cy+ry*math.sin(f2),res=a2c(x2,y2,rx,ry,angle,0,sweep_flag,x2old,y2old,[f2,f2old,cx,cy])}df=f2-f1;var c1=math.cos(f1),s1=math.sin(f1),c2=math.cos(f2),s2=math.sin(f2),t=math.tan(df/4),hx=4/3*rx*t,hy=4/3*ry*t,m1=[x1,y1],m2=[x1+hx*s1,y1-hy*c1],m3=[x2+hx*s2,y2-hy*c2],m4=[x2,y2];if(m2[0]=2*m1[0]-m2[0],m2[1]=2*m1[1]-m2[1],recursive)return[m2,m3,m4][concat](res);res=[m2,m3,m4][concat](res).join()[split](",");for(var newres=[],i=0,ii=res.length;i<ii;i++)newres[i]=i%2?rotate(res[i-1],res[i],rad).y:rotate(res[i],res[i+1],rad).x;return newres},findDotAtSegment=function(p1x,p1y,c1x,c1y,c2x,c2y,p2x,p2y,t){var t1=1-t;return{x:pow(t1,3)*p1x+3*pow(t1,2)*t*c1x+3*t1*t*t*c2x+pow(t,3)*p2x,y:pow(t1,3)*p1y+3*pow(t1,2)*t*c1y+3*t1*t*t*c2y+pow(t,3)*p2y}},curveDim=cacher(function(p1x,p1y,c1x,c1y,c2x,c2y,p2x,p2y){var dot,a=c2x-2*c1x+p1x-(p2x-2*c2x+c1x),b=2*(c1x-p1x)-2*(c2x-c1x),c=p1x-c1x,t1=(-b+math.sqrt(b*b-4*a*c))/2/a,t2=(-b-math.sqrt(b*b-4*a*c))/2/a,y=[p1y,p2y],x=[p1x,p2x];return abs(t1)>"1e12"&&(t1=.5),abs(t2)>"1e12"&&(t2=.5),t1>0&&t1<1&&(dot=findDotAtSegment(p1x,p1y,c1x,c1y,c2x,c2y,p2x,p2y,t1),x.push(dot.x),y.push(dot.y)),t2>0&&t2<1&&(dot=findDotAtSegment(p1x,p1y,c1x,c1y,c2x,c2y,p2x,p2y,t2),x.push(dot.x),y.push(dot.y)),a=c2y-2*c1y+p1y-(p2y-2*c2y+c1y),b=2*(c1y-p1y)-2*(c2y-c1y),c=p1y-c1y,t1=(-b+math.sqrt(b*b-4*a*c))/2/a,t2=(-b-math.sqrt(b*b-4*a*c))/2/a,abs(t1)>"1e12"&&(t1=.5),abs(t2)>"1e12"&&(t2=.5),t1>0&&t1<1&&(dot=findDotAtSegment(p1x,p1y,c1x,c1y,c2x,c2y,p2x,p2y,t1),x.push(dot.x),y.push(dot.y)),t2>0&&t2<1&&(dot=findDotAtSegment(p1x,p1y,c1x,c1y,c2x,c2y,p2x,p2y,t2),x.push(dot.x),y.push(dot.y)),{min:{x:mmin[apply](0,x),y:mmin[apply](0,y)},max:{x:mmax[apply](0,x),y:mmax[apply](0,y)}}}),path2curve=R._path2curve=cacher(function(path,path2){var pth=!path2&&paths(path);if(!path2&&pth.curve)return pathClone(pth.curve);for(var p=pathToAbsolute(path),p2=path2&&pathToAbsolute(path2),attrs={x:0,y:0,bx:0,by:0,X:0,Y:0,qx:null,qy:null},attrs2={x:0,y:0,bx:0,by:0,X:0,Y:0,qx:null,qy:null},processPath=(function(path,d,pcom){var nx,ny;if(!path)return["C",d.x,d.y,d.x,d.y,d.x,d.y];switch(!(path[0]in{T:1,Q:1})&&(d.qx=d.qy=null),path[0]){case"M":d.X=path[1],d.Y=path[2];break;case"A":path=["C"][concat](a2c[apply](0,[d.x,d.y][concat](path.slice(1))));break;case"S":"C"==pcom||"S"==pcom?(nx=2*d.x-d.bx,ny=2*d.y-d.by):(nx=d.x,ny=d.y),path=["C",nx,ny][concat](path.slice(1));break;case"T":"Q"==pcom||"T"==pcom?(d.qx=2*d.x-d.qx,d.qy=2*d.y-d.qy):(d.qx=d.x,d.qy=d.y),path=["C"][concat](q2c(d.x,d.y,d.qx,d.qy,path[1],path[2]));break;case"Q":d.qx=path[1],d.qy=path[2],path=["C"][concat](q2c(d.x,d.y,path[1],path[2],path[3],path[4]));break;case"L":path=["C"][concat](l2c(d.x,d.y,path[1],path[2]));break;case"H":path=["C"][concat](l2c(d.x,d.y,path[1],d.y));break;case"V":path=["C"][concat](l2c(d.x,d.y,d.x,path[1]));break;case"Z":path=["C"][concat](l2c(d.x,d.y,d.X,d.Y))}return path}),fixArc=function(pp,i){if(pp[i].length>7){pp[i].shift();for(var pi=pp[i];pi.length;)pp.splice(i++,0,["C"][concat](pi.splice(0,6)));pp.splice(i,1),ii=mmax(p.length,p2&&p2.length||0)}},fixM=function(path1,path2,a1,a2,i){path1&&path2&&"M"==path1[i][0]&&"M"!=path2[i][0]&&(path2.splice(i,0,["M",a2.x,a2.y]),a1.bx=0,a1.by=0,a1.x=path1[i][1],a1.y=path1[i][2],ii=mmax(p.length,p2&&p2.length||0))},i=0,ii=mmax(p.length,p2&&p2.length||0);i<ii;i++){p[i]=processPath(p[i],attrs),fixArc(p,i),p2&&(p2[i]=processPath(p2[i],attrs2)),p2&&fixArc(p2,i),fixM(p,p2,attrs,attrs2,i),fixM(p2,p,attrs2,attrs,i);var seg=p[i],seg2=p2&&p2[i],seglen=seg.length,seg2len=p2&&seg2.length;attrs.x=seg[seglen-2],attrs.y=seg[seglen-1],attrs.bx=toFloat(seg[seglen-4])||attrs.x,attrs.by=toFloat(seg[seglen-3])||attrs.y,attrs2.bx=p2&&(toFloat(seg2[seg2len-4])||attrs2.x),attrs2.by=p2&&(toFloat(seg2[seg2len-3])||attrs2.y),attrs2.x=p2&&seg2[seg2len-2],attrs2.y=p2&&seg2[seg2len-1]}return p2||(pth.curve=pathClone(p)),p2?[p,p2]:p},null,pathClone),tear=(R._parseDots=cacher(function(gradient){for(var dots=[],i=0,ii=gradient.length;i<ii;i++){var dot={},par=gradient[i].match(/^([^:]*):?([\d\.]*)/);if(dot.color=R.getRGB(par[1]),dot.color.error)return null;dot.color=dot.color.hex,par[2]&&(dot.offset=par[2]+"%"),dots.push(dot)}for(i=1,ii=dots.length-1;i<ii;i++)if(!dots[i].offset){for(var start=toFloat(dots[i-1].offset||0),end=0,j=i+1;j<ii;j++)if(dots[j].offset){end=dots[j].offset;break}end||(end=100,j=ii),end=toFloat(end);for(var d=(end-start)/(j-i+1);i<j;i++)start+=d,dots[i].offset=start+"%"}return dots}),R._tear=function(el,paper){el==paper.top&&(paper.top=el.prev),el==paper.bottom&&(paper.bottom=el.next),el.next&&(el.next.prev=el.prev),el.prev&&(el.prev.next=el.next)}),toMatrix=(R._tofront=function(el,paper){paper.top!==el&&(tear(el,paper),el.next=null,el.prev=paper.top,paper.top.next=el,paper.top=el)},R._toback=function(el,paper){paper.bottom!==el&&(tear(el,paper),el.next=paper.bottom,el.prev=null,paper.bottom.prev=el,paper.bottom=el)},R._insertafter=function(el,el2,paper){tear(el,paper),el2==paper.top&&(paper.top=el),el2.next&&(el2.next.prev=el),el.next=el2.next,el.prev=el2,el2.next=el},R._insertbefore=function(el,el2,paper){tear(el,paper),el2==paper.bottom&&(paper.bottom=el),el2.prev&&(el2.prev.next=el),el.prev=el2.prev,el2.prev=el,el.next=el2},R.toMatrix=function(path,transform){var bb=pathDimensions(path),el={_:{transform:E},getBBox:function(){return bb}};return extractTransform(el,transform),el.matrix}),extractTransform=(R.transformPath=function(path,transform){return mapPath(path,toMatrix(path,transform))},R._extractTransform=function(el,tstr){if(null==tstr)return el._.transform;tstr=Str(tstr).replace(/\.{3}|\u2026/g,el._.transform||E);var tdata=R.parseTransformString(tstr),deg=0,dx=0,dy=0,sx=1,sy=1,_=el._,m=new Matrix;if(_.transform=tdata||[],tdata)for(var i=0,ii=tdata.length;i<ii;i++){var x1,y1,x2,y2,bb,t=tdata[i],tlen=t.length,command=Str(t[0]).toLowerCase(),absolute=t[0]!=command,inver=absolute?m.invert():0;"t"==command&&3==tlen?absolute?(x1=inver.x(0,0),y1=inver.y(0,0),x2=inver.x(t[1],t[2]),y2=inver.y(t[1],t[2]),m.translate(x2-x1,y2-y1)):m.translate(t[1],t[2]):"r"==command?2==tlen?(bb=bb||el.getBBox(1),m.rotate(t[1],bb.x+bb.width/2,bb.y+bb.height/2),deg+=t[1]):4==tlen&&(absolute?(x2=inver.x(t[2],t[3]),y2=inver.y(t[2],t[3]),m.rotate(t[1],x2,y2)):m.rotate(t[1],t[2],t[3]),deg+=t[1]):"s"==command?2==tlen||3==tlen?(bb=bb||el.getBBox(1),m.scale(t[1],t[tlen-1],bb.x+bb.width/2,bb.y+bb.height/2),sx*=t[1],sy*=t[tlen-1]):5==tlen&&(absolute?(x2=inver.x(t[3],t[4]),y2=inver.y(t[3],t[4]),m.scale(t[1],t[2],x2,y2)):m.scale(t[1],t[2],t[3],t[4]),sx*=t[1],sy*=t[2]):"m"==command&&7==tlen&&m.add(t[1],t[2],t[3],t[4],t[5],t[6]),_.dirtyT=1,el.matrix=m}el.matrix=m,_.sx=sx,_.sy=sy,_.deg=deg,_.dx=dx=m.e,_.dy=dy=m.f,1==sx&&1==sy&&!deg&&_.bbox?(_.bbox.x+=+dx,_.bbox.y+=+dy):_.dirtyT=1}),getEmpty=function(item){var l=item[0];switch(l.toLowerCase()){case"t":return[l,0,0];case"m":return[l,1,0,0,1,0,0];case"r":return 4==item.length?[l,0,item[2],item[3]]:[l,0];case"s":return 5==item.length?[l,1,1,item[3],item[4]]:3==item.length?[l,1,1]:[l,1]}},equaliseTransform=R._equaliseTransform=function(t1,t2){t2=Str(t2).replace(/\.{3}|\u2026/g,t1),t1=R.parseTransformString(t1)||[],t2=R.parseTransformString(t2)||[];for(var j,jj,tt1,tt2,maxlength=mmax(t1.length,t2.length),from=[],to=[],i=0;i<maxlength;i++){if(tt1=t1[i]||getEmpty(t2[i]),tt2=t2[i]||getEmpty(tt1),tt1[0]!=tt2[0]||"r"==tt1[0].toLowerCase()&&(tt1[2]!=tt2[2]||tt1[3]!=tt2[3])||"s"==tt1[0].toLowerCase()&&(tt1[3]!=tt2[3]||tt1[4]!=tt2[4]))return;for(from[i]=[],to[i]=[],j=0,jj=mmax(tt1.length,tt2.length);j<jj;j++)j in tt1&&(from[i][j]=tt1[j]),j in tt2&&(to[i][j]=tt2[j])}return{from:from,to:to}};R._getContainer=function(x,y,w,h){var container;if(container=null!=h||R.is(x,"object")?x:g.doc.getElementById(x),null!=container)return container.tagName?null==y?{container:container,width:container.style.pixelWidth||container.offsetWidth,height:container.style.pixelHeight||container.offsetHeight}:{container:container,width:y,height:w}:{container:1,x:x,y:y,width:w,height:h}},R.pathToRelative=pathToRelative,R._engine={},R.path2curve=path2curve,R.matrix=function(a,b,c,d,e,f){return new Matrix(a,b,c,d,e,f)},function(matrixproto){function norm(a){return a[0]*a[0]+a[1]*a[1]}function normalize(a){var mag=math.sqrt(norm(a));a[0]&&(a[0]/=mag),a[1]&&(a[1]/=mag)}matrixproto.add=function(a,b,c,d,e,f){var x,y,z,res,out=[[],[],[]],m=[[this.a,this.c,this.e],[this.b,this.d,this.f],[0,0,1]],matrix=[[a,c,e],[b,d,f],[0,0,1]];for(a&&a instanceof Matrix&&(matrix=[[a.a,a.c,a.e],[a.b,a.d,a.f],[0,0,1]]),x=0;x<3;x++)for(y=0;y<3;y++){for(res=0,z=0;z<3;z++)res+=m[x][z]*matrix[z][y];out[x][y]=res}this.a=out[0][0],this.b=out[1][0],this.c=out[0][1],this.d=out[1][1],this.e=out[0][2],this.f=out[1][2]},matrixproto.invert=function(){var me=this,x=me.a*me.d-me.b*me.c;return new Matrix(me.d/x,-me.b/x,-me.c/x,me.a/x,(me.c*me.f-me.d*me.e)/x,(me.b*me.e-me.a*me.f)/x)},matrixproto.clone=function(){return new Matrix(this.a,this.b,this.c,this.d,this.e,this.f)},matrixproto.translate=function(x,y){this.add(1,0,0,1,x,y)},matrixproto.scale=function(x,y,cx,cy){null==y&&(y=x),(cx||cy)&&this.add(1,0,0,1,cx,cy),this.add(x,0,0,y,0,0),(cx||cy)&&this.add(1,0,0,1,-cx,-cy)},matrixproto.rotate=function(a,x,y){a=R.rad(a),x=x||0,y=y||0;var cos=+math.cos(a).toFixed(9),sin=+math.sin(a).toFixed(9);this.add(cos,sin,-sin,cos,x,y),this.add(1,0,0,1,-x,-y)},matrixproto.x=function(x,y){return x*this.a+y*this.c+this.e},matrixproto.y=function(x,y){return x*this.b+y*this.d+this.f},matrixproto.get=function(i){return+this[Str.fromCharCode(97+i)].toFixed(4)},matrixproto.toString=function(){return R.svg?"matrix("+[this.get(0),this.get(1),this.get(2),this.get(3),this.get(4),this.get(5)].join()+")":[this.get(0),this.get(2),this.get(1),this.get(3),0,0].join()},matrixproto.toFilter=function(){return"progid:DXImageTransform.Microsoft.Matrix(M11="+this.get(0)+", M12="+this.get(2)+", M21="+this.get(1)+", M22="+this.get(3)+", Dx="+this.get(4)+", Dy="+this.get(5)+", sizingmethod='auto expand')"},matrixproto.offset=function(){return[this.e.toFixed(4),this.f.toFixed(4)]},matrixproto.split=function(){var out={};out.dx=this.e,out.dy=this.f;var row=[[this.a,this.c],[this.b,this.d]];out.scalex=math.sqrt(norm(row[0])),normalize(row[0]),out.shear=row[0][0]*row[1][0]+row[0][1]*row[1][1],row[1]=[row[1][0]-row[0][0]*out.shear,row[1][1]-row[0][1]*out.shear],out.scaley=math.sqrt(norm(row[1])),normalize(row[1]),out.shear/=out.scaley;var sin=-row[0][1],cos=row[1][1];return cos<0?(out.rotate=R.deg(math.acos(cos)),sin<0&&(out.rotate=360-out.rotate)):out.rotate=R.deg(math.asin(sin)),out.isSimple=!(+out.shear.toFixed(9)||out.scalex.toFixed(9)!=out.scaley.toFixed(9)&&out.rotate),out.isSuperSimple=!+out.shear.toFixed(9)&&out.scalex.toFixed(9)==out.scaley.toFixed(9)&&!out.rotate,out.noRotation=!+out.shear.toFixed(9)&&!out.rotate,out},matrixproto.toTransformString=function(shorter){var s=shorter||this[split]();return s.isSimple?(s.scalex=+s.scalex.toFixed(4),s.scaley=+s.scaley.toFixed(4),s.rotate=+s.rotate.toFixed(4),(s.dx||s.dy?"t"+[s.dx,s.dy]:E)+(1!=s.scalex||1!=s.scaley?"s"+[s.scalex,s.scaley,0,0]:E)+(s.rotate?"r"+[s.rotate,0,0]:E)):"m"+[this.get(0),this.get(1),this.get(2),this.get(3),this.get(4),this.get(5)]}}(Matrix.prototype);var version=navigator.userAgent.match(/Version\/(.*?)\s/)||navigator.userAgent.match(/Chrome\/(\d+)/);"Apple Computer, Inc."==navigator.vendor&&(version&&version[1]<4||"iP"==navigator.platform.slice(0,2))||"Google Inc."==navigator.vendor&&version&&version[1]<8?paperproto.safari=function(){var rect=this.rect(-99,-99,this.width+99,this.height+99).attr({stroke:"none"});setTimeout(function(){rect.remove()})}:paperproto.safari=fun;for(var preventDefault=function(){this.returnValue=!1},preventTouch=function(){return this.originalEvent.preventDefault()},stopPropagation=function(){this.cancelBubble=!0},stopTouch=function(){return this.originalEvent.stopPropagation()},getEventPosition=function(e){var scrollY=g.doc.documentElement.scrollTop||g.doc.body.scrollTop,scrollX=g.doc.documentElement.scrollLeft||g.doc.body.scrollLeft;return{x:e.clientX+scrollX,y:e.clientY+scrollY}},addEvent=function(){return g.doc.addEventListener?function(obj,type,fn,element){var f=function(e){var pos=getEventPosition(e);return fn.call(element,e,pos.x,pos.y)};if(obj.addEventListener(type,f,!1),supportsTouch&&touchMap[type]){var _f=function(e){for(var pos=getEventPosition(e),olde=e,i=0,ii=e.targetTouches&&e.targetTouches.length;i<ii;i++)if(e.targetTouches[i].target==obj){e=e.targetTouches[i],e.originalEvent=olde,e.preventDefault=preventTouch,e.stopPropagation=stopTouch;break}return fn.call(element,e,pos.x,pos.y)};obj.addEventListener(touchMap[type],_f,!1)}return function(){return obj.removeEventListener(type,f,!1),supportsTouch&&touchMap[type]&&obj.removeEventListener(touchMap[type],f,!1),!0}}:g.doc.attachEvent?function(obj,type,fn,element){var f=function(e){e=e||g.win.event;var scrollY=g.doc.documentElement.scrollTop||g.doc.body.scrollTop,scrollX=g.doc.documentElement.scrollLeft||g.doc.body.scrollLeft,x=e.clientX+scrollX,y=e.clientY+scrollY;return e.preventDefault=e.preventDefault||preventDefault,e.stopPropagation=e.stopPropagation||stopPropagation,fn.call(element,e,x,y)};obj.attachEvent("on"+type,f);var detacher=function(){return obj.detachEvent("on"+type,f),!0};return detacher}:void 0}(),drag=[],dragMove=function(e){for(var dragi,x=e.clientX,y=e.clientY,scrollY=g.doc.documentElement.scrollTop||g.doc.body.scrollTop,scrollX=g.doc.documentElement.scrollLeft||g.doc.body.scrollLeft,j=drag.length;j--;){if(dragi=drag[j],supportsTouch&&e.touches){for(var touch,i=e.touches.length;i--;)if(touch=e.touches[i],touch.identifier==dragi.el._drag.id){x=touch.clientX,y=touch.clientY,(e.originalEvent?e.originalEvent:e).preventDefault();break}}else e.preventDefault();var o,node=dragi.el.node,next=node.nextSibling,parent=node.parentNode,display=node.style.display;g.win.opera&&parent.removeChild(node),node.style.display="none",o=dragi.el.paper.getElementByPoint(x,y),node.style.display=display,g.win.opera&&(next?parent.insertBefore(node,next):parent.appendChild(node)),o&&eve("raphael.drag.over."+dragi.el.id,dragi.el,o),x+=scrollX,y+=scrollY,eve("raphael.drag.move."+dragi.el.id,dragi.move_scope||dragi.el,x-dragi.el._drag.x,y-dragi.el._drag.y,x,y,e)}},dragUp=function(e){R.unmousemove(dragMove).unmouseup(dragUp);for(var dragi,i=drag.length;i--;)dragi=drag[i],dragi.el._drag={},eve("raphael.drag.end."+dragi.el.id,dragi.end_scope||dragi.start_scope||dragi.move_scope||dragi.el,e);drag=[]},elproto=R.el={},i=events.length;i--;)!function(eventName){R[eventName]=elproto[eventName]=function(fn,scope){return R.is(fn,"function")&&(this.events=this.events||[],this.events.push({name:eventName,f:fn,unbind:addEvent(this.shape||this.node||g.doc,eventName,fn,scope||this)})),this},R["un"+eventName]=elproto["un"+eventName]=function(fn){for(var events=this.events||[],l=events.length;l--;)events[l].name!=eventName||!R.is(fn,"undefined")&&events[l].f!=fn||(events[l].unbind(),events.splice(l,1),!events.length&&delete this.events);return this}}(events[i]);elproto.data=function(key,value){var data=eldata[this.id]=eldata[this.id]||{};if(0==arguments.length)return data;if(1==arguments.length){if(R.is(key,"object")){for(var i in key)key[has](i)&&this.data(i,key[i]);return this}return eve("raphael.data.get."+this.id,this,data[key],key),data[key]}return data[key]=value,eve("raphael.data.set."+this.id,this,value,key),this},elproto.removeData=function(key){return null==key?eldata[this.id]={}:eldata[this.id]&&delete eldata[this.id][key],this},elproto.getData=function(){return clone(eldata[this.id]||{})},elproto.hover=function(f_in,f_out,scope_in,scope_out){return this.mouseover(f_in,scope_in).mouseout(f_out,scope_out||scope_in)},elproto.unhover=function(f_in,f_out){return this.unmouseover(f_in).unmouseout(f_out)};var draggable=[];elproto.drag=function(onmove,onstart,onend,move_scope,start_scope,end_scope){function start(e){(e.originalEvent||e).preventDefault();var x=e.clientX,y=e.clientY,scrollY=g.doc.documentElement.scrollTop||g.doc.body.scrollTop,scrollX=g.doc.documentElement.scrollLeft||g.doc.body.scrollLeft;if(this._drag.id=e.identifier,supportsTouch&&e.touches)for(var touch,i=e.touches.length;i--;)if(touch=e.touches[i],this._drag.id=touch.identifier,touch.identifier==this._drag.id){x=touch.clientX,y=touch.clientY;break}this._drag.x=x+scrollX,this._drag.y=y+scrollY,!drag.length&&R.mousemove(dragMove).mouseup(dragUp),drag.push({el:this,move_scope:move_scope,start_scope:start_scope,end_scope:end_scope}),onstart&&eve.on("raphael.drag.start."+this.id,onstart),onmove&&eve.on("raphael.drag.move."+this.id,onmove),onend&&eve.on("raphael.drag.end."+this.id,onend),eve("raphael.drag.start."+this.id,start_scope||move_scope||this,e.clientX+scrollX,e.clientY+scrollY,e)}return this._drag={},draggable.push({el:this,start:start}),this.mousedown(start),this},elproto.onDragOver=function(f){f?eve.on("raphael.drag.over."+this.id,f):eve.unbind("raphael.drag.over."+this.id)},elproto.undrag=function(){for(var i=draggable.length;i--;)draggable[i].el==this&&(this.unmousedown(draggable[i].start),draggable.splice(i,1),eve.unbind("raphael.drag.*."+this.id));!draggable.length&&R.unmousemove(dragMove).unmouseup(dragUp),drag=[]},paperproto.circle=function(x,y,r){var out=R._engine.circle(this,x||0,y||0,r||0);return this.__set__&&this.__set__.push(out),out},paperproto.rect=function(x,y,w,h,r){var out=R._engine.rect(this,x||0,y||0,w||0,h||0,r||0);return this.__set__&&this.__set__.push(out),out},paperproto.ellipse=function(x,y,rx,ry){var out=R._engine.ellipse(this,x||0,y||0,rx||0,ry||0);return this.__set__&&this.__set__.push(out),out},paperproto.path=function(pathString){pathString&&!R.is(pathString,string)&&!R.is(pathString[0],array)&&(pathString+=E);var out=R._engine.path(R.format[apply](R,arguments),this);return this.__set__&&this.__set__.push(out),out},paperproto.image=function(src,x,y,w,h){var out=R._engine.image(this,src||"about:blank",x||0,y||0,w||0,h||0);return this.__set__&&this.__set__.push(out),out},paperproto.text=function(x,y,text){var out=R._engine.text(this,x||0,y||0,Str(text));return this.__set__&&this.__set__.push(out),out},paperproto.set=function(itemsArray){!R.is(itemsArray,"array")&&(itemsArray=Array.prototype.splice.call(arguments,0,arguments.length));var out=new Set(itemsArray);return this.__set__&&this.__set__.push(out),out.paper=this,out.type="set",out},paperproto.setStart=function(set){this.__set__=set||this.set()},paperproto.setFinish=function(set){var out=this.__set__;return delete this.__set__,out},paperproto.setSize=function(width,height){return R._engine.setSize.call(this,width,height)},paperproto.setViewBox=function(x,y,w,h,fit){return R._engine.setViewBox.call(this,x,y,w,h,fit)},paperproto.top=paperproto.bottom=null,paperproto.raphael=R;var getOffset=function(elem){var box=elem.getBoundingClientRect(),doc=elem.ownerDocument,body=doc.body,docElem=doc.documentElement,clientTop=docElem.clientTop||body.clientTop||0,clientLeft=docElem.clientLeft||body.clientLeft||0,top=box.top+(g.win.pageYOffset||docElem.scrollTop||body.scrollTop)-clientTop,left=box.left+(g.win.pageXOffset||docElem.scrollLeft||body.scrollLeft)-clientLeft;return{y:top,x:left}};paperproto.getElementByPoint=function(x,y){var paper=this,svg=paper.canvas,target=g.doc.elementFromPoint(x,y);if(g.win.opera&&"svg"==target.tagName){var so=getOffset(svg),sr=svg.createSVGRect();sr.x=x-so.x,sr.y=y-so.y,sr.width=sr.height=1;var hits=svg.getIntersectionList(sr,null);hits.length&&(target=hits[hits.length-1])}if(!target)return null;for(;target.parentNode&&target!=svg.parentNode&&!target.raphael;)target=target.parentNode;return target==paper.canvas.parentNode&&(target=svg),target=target&&target.raphael?paper.getById(target.raphaelid):null},paperproto.getElementsByBBox=function(bbox){var set=this.set();return this.forEach(function(el){R.isBBoxIntersect(el.getBBox(),bbox)&&set.push(el)}),set},paperproto.getById=function(id){for(var bot=this.bottom;bot;){if(bot.id==id)return bot;bot=bot.next}return null},paperproto.forEach=function(callback,thisArg){for(var bot=this.bottom;bot;){if(callback.call(thisArg,bot)===!1)return this;bot=bot.next}return this},paperproto.getElementsByPoint=function(x,y){var set=this.set();return this.forEach(function(el){el.isPointInside(x,y)&&set.push(el)}),set},elproto.isPointInside=function(x,y){var rp=this.realPath=getPath[this.type](this);return this.attr("transform")&&this.attr("transform").length&&(rp=R.transformPath(rp,this.attr("transform"))),R.isPointInsidePath(rp,x,y)},elproto.getBBox=function(isWithoutTransform){if(this.removed)return{};var _=this._;return isWithoutTransform?(!_.dirty&&_.bboxwt||(this.realPath=getPath[this.type](this),_.bboxwt=pathDimensions(this.realPath),_.bboxwt.toString=x_y_w_h,_.dirty=0),_.bboxwt):((_.dirty||_.dirtyT||!_.bbox)&&(!_.dirty&&this.realPath||(_.bboxwt=0,this.realPath=getPath[this.type](this)),_.bbox=pathDimensions(mapPath(this.realPath,this.matrix)),_.bbox.toString=x_y_w_h,_.dirty=_.dirtyT=0),_.bbox)},elproto.clone=function(){if(this.removed)return null;var out=this.paper[this.type]().attr(this.attr());return this.__set__&&this.__set__.push(out),out},elproto.glow=function(glow){if("text"==this.type)return null;glow=glow||{};var s={width:(glow.width||10)+(+this.attr("stroke-width")||1),fill:glow.fill||!1,opacity:glow.opacity||.5,offsetx:glow.offsetx||0,offsety:glow.offsety||0,color:glow.color||"#000"},c=s.width/2,r=this.paper,out=r.set(),path=this.realPath||getPath[this.type](this);path=this.matrix?mapPath(path,this.matrix):path;for(var i=1;i<c+1;i++)out.push(r.path(path).attr({stroke:s.color,fill:s.fill?s.color:"none","stroke-linejoin":"round","stroke-linecap":"round","stroke-width":+(s.width/c*i).toFixed(3),opacity:+(s.opacity/c).toFixed(3)}));return out.insertBefore(this).translate(s.offsetx,s.offsety)};var getPointAtSegmentLength=function(p1x,p1y,c1x,c1y,c2x,c2y,p2x,p2y,length){return null==length?bezlen(p1x,p1y,c1x,c1y,c2x,c2y,p2x,p2y):R.findDotsAtSegment(p1x,p1y,c1x,c1y,c2x,c2y,p2x,p2y,getTatLen(p1x,p1y,c1x,c1y,c2x,c2y,p2x,p2y,length))},getLengthFactory=function(istotal,subpath){return function(path,length,onlystart){path=path2curve(path);for(var x,y,p,l,point,sp="",subpaths={},len=0,i=0,ii=path.length;i<ii;i++){if(p=path[i],"M"==p[0])x=+p[1],y=+p[2];else{if(l=getPointAtSegmentLength(x,y,p[1],p[2],p[3],p[4],p[5],p[6]),len+l>length){if(subpath&&!subpaths.start){if(point=getPointAtSegmentLength(x,y,p[1],p[2],p[3],p[4],p[5],p[6],length-len),sp+=["C"+point.start.x,point.start.y,point.m.x,point.m.y,point.x,point.y],onlystart)return sp;subpaths.start=sp,sp=["M"+point.x,point.y+"C"+point.n.x,point.n.y,point.end.x,point.end.y,p[5],p[6]].join(),len+=l,x=+p[5],y=+p[6];continue}if(!istotal&&!subpath)return point=getPointAtSegmentLength(x,y,p[1],p[2],p[3],p[4],p[5],p[6],length-len),{x:point.x,y:point.y,alpha:point.alpha}}len+=l,x=+p[5],y=+p[6]}sp+=p.shift()+p}return subpaths.end=sp,point=istotal?len:subpath?subpaths:R.findDotsAtSegment(x,y,p[0],p[1],p[2],p[3],p[4],p[5],1),point.alpha&&(point={x:point.x,y:point.y,alpha:point.alpha}),point}},getTotalLength=getLengthFactory(1),getPointAtLength=getLengthFactory(),getSubpathsAtLength=getLengthFactory(0,1);R.getTotalLength=getTotalLength,R.getPointAtLength=getPointAtLength,R.getSubpath=function(path,from,to){if(this.getTotalLength(path)-to<1e-6)return getSubpathsAtLength(path,from).end;var a=getSubpathsAtLength(path,to,1);return from?getSubpathsAtLength(a,from).end:a},elproto.getTotalLength=function(){var path=this.getPath();if(path)return this.node.getTotalLength?this.node.getTotalLength():getTotalLength(path)},elproto.getPointAtLength=function(length){var path=this.getPath();if(path)return getPointAtLength(path,length)},elproto.getPath=function(){var path,getPath=R._getPath[this.type];if("text"!=this.type&&"set"!=this.type)return getPath&&(path=getPath(this)),path},elproto.getSubpath=function(from,to){var path=this.getPath();if(path)return R.getSubpath(path,from,to)};var ef=R.easing_formulas={linear:function(n){return n},"<":function(n){return pow(n,1.7)},">":function(n){return pow(n,.48)},"<>":function(n){var q=.48-n/1.04,Q=math.sqrt(.1734+q*q),x=Q-q,X=pow(abs(x),1/3)*(x<0?-1:1),y=-Q-q,Y=pow(abs(y),1/3)*(y<0?-1:1),t=X+Y+.5;return 3*(1-t)*t*t+t*t*t},backIn:function(n){var s=1.70158;return n*n*((s+1)*n-s)},backOut:function(n){n-=1;var s=1.70158;return n*n*((s+1)*n+s)+1},elastic:function(n){return n==!!n?n:pow(2,-10*n)*math.sin((n-.075)*(2*PI)/.3)+1},bounce:function(n){var l,s=7.5625,p=2.75;return n<1/p?l=s*n*n:n<2/p?(n-=1.5/p,l=s*n*n+.75):n<2.5/p?(n-=2.25/p,l=s*n*n+.9375):(n-=2.625/p,l=s*n*n+.984375),l}};ef.easeIn=ef["ease-in"]=ef["<"],ef.easeOut=ef["ease-out"]=ef[">"],ef.easeInOut=ef["ease-in-out"]=ef["<>"],ef["back-in"]=ef.backIn,ef["back-out"]=ef.backOut;var animationElements=[],requestAnimFrame=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(callback){setTimeout(callback,16)},animation=function(){for(var Now=+new Date,l=0;l<animationElements.length;l++){var e=animationElements[l];if(!e.el.removed&&!e.paused){var now,key,time=Now-e.start,ms=e.ms,easing=e.easing,from=e.from,diff=e.diff,to=e.to,that=(e.t,e.el),set={},init={};if(e.initstatus?(time=(e.initstatus*e.anim.top-e.prev)/(e.percent-e.prev)*ms,e.status=e.initstatus,delete e.initstatus,e.stop&&animationElements.splice(l--,1)):e.status=(e.prev+(e.percent-e.prev)*(time/ms))/e.anim.top,!(time<0))if(time<ms){var pos=easing(time/ms);for(var attr in from)if(from[has](attr)){switch(availableAnimAttrs[attr]){case nu:now=+from[attr]+pos*ms*diff[attr];break;case"colour":now="rgb("+[upto255(round(from[attr].r+pos*ms*diff[attr].r)),upto255(round(from[attr].g+pos*ms*diff[attr].g)),upto255(round(from[attr].b+pos*ms*diff[attr].b))].join(",")+")";break;case"path":now=[];for(var i=0,ii=from[attr].length;i<ii;i++){now[i]=[from[attr][i][0]];for(var j=1,jj=from[attr][i].length;j<jj;j++)now[i][j]=+from[attr][i][j]+pos*ms*diff[attr][i][j];now[i]=now[i].join(S)}now=now.join(S);break;case"transform":if(diff[attr].real)for(now=[],i=0,ii=from[attr].length;i<ii;i++)for(now[i]=[from[attr][i][0]],j=1,jj=from[attr][i].length;j<jj;j++)now[i][j]=from[attr][i][j]+pos*ms*diff[attr][i][j];else{var get=function(i){return+from[attr][i]+pos*ms*diff[attr][i]};now=[["m",get(0),get(1),get(2),get(3),get(4),get(5)]]}break;case"csv":if("clip-rect"==attr)for(now=[],i=4;i--;)now[i]=+from[attr][i]+pos*ms*diff[attr][i];break;default:var from2=[][concat](from[attr]);for(now=[],i=that.paper.customAttributes[attr].length;i--;)now[i]=+from2[i]+pos*ms*diff[attr][i]}set[attr]=now}that.attr(set),function(id,that,anim){setTimeout(function(){eve("raphael.anim.frame."+id,that,anim)})}(that.id,that,e.anim)}else{if(function(f,el,a){setTimeout(function(){eve("raphael.anim.frame."+el.id,el,a),eve("raphael.anim.finish."+el.id,el,a),R.is(f,"function")&&f.call(el)})}(e.callback,that,e.anim),that.attr(to),animationElements.splice(l--,1),e.repeat>1&&!e.next){for(key in to)to[has](key)&&(init[key]=e.totalOrigin[key]);e.el.attr(init),runAnimation(e.anim,e.el,e.anim.percents[0],null,e.totalOrigin,e.repeat-1)}e.next&&!e.stop&&runAnimation(e.anim,e.el,e.next,null,e.totalOrigin,e.repeat)}}}R.svg&&that&&that.paper&&that.paper.safari(),animationElements.length&&requestAnimFrame(animation)},upto255=function(color){return color>255?255:color<0?0:color};elproto.animateWith=function(el,anim,params,ms,easing,callback){var element=this;if(element.removed)return callback&&callback.call(element),element;var a=params instanceof Animation?params:R.animation(params,ms,easing,callback);runAnimation(a,element,a.percents[0],null,element.attr());for(var i=0,ii=animationElements.length;i<ii;i++)if(animationElements[i].anim==anim&&animationElements[i].el==el){animationElements[ii-1].start=animationElements[i].start;break}return element},elproto.onAnimation=function(f){return f?eve.on("raphael.anim.frame."+this.id,f):eve.unbind("raphael.anim.frame."+this.id),this},Animation.prototype.delay=function(delay){var a=new Animation(this.anim,this.ms);return a.times=this.times,a.del=+delay||0,a},Animation.prototype.repeat=function(times){var a=new Animation(this.anim,this.ms);return a.del=this.del,a.times=math.floor(mmax(times,0))||1,a},R.animation=function(params,ms,easing,callback){if(params instanceof Animation)return params; !R.is(easing,"function")&&easing||(callback=callback||easing||null,easing=null),params=Object(params),ms=+ms||0;var json,attr,p={};for(attr in params)params[has](attr)&&toFloat(attr)!=attr&&toFloat(attr)+"%"!=attr&&(json=!0,p[attr]=params[attr]);return json?(easing&&(p.easing=easing),callback&&(p.callback=callback),new Animation({100:p},ms)):new Animation(params,ms)},elproto.animate=function(params,ms,easing,callback){var element=this;if(element.removed)return callback&&callback.call(element),element;var anim=params instanceof Animation?params:R.animation(params,ms,easing,callback);return runAnimation(anim,element,anim.percents[0],null,element.attr()),element},elproto.setTime=function(anim,value){return anim&&null!=value&&this.status(anim,mmin(value,anim.ms)/anim.ms),this},elproto.status=function(anim,value){var len,e,out=[],i=0;if(null!=value)return runAnimation(anim,this,-1,mmin(value,1)),this;for(len=animationElements.length;i<len;i++)if(e=animationElements[i],e.el.id==this.id&&(!anim||e.anim==anim)){if(anim)return e.status;out.push({anim:e.anim,status:e.status})}return anim?0:out},elproto.pause=function(anim){for(var i=0;i<animationElements.length;i++)animationElements[i].el.id!=this.id||anim&&animationElements[i].anim!=anim||eve("raphael.anim.pause."+this.id,this,animationElements[i].anim)!==!1&&(animationElements[i].paused=!0);return this},elproto.resume=function(anim){for(var i=0;i<animationElements.length;i++)if(animationElements[i].el.id==this.id&&(!anim||animationElements[i].anim==anim)){var e=animationElements[i];eve("raphael.anim.resume."+this.id,this,e.anim)!==!1&&(delete e.paused,this.status(e.anim,e.status))}return this},elproto.stop=function(anim){for(var i=0;i<animationElements.length;i++)animationElements[i].el.id!=this.id||anim&&animationElements[i].anim!=anim||eve("raphael.anim.stop."+this.id,this,animationElements[i].anim)!==!1&&animationElements.splice(i--,1);return this},eve.on("raphael.remove",stopAnimation),eve.on("raphael.clear",stopAnimation),elproto.toString=function(){return"Raphaël’s object"};var Set=function(items){if(this.items=[],this.length=0,this.type="set",items)for(var i=0,ii=items.length;i<ii;i++)!items[i]||items[i].constructor!=elproto.constructor&&items[i].constructor!=Set||(this[this.items.length]=this.items[this.items.length]=items[i],this.length++)},setproto=Set.prototype;setproto.push=function(){for(var item,len,i=0,ii=arguments.length;i<ii;i++)item=arguments[i],!item||item.constructor!=elproto.constructor&&item.constructor!=Set||(len=this.items.length,this[len]=this.items[len]=item,this.length++);return this},setproto.pop=function(){return this.length&&delete this[this.length--],this.items.pop()},setproto.forEach=function(callback,thisArg){for(var i=0,ii=this.items.length;i<ii;i++)if(callback.call(thisArg,this.items[i],i)===!1)return this;return this};for(var method in elproto)elproto[has](method)&&(setproto[method]=function(methodname){return function(){var arg=arguments;return this.forEach(function(el){el[methodname][apply](el,arg)})}}(method));return setproto.attr=function(name,value){if(name&&R.is(name,array)&&R.is(name[0],"object"))for(var j=0,jj=name.length;j<jj;j++)this.items[j].attr(name[j]);else for(var i=0,ii=this.items.length;i<ii;i++)this.items[i].attr(name,value);return this},setproto.clear=function(){for(;this.length;)this.pop()},setproto.splice=function(index,count,insertion){index=index<0?mmax(this.length+index,0):index,count=mmax(0,mmin(this.length-index,count));var i,tail=[],todel=[],args=[];for(i=2;i<arguments.length;i++)args.push(arguments[i]);for(i=0;i<count;i++)todel.push(this[index+i]);for(;i<this.length-index;i++)tail.push(this[index+i]);var arglen=args.length;for(i=0;i<arglen+tail.length;i++)this.items[index+i]=this[index+i]=i<arglen?args[i]:tail[i-arglen];for(i=this.items.length=this.length-=count-arglen;this[i];)delete this[i++];return new Set(todel)},setproto.exclude=function(el){for(var i=0,ii=this.length;i<ii;i++)if(this[i]==el)return this.splice(i,1),!0},setproto.animate=function(params,ms,easing,callback){(R.is(easing,"function")||!easing)&&(callback=easing||null);var item,collector,len=this.items.length,i=len,set=this;if(!len)return this;callback&&(collector=function(){!--len&&callback.call(set)}),easing=R.is(easing,string)?easing:collector;var anim=R.animation(params,ms,easing,collector);for(item=this.items[--i].animate(anim);i--;)this.items[i]&&!this.items[i].removed&&this.items[i].animateWith(item,anim,anim),this.items[i]&&!this.items[i].removed||len--;return this},setproto.insertAfter=function(el){for(var i=this.items.length;i--;)this.items[i].insertAfter(el);return this},setproto.getBBox=function(){for(var x=[],y=[],x2=[],y2=[],i=this.items.length;i--;)if(!this.items[i].removed){var box=this.items[i].getBBox();x.push(box.x),y.push(box.y),x2.push(box.x+box.width),y2.push(box.y+box.height)}return x=mmin[apply](0,x),y=mmin[apply](0,y),x2=mmax[apply](0,x2),y2=mmax[apply](0,y2),{x:x,y:y,x2:x2,y2:y2,width:x2-x,height:y2-y}},setproto.clone=function(s){s=this.paper.set();for(var i=0,ii=this.items.length;i<ii;i++)s.push(this.items[i].clone());return s},setproto.toString=function(){return"Raphaël‘s set"},setproto.glow=function(glowConfig){var ret=this.paper.set();return this.forEach(function(shape,index){var g=shape.glow(glowConfig);null!=g&&g.forEach(function(shape2,index2){ret.push(shape2)})}),ret},setproto.isPointInside=function(x,y){var isPointInside=!1;return this.forEach(function(el){if(el.isPointInside(x,y))return console.log("runned"),isPointInside=!0,!1}),isPointInside},R.registerFont=function(font){if(!font.face)return font;this.fonts=this.fonts||{};var fontcopy={w:font.w,face:{},glyphs:{}},family=font.face["font-family"];for(var prop in font.face)font.face[has](prop)&&(fontcopy.face[prop]=font.face[prop]);if(this.fonts[family]?this.fonts[family].push(fontcopy):this.fonts[family]=[fontcopy],!font.svg){fontcopy.face["units-per-em"]=toInt(font.face["units-per-em"],10);for(var glyph in font.glyphs)if(font.glyphs[has](glyph)){var path=font.glyphs[glyph];if(fontcopy.glyphs[glyph]={w:path.w,k:{},d:path.d&&"M"+path.d.replace(/[mlcxtrv]/g,function(command){return{l:"L",c:"C",x:"z",t:"m",r:"l",v:"c"}[command]||"M"})+"z"},path.k)for(var k in path.k)path[has](k)&&(fontcopy.glyphs[glyph].k[k]=path.k[k])}}return font},paperproto.getFont=function(family,weight,style,stretch){if(stretch=stretch||"normal",style=style||"normal",weight=+weight||{normal:400,bold:700,lighter:300,bolder:800}[weight]||400,R.fonts){var font=R.fonts[family];if(!font){var name=new RegExp("(^|\\s)"+family.replace(/[^\w\d\s+!~.:_-]/g,E)+"(\\s|$)","i");for(var fontName in R.fonts)if(R.fonts[has](fontName)&&name.test(fontName)){font=R.fonts[fontName];break}}var thefont;if(font)for(var i=0,ii=font.length;i<ii&&(thefont=font[i],thefont.face["font-weight"]!=weight||thefont.face["font-style"]!=style&&thefont.face["font-style"]||thefont.face["font-stretch"]!=stretch);i++);return thefont}},paperproto.print=function(x,y,string,font,size,origin,letter_spacing,line_spacing){origin=origin||"middle",letter_spacing=mmax(mmin(letter_spacing||0,1),-1),line_spacing=mmax(mmin(line_spacing||1,3),1);var scale,letters=Str(string)[split](E),shift=0,notfirst=0,path=E;if(R.is(font,"string")&&(font=this.getFont(font)),font){scale=(size||16)/font.face["units-per-em"];for(var bb=font.face.bbox[split](separator),top=+bb[0],lineHeight=bb[3]-bb[1],shifty=0,height=+bb[1]+("baseline"==origin?lineHeight+ +font.face.descent:lineHeight/2),i=0,ii=letters.length;i<ii;i++){if("\n"==letters[i])shift=0,curr=0,notfirst=0,shifty+=lineHeight*line_spacing;else{var prev=notfirst&&font.glyphs[letters[i-1]]||{},curr=font.glyphs[letters[i]];shift+=notfirst?(prev.w||font.w)+(prev.k&&prev.k[letters[i]]||0)+font.w*letter_spacing:0,notfirst=1}curr&&curr.d&&(path+=R.transformPath(curr.d,["t",shift*scale,shifty*scale,"s",scale,scale,top,height,"t",(x-top)/scale,(y-height)/scale]))}}return this.path(path).attr({fill:"#000",stroke:"none"})},paperproto.add=function(json){if(R.is(json,"array"))for(var j,res=this.set(),i=0,ii=json.length;i<ii;i++)j=json[i]||{},elements[has](j.type)&&res.push(this[j.type]().attr(j));return res},R.format=function(token,params){var args=R.is(params,array)?[0][concat](params):arguments;return token&&R.is(token,string)&&args.length-1&&(token=token.replace(formatrg,function(str,i){return null==args[++i]?E:args[i]})),token||E},R.fullfill=function(){var tokenRegex=/\{([^\}]+)\}/g,objNotationRegex=/(?:(?:^|\.)(.+?)(?=\[|\.|$|\()|\[('|")(.+?)\2\])(\(\))?/g,replacer=function(all,key,obj){var res=obj;return key.replace(objNotationRegex,function(all,name,quote,quotedName,isFunc){name=name||quotedName,res&&(name in res&&(res=res[name]),"function"==typeof res&&isFunc&&(res=res()))}),res=(null==res||res==obj?all:res)+""};return function(str,obj){return String(str).replace(tokenRegex,function(all,key){return replacer(all,key,obj)})}}(),R.st=setproto,function(doc,loaded,f){function isLoaded(){/in/.test(doc.readyState)?setTimeout(isLoaded,9):R.eve("raphael.DOMload")}null==doc.readyState&&doc.addEventListener&&(doc.addEventListener(loaded,f=function(){doc.removeEventListener(loaded,f,!1),doc.readyState="complete"},!1),doc.readyState="loading"),isLoaded()}(document,"DOMContentLoaded"),eve.on("raphael.DOMload",function(){loaded=!0}),function(){if(R.svg){var has="hasOwnProperty",Str=String,toFloat=parseFloat,toInt=parseInt,math=Math,mmax=math.max,abs=math.abs,pow=math.pow,separator=/[, ]+/,eve=R.eve,E="",S=" ",xlink="http://www.w3.org/1999/xlink",markers={block:"M5,0 0,2.5 5,5z",classic:"M5,0 0,2.5 5,5 3.5,3 3.5,2z",diamond:"M2.5,0 5,2.5 2.5,5 0,2.5z",open:"M6,1 1,3.5 6,6",oval:"M2.5,0A2.5,2.5,0,0,1,2.5,5 2.5,2.5,0,0,1,2.5,0z"},markerCounter={};R.toString=function(){return"Your browser supports SVG.\nYou are running Raphaël "+this.version};var $=function(el,attr){if(attr){"string"==typeof el&&(el=$(el));for(var key in attr)attr[has](key)&&("xlink:"==key.substring(0,6)?el.setAttributeNS(xlink,key.substring(6),Str(attr[key])):el.setAttribute(key,Str(attr[key])))}else el=R._g.doc.createElementNS("http://www.w3.org/2000/svg",el),el.style&&(el.style.webkitTapHighlightColor="rgba(0,0,0,0)");return el},addGradientFill=function(element,gradient){var type="linear",id=element.id+gradient,fx=.5,fy=.5,o=element.node,SVG=element.paper,s=o.style,el=R._g.doc.getElementById(id);if(!el){if(gradient=Str(gradient).replace(R._radial_gradient,function(all,_fx,_fy){if(type="radial",_fx&&_fy){fx=toFloat(_fx),fy=toFloat(_fy);var dir=2*(fy>.5)-1;pow(fx-.5,2)+pow(fy-.5,2)>.25&&(fy=math.sqrt(.25-pow(fx-.5,2))*dir+.5)&&.5!=fy&&(fy=fy.toFixed(5)-1e-5*dir)}return E}),gradient=gradient.split(/\s*\-\s*/),"linear"==type){var angle=gradient.shift();if(angle=-toFloat(angle),isNaN(angle))return null;var vector=[0,0,math.cos(R.rad(angle)),math.sin(R.rad(angle))],max=1/(mmax(abs(vector[2]),abs(vector[3]))||1);vector[2]*=max,vector[3]*=max,vector[2]<0&&(vector[0]=-vector[2],vector[2]=0),vector[3]<0&&(vector[1]=-vector[3],vector[3]=0)}var dots=R._parseDots(gradient);if(!dots)return null;if(id=id.replace(/[\(\)\s,\xb0#]/g,"_"),element.gradient&&id!=element.gradient.id&&(SVG.defs.removeChild(element.gradient),delete element.gradient),!element.gradient){el=$(type+"Gradient",{id:id}),element.gradient=el,$(el,"radial"==type?{fx:fx,fy:fy}:{x1:vector[0],y1:vector[1],x2:vector[2],y2:vector[3],gradientTransform:element.matrix.invert()}),SVG.defs.appendChild(el);for(var i=0,ii=dots.length;i<ii;i++)el.appendChild($("stop",{offset:dots[i].offset?dots[i].offset:i?"100%":"0%","stop-color":dots[i].color||"#fff"}))}}return $(o,{fill:"url(#"+id+")",opacity:1,"fill-opacity":1}),s.fill=E,s.opacity=1,s.fillOpacity=1,1},updatePosition=function(o){var bbox=o.getBBox(1);$(o.pattern,{patternTransform:o.matrix.invert()+" translate("+bbox.x+","+bbox.y+")"})},addArrow=function(o,value,isEnd){if("path"==o.type){for(var from,to,dx,refX,attr,values=Str(value).toLowerCase().split("-"),p=o.paper,se=isEnd?"end":"start",node=o.node,attrs=o.attrs,stroke=attrs["stroke-width"],i=values.length,type="classic",w=3,h=3,t=5;i--;)switch(values[i]){case"block":case"classic":case"oval":case"diamond":case"open":case"none":type=values[i];break;case"wide":h=5;break;case"narrow":h=2;break;case"long":w=5;break;case"short":w=2}if("open"==type?(w+=2,h+=2,t+=2,dx=1,refX=isEnd?4:1,attr={fill:"none",stroke:attrs.stroke}):(refX=dx=w/2,attr={fill:attrs.stroke,stroke:"none"}),o._.arrows?isEnd?(o._.arrows.endPath&&markerCounter[o._.arrows.endPath]--,o._.arrows.endMarker&&markerCounter[o._.arrows.endMarker]--):(o._.arrows.startPath&&markerCounter[o._.arrows.startPath]--,o._.arrows.startMarker&&markerCounter[o._.arrows.startMarker]--):o._.arrows={},"none"!=type){var pathId="raphael-marker-"+type,markerId="raphael-marker-"+se+type+w+h;R._g.doc.getElementById(pathId)?markerCounter[pathId]++:(p.defs.appendChild($($("path"),{"stroke-linecap":"round",d:markers[type],id:pathId})),markerCounter[pathId]=1);var use,marker=R._g.doc.getElementById(markerId);marker?(markerCounter[markerId]++,use=marker.getElementsByTagName("use")[0]):(marker=$($("marker"),{id:markerId,markerHeight:h,markerWidth:w,orient:"auto",refX:refX,refY:h/2}),use=$($("use"),{"xlink:href":"#"+pathId,transform:(isEnd?"rotate(180 "+w/2+" "+h/2+") ":E)+"scale("+w/t+","+h/t+")","stroke-width":(1/((w/t+h/t)/2)).toFixed(4)}),marker.appendChild(use),p.defs.appendChild(marker),markerCounter[markerId]=1),$(use,attr);var delta=dx*("diamond"!=type&&"oval"!=type);isEnd?(from=o._.arrows.startdx*stroke||0,to=R.getTotalLength(attrs.path)-delta*stroke):(from=delta*stroke,to=R.getTotalLength(attrs.path)-(o._.arrows.enddx*stroke||0)),attr={},attr["marker-"+se]="url(#"+markerId+")",(to||from)&&(attr.d=R.getSubpath(attrs.path,from,to)),$(node,attr),o._.arrows[se+"Path"]=pathId,o._.arrows[se+"Marker"]=markerId,o._.arrows[se+"dx"]=delta,o._.arrows[se+"Type"]=type,o._.arrows[se+"String"]=value}else isEnd?(from=o._.arrows.startdx*stroke||0,to=R.getTotalLength(attrs.path)-from):(from=0,to=R.getTotalLength(attrs.path)-(o._.arrows.enddx*stroke||0)),o._.arrows[se+"Path"]&&$(node,{d:R.getSubpath(attrs.path,from,to)}),delete o._.arrows[se+"Path"],delete o._.arrows[se+"Marker"],delete o._.arrows[se+"dx"],delete o._.arrows[se+"Type"],delete o._.arrows[se+"String"];for(attr in markerCounter)if(markerCounter[has](attr)&&!markerCounter[attr]){var item=R._g.doc.getElementById(attr);item&&item.parentNode.removeChild(item)}}},dasharray={"":[0],none:[0],"-":[3,1],".":[1,1],"-.":[3,1,1,1],"-..":[3,1,1,1,1,1],". ":[1,3],"- ":[4,3],"--":[8,3],"- .":[4,3,1,3],"--.":[8,3,1,3],"--..":[8,3,1,3,1,3]},addDashes=function(o,value,params){if(value=dasharray[Str(value).toLowerCase()]){for(var width=o.attrs["stroke-width"]||"1",butt={round:width,square:width,butt:0}[o.attrs["stroke-linecap"]||params["stroke-linecap"]]||0,dashes=[],i=value.length;i--;)dashes[i]=value[i]*width+(i%2?1:-1)*butt;$(o.node,{"stroke-dasharray":dashes.join(",")})}},setFillAndStroke=function(o,params){var node=o.node,attrs=o.attrs,vis=node.style.visibility;node.style.visibility="hidden";for(var att in params)if(params[has](att)){if(!R._availableAttrs[has](att))continue;var value=params[att];switch(attrs[att]=value,att){case"blur":o.blur(value);break;case"href":case"title":var hl=$("title"),val=R._g.doc.createTextNode(value);hl.appendChild(val),node.appendChild(hl);break;case"target":var pn=node.parentNode;if("a"!=pn.tagName.toLowerCase()){var hl=$("a");pn.insertBefore(hl,node),hl.appendChild(node),pn=hl}"target"==att?pn.setAttributeNS(xlink,"show","blank"==value?"new":value):pn.setAttributeNS(xlink,att,value);break;case"cursor":node.style.cursor=value;break;case"transform":o.transform(value);break;case"arrow-start":addArrow(o,value);break;case"arrow-end":addArrow(o,value,1);break;case"clip-rect":var rect=Str(value).split(separator);if(4==rect.length){o.clip&&o.clip.parentNode.parentNode.removeChild(o.clip.parentNode);var el=$("clipPath"),rc=$("rect");el.id=R.createUUID(),$(rc,{x:rect[0],y:rect[1],width:rect[2],height:rect[3]}),el.appendChild(rc),o.paper.defs.appendChild(el),$(node,{"clip-path":"url(#"+el.id+")"}),o.clip=rc}if(!value){var path=node.getAttribute("clip-path");if(path){var clip=R._g.doc.getElementById(path.replace(/(^url\(#|\)$)/g,E));clip&&clip.parentNode.removeChild(clip),$(node,{"clip-path":E}),delete o.clip}}break;case"path":"path"==o.type&&($(node,{d:value?attrs.path=R._pathToAbsolute(value):"M0,0"}),o._.dirty=1,o._.arrows&&("startString"in o._.arrows&&addArrow(o,o._.arrows.startString),"endString"in o._.arrows&&addArrow(o,o._.arrows.endString,1)));break;case"width":if(node.setAttribute(att,value),o._.dirty=1,!attrs.fx)break;att="x",value=attrs.x;case"x":attrs.fx&&(value=-attrs.x-(attrs.width||0));case"rx":if("rx"==att&&"rect"==o.type)break;case"cx":node.setAttribute(att,value),o.pattern&&updatePosition(o),o._.dirty=1;break;case"height":if(node.setAttribute(att,value),o._.dirty=1,!attrs.fy)break;att="y",value=attrs.y;case"y":attrs.fy&&(value=-attrs.y-(attrs.height||0));case"ry":if("ry"==att&&"rect"==o.type)break;case"cy":node.setAttribute(att,value),o.pattern&&updatePosition(o),o._.dirty=1;break;case"r":"rect"==o.type?$(node,{rx:value,ry:value}):node.setAttribute(att,value),o._.dirty=1;break;case"src":"image"==o.type&&node.setAttributeNS(xlink,"href",value);break;case"stroke-width":1==o._.sx&&1==o._.sy||(value/=mmax(abs(o._.sx),abs(o._.sy))||1),o.paper._vbSize&&(value*=o.paper._vbSize),node.setAttribute(att,value),attrs["stroke-dasharray"]&&addDashes(o,attrs["stroke-dasharray"],params),o._.arrows&&("startString"in o._.arrows&&addArrow(o,o._.arrows.startString),"endString"in o._.arrows&&addArrow(o,o._.arrows.endString,1));break;case"stroke-dasharray":addDashes(o,value,params);break;case"fill":var isURL=Str(value).match(R._ISURL);if(isURL){el=$("pattern");var ig=$("image");el.id=R.createUUID(),$(el,{x:0,y:0,patternUnits:"userSpaceOnUse",height:1,width:1}),$(ig,{x:0,y:0,"xlink:href":isURL[1]}),el.appendChild(ig),function(el){R._preload(isURL[1],function(){var w=this.offsetWidth,h=this.offsetHeight;$(el,{width:w,height:h}),$(ig,{width:w,height:h}),o.paper.safari()})}(el),o.paper.defs.appendChild(el),$(node,{fill:"url(#"+el.id+")"}),o.pattern=el,o.pattern&&updatePosition(o);break}var clr=R.getRGB(value);if(clr.error){if(("circle"==o.type||"ellipse"==o.type||"r"!=Str(value).charAt())&&addGradientFill(o,value)){if("opacity"in attrs||"fill-opacity"in attrs){var gradient=R._g.doc.getElementById(node.getAttribute("fill").replace(/^url\(#|\)$/g,E));if(gradient){var stops=gradient.getElementsByTagName("stop");$(stops[stops.length-1],{"stop-opacity":("opacity"in attrs?attrs.opacity:1)*("fill-opacity"in attrs?attrs["fill-opacity"]:1)})}}attrs.gradient=value,attrs.fill="none";break}}else delete params.gradient,delete attrs.gradient,!R.is(attrs.opacity,"undefined")&&R.is(params.opacity,"undefined")&&$(node,{opacity:attrs.opacity}),!R.is(attrs["fill-opacity"],"undefined")&&R.is(params["fill-opacity"],"undefined")&&$(node,{"fill-opacity":attrs["fill-opacity"]});clr[has]("opacity")&&$(node,{"fill-opacity":clr.opacity>1?clr.opacity/100:clr.opacity});case"stroke":clr=R.getRGB(value),node.setAttribute(att,clr.hex),"stroke"==att&&clr[has]("opacity")&&$(node,{"stroke-opacity":clr.opacity>1?clr.opacity/100:clr.opacity}),"stroke"==att&&o._.arrows&&("startString"in o._.arrows&&addArrow(o,o._.arrows.startString),"endString"in o._.arrows&&addArrow(o,o._.arrows.endString,1));break;case"gradient":("circle"==o.type||"ellipse"==o.type||"r"!=Str(value).charAt())&&addGradientFill(o,value);break;case"opacity":attrs.gradient&&!attrs[has]("stroke-opacity")&&$(node,{"stroke-opacity":value>1?value/100:value});case"fill-opacity":if(attrs.gradient){gradient=R._g.doc.getElementById(node.getAttribute("fill").replace(/^url\(#|\)$/g,E)),gradient&&(stops=gradient.getElementsByTagName("stop"),$(stops[stops.length-1],{"stop-opacity":value}));break}default:"font-size"==att&&(value=toInt(value,10)+"px");var cssrule=att.replace(/(\-.)/g,function(w){return w.substring(1).toUpperCase()});node.style[cssrule]=value,o._.dirty=1,node.setAttribute(att,value)}}tuneText(o,params),node.style.visibility=vis},leading=1.2,tuneText=function(el,params){if("text"==el.type&&(params[has]("text")||params[has]("font")||params[has]("font-size")||params[has]("x")||params[has]("y"))){var a=el.attrs,node=el.node,fontSize=node.firstChild?toInt(R._g.doc.defaultView.getComputedStyle(node.firstChild,E).getPropertyValue("font-size"),10):10;if(params[has]("text")){for(a.text=params.text;node.firstChild;)node.removeChild(node.firstChild);for(var tspan,texts=Str(params.text).split("\n"),tspans=[],i=0,ii=texts.length;i<ii;i++)tspan=$("tspan"),i&&$(tspan,{dy:fontSize*leading,x:a.x}),tspan.appendChild(R._g.doc.createTextNode(texts[i])),node.appendChild(tspan),tspans[i]=tspan}else for(tspans=node.getElementsByTagName("tspan"),i=0,ii=tspans.length;i<ii;i++)i?$(tspans[i],{dy:fontSize*leading,x:a.x}):$(tspans[0],{dy:0});$(node,{x:a.x,y:a.y}),el._.dirty=1;var bb=el._getBBox(),dif=a.y-(bb.y+bb.height/2);dif&&R.is(dif,"finite")&&$(tspans[0],{dy:dif})}},Element=function(node,svg){this[0]=this.node=node,node.raphael=!0,this.id=R._oid++,node.raphaelid=this.id,this.matrix=R.matrix(),this.realPath=null,this.paper=svg,this.attrs=this.attrs||{},this._={transform:[],sx:1,sy:1,deg:0,dx:0,dy:0,dirty:1},!svg.bottom&&(svg.bottom=this),this.prev=svg.top,svg.top&&(svg.top.next=this),svg.top=this,this.next=null},elproto=R.el;Element.prototype=elproto,elproto.constructor=Element,R._engine.path=function(pathString,SVG){var el=$("path");SVG.canvas&&SVG.canvas.appendChild(el);var p=new Element(el,SVG);return p.type="path",setFillAndStroke(p,{fill:"none",stroke:"#000",path:pathString}),p},elproto.rotate=function(deg,cx,cy){if(this.removed)return this;if(deg=Str(deg).split(separator),deg.length-1&&(cx=toFloat(deg[1]),cy=toFloat(deg[2])),deg=toFloat(deg[0]),null==cy&&(cx=cy),null==cx||null==cy){var bbox=this.getBBox(1);cx=bbox.x+bbox.width/2,cy=bbox.y+bbox.height/2}return this.transform(this._.transform.concat([["r",deg,cx,cy]])),this},elproto.scale=function(sx,sy,cx,cy){if(this.removed)return this;if(sx=Str(sx).split(separator),sx.length-1&&(sy=toFloat(sx[1]),cx=toFloat(sx[2]),cy=toFloat(sx[3])),sx=toFloat(sx[0]),null==sy&&(sy=sx),null==cy&&(cx=cy),null==cx||null==cy)var bbox=this.getBBox(1);return cx=null==cx?bbox.x+bbox.width/2:cx,cy=null==cy?bbox.y+bbox.height/2:cy,this.transform(this._.transform.concat([["s",sx,sy,cx,cy]])),this},elproto.translate=function(dx,dy){return this.removed?this:(dx=Str(dx).split(separator),dx.length-1&&(dy=toFloat(dx[1])),dx=toFloat(dx[0])||0,dy=+dy||0,this.transform(this._.transform.concat([["t",dx,dy]])),this)},elproto.transform=function(tstr){var _=this._;if(null==tstr)return _.transform;if(R._extractTransform(this,tstr),this.clip&&$(this.clip,{transform:this.matrix.invert()}),this.pattern&&updatePosition(this),this.node&&$(this.node,{transform:this.matrix}),1!=_.sx||1!=_.sy){var sw=this.attrs[has]("stroke-width")?this.attrs["stroke-width"]:1;this.attr({"stroke-width":sw})}return this},elproto.hide=function(){return!this.removed&&this.paper.safari(this.node.style.display="none"),this},elproto.show=function(){return!this.removed&&this.paper.safari(this.node.style.display=""),this},elproto.remove=function(){if(!this.removed&&this.node.parentNode){var paper=this.paper;paper.__set__&&paper.__set__.exclude(this),eve.unbind("raphael.*.*."+this.id),this.gradient&&paper.defs.removeChild(this.gradient),R._tear(this,paper),"a"==this.node.parentNode.tagName.toLowerCase()?this.node.parentNode.parentNode.removeChild(this.node.parentNode):this.node.parentNode.removeChild(this.node);for(var i in this)this[i]="function"==typeof this[i]?R._removedFactory(i):null;this.removed=!0}},elproto._getBBox=function(){if("none"==this.node.style.display){this.show();var hide=!0}var bbox={};try{bbox=this.node.getBBox()}catch(e){}finally{bbox=bbox||{}}return hide&&this.hide(),bbox},elproto.attr=function(name,value){if(this.removed)return this;if(null==name){var res={};for(var a in this.attrs)this.attrs[has](a)&&(res[a]=this.attrs[a]);return res.gradient&&"none"==res.fill&&(res.fill=res.gradient)&&delete res.gradient,res.transform=this._.transform,res}if(null==value&&R.is(name,"string")){if("fill"==name&&"none"==this.attrs.fill&&this.attrs.gradient)return this.attrs.gradient;if("transform"==name)return this._.transform;for(var names=name.split(separator),out={},i=0,ii=names.length;i<ii;i++)name=names[i],name in this.attrs?out[name]=this.attrs[name]:R.is(this.paper.customAttributes[name],"function")?out[name]=this.paper.customAttributes[name].def:out[name]=R._availableAttrs[name];return ii-1?out:out[names[0]]}if(null==value&&R.is(name,"array")){for(out={},i=0,ii=name.length;i<ii;i++)out[name[i]]=this.attr(name[i]);return out}if(null!=value){var params={};params[name]=value}else null!=name&&R.is(name,"object")&&(params=name);for(var key in params)eve("raphael.attr."+key+"."+this.id,this,params[key]);for(key in this.paper.customAttributes)if(this.paper.customAttributes[has](key)&&params[has](key)&&R.is(this.paper.customAttributes[key],"function")){var par=this.paper.customAttributes[key].apply(this,[].concat(params[key]));this.attrs[key]=params[key];for(var subkey in par)par[has](subkey)&&(params[subkey]=par[subkey])}return setFillAndStroke(this,params),this},elproto.toFront=function(){if(this.removed)return this;"a"==this.node.parentNode.tagName.toLowerCase()?this.node.parentNode.parentNode.appendChild(this.node.parentNode):this.node.parentNode.appendChild(this.node);var svg=this.paper;return svg.top!=this&&R._tofront(this,svg),this},elproto.toBack=function(){if(this.removed)return this;var parent=this.node.parentNode;"a"==parent.tagName.toLowerCase()?parent.parentNode.insertBefore(this.node.parentNode,this.node.parentNode.parentNode.firstChild):parent.firstChild!=this.node&&parent.insertBefore(this.node,this.node.parentNode.firstChild),R._toback(this,this.paper);this.paper;return this},elproto.insertAfter=function(element){if(this.removed)return this;var node=element.node||element[element.length-1].node;return node.nextSibling?node.parentNode.insertBefore(this.node,node.nextSibling):node.parentNode.appendChild(this.node),R._insertafter(this,element,this.paper),this},elproto.insertBefore=function(element){if(this.removed)return this;var node=element.node||element[0].node;return node.parentNode.insertBefore(this.node,node),R._insertbefore(this,element,this.paper),this},elproto.blur=function(size){var t=this;if(0!==+size){var fltr=$("filter"),blur=$("feGaussianBlur");t.attrs.blur=size,fltr.id=R.createUUID(),$(blur,{stdDeviation:+size||1.5}),fltr.appendChild(blur),t.paper.defs.appendChild(fltr),t._blur=fltr,$(t.node,{filter:"url(#"+fltr.id+")"})}else t._blur&&(t._blur.parentNode.removeChild(t._blur),delete t._blur,delete t.attrs.blur),t.node.removeAttribute("filter");return t},R._engine.circle=function(svg,x,y,r){var el=$("circle");svg.canvas&&svg.canvas.appendChild(el);var res=new Element(el,svg);return res.attrs={cx:x,cy:y,r:r,fill:"none",stroke:"#000"},res.type="circle",$(el,res.attrs),res},R._engine.rect=function(svg,x,y,w,h,r){var el=$("rect");svg.canvas&&svg.canvas.appendChild(el);var res=new Element(el,svg);return res.attrs={x:x,y:y,width:w,height:h,r:r||0,rx:r||0,ry:r||0,fill:"none",stroke:"#000"},res.type="rect",$(el,res.attrs),res},R._engine.ellipse=function(svg,x,y,rx,ry){var el=$("ellipse");svg.canvas&&svg.canvas.appendChild(el);var res=new Element(el,svg);return res.attrs={cx:x,cy:y,rx:rx,ry:ry,fill:"none",stroke:"#000"},res.type="ellipse",$(el,res.attrs),res},R._engine.image=function(svg,src,x,y,w,h){var el=$("image");$(el,{x:x,y:y,width:w,height:h,preserveAspectRatio:"none"}),el.setAttributeNS(xlink,"href",src),svg.canvas&&svg.canvas.appendChild(el);var res=new Element(el,svg);return res.attrs={x:x,y:y,width:w,height:h,src:src},res.type="image",res},R._engine.text=function(svg,x,y,text){var el=$("text");svg.canvas&&svg.canvas.appendChild(el);var res=new Element(el,svg);return res.attrs={x:x,y:y,"text-anchor":"middle",text:text,font:R._availableAttrs.font,stroke:"none",fill:"#000"},res.type="text",setFillAndStroke(res,res.attrs),res},R._engine.setSize=function(width,height){return this.width=width||this.width,this.height=height||this.height,this.canvas.setAttribute("width",this.width),this.canvas.setAttribute("height",this.height),this._viewBox&&this.setViewBox.apply(this,this._viewBox),this},R._engine.create=function(){var con=R._getContainer.apply(0,arguments),container=con&&con.container,x=con.x,y=con.y,width=con.width,height=con.height;if(!container)throw new Error("SVG container not found.");var isFloating,cnvs=$("svg"),css="overflow:hidden;";return x=x||0,y=y||0,width=width||512,height=height||342,$(cnvs,{height:height,version:1.1,width:width,xmlns:"http://www.w3.org/2000/svg"}),1==container?(cnvs.style.cssText=css+"position:absolute;left:"+x+"px;top:"+y+"px",R._g.doc.body.appendChild(cnvs),isFloating=1):(cnvs.style.cssText=css+"position:relative",container.firstChild?container.insertBefore(cnvs,container.firstChild):container.appendChild(cnvs)),container=new R._Paper,container.width=width,container.height=height,container.canvas=cnvs,container.clear(),container._left=container._top=0,isFloating&&(container.renderfix=function(){}),container.renderfix(),container},R._engine.setViewBox=function(x,y,w,h,fit){eve("raphael.setViewBox",this,this._viewBox,[x,y,w,h,fit]);var vb,sw,size=mmax(w/this.width,h/this.height),top=this.top,aspectRatio=fit?"meet":"xMinYMin";for(null==x?(this._vbSize&&(size=1),delete this._vbSize,vb="0 0 "+this.width+S+this.height):(this._vbSize=size,vb=x+S+y+S+w+S+h),$(this.canvas,{viewBox:vb,preserveAspectRatio:aspectRatio});size&&top;)sw="stroke-width"in top.attrs?top.attrs["stroke-width"]:1,top.attr({"stroke-width":sw}),top._.dirty=1,top._.dirtyT=1,top=top.prev;return this._viewBox=[x,y,w,h,!!fit],this},R.prototype.renderfix=function(){var pos,cnvs=this.canvas,s=cnvs.style;try{pos=cnvs.getScreenCTM()||cnvs.createSVGMatrix()}catch(e){pos=cnvs.createSVGMatrix()}var left=-pos.e%1,top=-pos.f%1;(left||top)&&(left&&(this._left=(this._left+left)%1,s.left=this._left+"px"),top&&(this._top=(this._top+top)%1,s.top=this._top+"px"))},R.prototype.clear=function(){R.eve("raphael.clear",this);for(var c=this.canvas;c.firstChild;)c.removeChild(c.firstChild);this.bottom=this.top=null,(this.desc=$("desc")).appendChild(R._g.doc.createTextNode("Created with Raphaël "+R.version)),c.appendChild(this.desc),c.appendChild(this.defs=$("defs"))},R.prototype.remove=function(){eve("raphael.remove",this),this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas);for(var i in this)this[i]="function"==typeof this[i]?R._removedFactory(i):null};var setproto=R.st;for(var method in elproto)elproto[has](method)&&!setproto[has](method)&&(setproto[method]=function(methodname){return function(){var arg=arguments;return this.forEach(function(el){el[methodname].apply(el,arg)})}}(method))}}(),function(){if(R.vml){var has="hasOwnProperty",Str=String,toFloat=parseFloat,math=Math,round=math.round,mmax=math.max,mmin=math.min,abs=math.abs,fillString="fill",separator=/[, ]+/,eve=R.eve,ms=" progid:DXImageTransform.Microsoft",S=" ",E="",map={M:"m",L:"l",C:"c",Z:"x",m:"t",l:"r",c:"v",z:"x"},bites=/([clmz]),?([^clmz]*)/gi,blurregexp=/ progid:\S+Blur\([^\)]+\)/g,val=/-?[^,\s-]+/g,cssDot="position:absolute;left:0;top:0;width:1px;height:1px",zoom=21600,pathTypes={path:1,rect:1,image:1},ovalTypes={circle:1,ellipse:1},path2vml=function(path){var total=/[ahqstv]/gi,command=R._pathToAbsolute;if(Str(path).match(total)&&(command=R._path2curve),total=/[clmz]/g,command==R._pathToAbsolute&&!Str(path).match(total)){var res=Str(path).replace(bites,function(all,command,args){var vals=[],isMove="m"==command.toLowerCase(),res=map[command];return args.replace(val,function(value){isMove&&2==vals.length&&(res+=vals+map["m"==command?"l":"L"],vals=[]),vals.push(round(value*zoom))}),res+vals});return res}var p,r,pa=command(path);res=[]; for(var i=0,ii=pa.length;i<ii;i++){p=pa[i],r=pa[i][0].toLowerCase(),"z"==r&&(r="x");for(var j=1,jj=p.length;j<jj;j++)r+=round(p[j]*zoom)+(j!=jj-1?",":E);res.push(r)}return res.join(S)},compensation=function(deg,dx,dy){var m=R.matrix();return m.rotate(-deg,.5,.5),{dx:m.x(dx,dy),dy:m.y(dx,dy)}},setCoords=function(p,sx,sy,dx,dy,deg){var _=p._,m=p.matrix,fillpos=_.fillpos,o=p.node,s=o.style,y=1,flip="",kx=zoom/sx,ky=zoom/sy;if(s.visibility="hidden",sx&&sy){if(o.coordsize=abs(kx)+S+abs(ky),s.rotation=deg*(sx*sy<0?-1:1),deg){var c=compensation(deg,dx,dy);dx=c.dx,dy=c.dy}if(sx<0&&(flip+="x"),sy<0&&(flip+=" y")&&(y=-1),s.flip=flip,o.coordorigin=dx*-kx+S+dy*-ky,fillpos||_.fillsize){var fill=o.getElementsByTagName(fillString);fill=fill&&fill[0],o.removeChild(fill),fillpos&&(c=compensation(deg,m.x(fillpos[0],fillpos[1]),m.y(fillpos[0],fillpos[1])),fill.position=c.dx*y+S+c.dy*y),_.fillsize&&(fill.size=_.fillsize[0]*abs(sx)+S+_.fillsize[1]*abs(sy)),o.appendChild(fill)}s.visibility="visible"}};R.toString=function(){return"Your browser doesn’t support SVG. Falling down to VML.\nYou are running Raphaël "+this.version};var addArrow=function(o,value,isEnd){for(var values=Str(value).toLowerCase().split("-"),se=isEnd?"end":"start",i=values.length,type="classic",w="medium",h="medium";i--;)switch(values[i]){case"block":case"classic":case"oval":case"diamond":case"open":case"none":type=values[i];break;case"wide":case"narrow":h=values[i];break;case"long":case"short":w=values[i]}var stroke=o.node.getElementsByTagName("stroke")[0];stroke[se+"arrow"]=type,stroke[se+"arrowlength"]=w,stroke[se+"arrowwidth"]=h},setFillAndStroke=function(o,params){o.attrs=o.attrs||{};var node=o.node,a=o.attrs,s=node.style,newpath=pathTypes[o.type]&&(params.x!=a.x||params.y!=a.y||params.width!=a.width||params.height!=a.height||params.cx!=a.cx||params.cy!=a.cy||params.rx!=a.rx||params.ry!=a.ry||params.r!=a.r),isOval=ovalTypes[o.type]&&(a.cx!=params.cx||a.cy!=params.cy||a.r!=params.r||a.rx!=params.rx||a.ry!=params.ry),res=o;for(var par in params)params[has](par)&&(a[par]=params[par]);if(newpath&&(a.path=R._getPath[o.type](o),o._.dirty=1),params.href&&(node.href=params.href),params.title&&(node.title=params.title),params.target&&(node.target=params.target),params.cursor&&(s.cursor=params.cursor),"blur"in params&&o.blur(params.blur),(params.path&&"path"==o.type||newpath)&&(node.path=path2vml(~Str(a.path).toLowerCase().indexOf("r")?R._pathToAbsolute(a.path):a.path),"image"==o.type&&(o._.fillpos=[a.x,a.y],o._.fillsize=[a.width,a.height],setCoords(o,1,1,0,0,0))),"transform"in params&&o.transform(params.transform),isOval){var cx=+a.cx,cy=+a.cy,rx=+a.rx||+a.r||0,ry=+a.ry||+a.r||0;node.path=R.format("ar{0},{1},{2},{3},{4},{1},{4},{1}x",round((cx-rx)*zoom),round((cy-ry)*zoom),round((cx+rx)*zoom),round((cy+ry)*zoom),round(cx*zoom)),o._.dirty=1}if("clip-rect"in params){var rect=Str(params["clip-rect"]).split(separator);if(4==rect.length){rect[2]=+rect[2]+ +rect[0],rect[3]=+rect[3]+ +rect[1];var div=node.clipRect||R._g.doc.createElement("div"),dstyle=div.style;dstyle.clip=R.format("rect({1}px {2}px {3}px {0}px)",rect),node.clipRect||(dstyle.position="absolute",dstyle.top=0,dstyle.left=0,dstyle.width=o.paper.width+"px",dstyle.height=o.paper.height+"px",node.parentNode.insertBefore(div,node),div.appendChild(node),node.clipRect=div)}params["clip-rect"]||node.clipRect&&(node.clipRect.style.clip="auto")}if(o.textpath){var textpathStyle=o.textpath.style;params.font&&(textpathStyle.font=params.font),params["font-family"]&&(textpathStyle.fontFamily='"'+params["font-family"].split(",")[0].replace(/^['"]+|['"]+$/g,E)+'"'),params["font-size"]&&(textpathStyle.fontSize=params["font-size"]),params["font-weight"]&&(textpathStyle.fontWeight=params["font-weight"]),params["font-style"]&&(textpathStyle.fontStyle=params["font-style"])}if("arrow-start"in params&&addArrow(res,params["arrow-start"]),"arrow-end"in params&&addArrow(res,params["arrow-end"],1),null!=params.opacity||null!=params["stroke-width"]||null!=params.fill||null!=params.src||null!=params.stroke||null!=params["stroke-width"]||null!=params["stroke-opacity"]||null!=params["fill-opacity"]||null!=params["stroke-dasharray"]||null!=params["stroke-miterlimit"]||null!=params["stroke-linejoin"]||null!=params["stroke-linecap"]){var fill=node.getElementsByTagName(fillString),newfill=!1;if(fill=fill&&fill[0],!fill&&(newfill=fill=createNode(fillString)),"image"==o.type&&params.src&&(fill.src=params.src),params.fill&&(fill.on=!0),null!=fill.on&&"none"!=params.fill&&null!==params.fill||(fill.on=!1),fill.on&&params.fill){var isURL=Str(params.fill).match(R._ISURL);if(isURL){fill.parentNode==node&&node.removeChild(fill),fill.rotate=!0,fill.src=isURL[1],fill.type="tile";var bbox=o.getBBox(1);fill.position=bbox.x+S+bbox.y,o._.fillpos=[bbox.x,bbox.y],R._preload(isURL[1],function(){o._.fillsize=[this.offsetWidth,this.offsetHeight]})}else fill.color=R.getRGB(params.fill).hex,fill.src=E,fill.type="solid",R.getRGB(params.fill).error&&(res.type in{circle:1,ellipse:1}||"r"!=Str(params.fill).charAt())&&addGradientFill(res,params.fill,fill)&&(a.fill="none",a.gradient=params.fill,fill.rotate=!1)}if("fill-opacity"in params||"opacity"in params){var opacity=((+a["fill-opacity"]+1||2)-1)*((+a.opacity+1||2)-1)*((+R.getRGB(params.fill).o+1||2)-1);opacity=mmin(mmax(opacity,0),1),fill.opacity=opacity,fill.src&&(fill.color="none")}node.appendChild(fill);var stroke=node.getElementsByTagName("stroke")&&node.getElementsByTagName("stroke")[0],newstroke=!1;!stroke&&(newstroke=stroke=createNode("stroke")),(params.stroke&&"none"!=params.stroke||params["stroke-width"]||null!=params["stroke-opacity"]||params["stroke-dasharray"]||params["stroke-miterlimit"]||params["stroke-linejoin"]||params["stroke-linecap"])&&(stroke.on=!0),("none"==params.stroke||null===params.stroke||null==stroke.on||0==params.stroke||0==params["stroke-width"])&&(stroke.on=!1);var strokeColor=R.getRGB(params.stroke);stroke.on&&params.stroke&&(stroke.color=strokeColor.hex),opacity=((+a["stroke-opacity"]+1||2)-1)*((+a.opacity+1||2)-1)*((+strokeColor.o+1||2)-1);var width=.75*(toFloat(params["stroke-width"])||1);if(opacity=mmin(mmax(opacity,0),1),null==params["stroke-width"]&&(width=a["stroke-width"]),params["stroke-width"]&&(stroke.weight=width),width&&width<1&&(opacity*=width)&&(stroke.weight=1),stroke.opacity=opacity,params["stroke-linejoin"]&&(stroke.joinstyle=params["stroke-linejoin"]||"miter"),stroke.miterlimit=params["stroke-miterlimit"]||8,params["stroke-linecap"]&&(stroke.endcap="butt"==params["stroke-linecap"]?"flat":"square"==params["stroke-linecap"]?"square":"round"),params["stroke-dasharray"]){var dasharray={"-":"shortdash",".":"shortdot","-.":"shortdashdot","-..":"shortdashdotdot",". ":"dot","- ":"dash","--":"longdash","- .":"dashdot","--.":"longdashdot","--..":"longdashdotdot"};stroke.dashstyle=dasharray[has](params["stroke-dasharray"])?dasharray[params["stroke-dasharray"]]:E}newstroke&&node.appendChild(stroke)}if("text"==res.type){res.paper.canvas.style.display=E;var span=res.paper.span,m=100,fontSize=a.font&&a.font.match(/\d+(?:\.\d*)?(?=px)/);s=span.style,a.font&&(s.font=a.font),a["font-family"]&&(s.fontFamily=a["font-family"]),a["font-weight"]&&(s.fontWeight=a["font-weight"]),a["font-style"]&&(s.fontStyle=a["font-style"]),fontSize=toFloat(a["font-size"]||fontSize&&fontSize[0])||10,s.fontSize=fontSize*m+"px",res.textpath.string&&(span.innerHTML=Str(res.textpath.string).replace(/</g,"&#60;").replace(/&/g,"&#38;").replace(/\n/g,"<br>"));var brect=span.getBoundingClientRect();res.W=a.w=(brect.right-brect.left)/m,res.H=a.h=(brect.bottom-brect.top)/m,res.X=a.x,res.Y=a.y+res.H/2,("x"in params||"y"in params)&&(res.path.v=R.format("m{0},{1}l{2},{1}",round(a.x*zoom),round(a.y*zoom),round(a.x*zoom)+1));for(var dirtyattrs=["x","y","text","font","font-family","font-weight","font-style","font-size"],d=0,dd=dirtyattrs.length;d<dd;d++)if(dirtyattrs[d]in params){res._.dirty=1;break}switch(a["text-anchor"]){case"start":res.textpath.style["v-text-align"]="left",res.bbx=res.W/2;break;case"end":res.textpath.style["v-text-align"]="right",res.bbx=-res.W/2;break;default:res.textpath.style["v-text-align"]="center",res.bbx=0}res.textpath.style["v-text-kern"]=!0}},addGradientFill=function(o,gradient,fill){o.attrs=o.attrs||{};var pow=(o.attrs,Math.pow),type="linear",fxfy=".5 .5";if(o.attrs.gradient=gradient,gradient=Str(gradient).replace(R._radial_gradient,function(all,fx,fy){return type="radial",fx&&fy&&(fx=toFloat(fx),fy=toFloat(fy),pow(fx-.5,2)+pow(fy-.5,2)>.25&&(fy=math.sqrt(.25-pow(fx-.5,2))*(2*(fy>.5)-1)+.5),fxfy=fx+S+fy),E}),gradient=gradient.split(/\s*\-\s*/),"linear"==type){var angle=gradient.shift();if(angle=-toFloat(angle),isNaN(angle))return null}var dots=R._parseDots(gradient);if(!dots)return null;if(o=o.shape||o.node,dots.length){o.removeChild(fill),fill.on=!0,fill.method="none",fill.color=dots[0].color,fill.color2=dots[dots.length-1].color;for(var clrs=[],i=0,ii=dots.length;i<ii;i++)dots[i].offset&&clrs.push(dots[i].offset+S+dots[i].color);fill.colors=clrs.length?clrs.join():"0% "+fill.color,"radial"==type?(fill.type="gradientTitle",fill.focus="100%",fill.focussize="0 0",fill.focusposition=fxfy,fill.angle=0):(fill.type="gradient",fill.angle=(270-angle)%360),o.appendChild(fill)}return 1},Element=function(node,vml){this[0]=this.node=node,node.raphael=!0,this.id=R._oid++,node.raphaelid=this.id,this.X=0,this.Y=0,this.attrs={},this.paper=vml,this.matrix=R.matrix(),this._={transform:[],sx:1,sy:1,dx:0,dy:0,deg:0,dirty:1,dirtyT:1},!vml.bottom&&(vml.bottom=this),this.prev=vml.top,vml.top&&(vml.top.next=this),vml.top=this,this.next=null},elproto=R.el;Element.prototype=elproto,elproto.constructor=Element,elproto.transform=function(tstr){if(null==tstr)return this._.transform;var oldt,vbs=this.paper._viewBoxShift,vbt=vbs?"s"+[vbs.scale,vbs.scale]+"-1-1t"+[vbs.dx,vbs.dy]:E;vbs&&(oldt=tstr=Str(tstr).replace(/\.{3}|\u2026/g,this._.transform||E)),R._extractTransform(this,vbt+tstr);var split,matrix=this.matrix.clone(),skew=this.skew,o=this.node,isGrad=~Str(this.attrs.fill).indexOf("-"),isPatt=!Str(this.attrs.fill).indexOf("url(");if(matrix.translate(1,1),isPatt||isGrad||"image"==this.type)if(skew.matrix="1 0 0 1",skew.offset="0 0",split=matrix.split(),isGrad&&split.noRotation||!split.isSimple){o.style.filter=matrix.toFilter();var bb=this.getBBox(),bbt=this.getBBox(1),dx=bb.x-bbt.x,dy=bb.y-bbt.y;o.coordorigin=dx*-zoom+S+dy*-zoom,setCoords(this,1,1,dx,dy,0)}else o.style.filter=E,setCoords(this,split.scalex,split.scaley,split.dx,split.dy,split.rotate);else o.style.filter=E,skew.matrix=Str(matrix),skew.offset=matrix.offset();return oldt&&(this._.transform=oldt),this},elproto.rotate=function(deg,cx,cy){if(this.removed)return this;if(null!=deg){if(deg=Str(deg).split(separator),deg.length-1&&(cx=toFloat(deg[1]),cy=toFloat(deg[2])),deg=toFloat(deg[0]),null==cy&&(cx=cy),null==cx||null==cy){var bbox=this.getBBox(1);cx=bbox.x+bbox.width/2,cy=bbox.y+bbox.height/2}return this._.dirtyT=1,this.transform(this._.transform.concat([["r",deg,cx,cy]])),this}},elproto.translate=function(dx,dy){return this.removed?this:(dx=Str(dx).split(separator),dx.length-1&&(dy=toFloat(dx[1])),dx=toFloat(dx[0])||0,dy=+dy||0,this._.bbox&&(this._.bbox.x+=dx,this._.bbox.y+=dy),this.transform(this._.transform.concat([["t",dx,dy]])),this)},elproto.scale=function(sx,sy,cx,cy){if(this.removed)return this;if(sx=Str(sx).split(separator),sx.length-1&&(sy=toFloat(sx[1]),cx=toFloat(sx[2]),cy=toFloat(sx[3]),isNaN(cx)&&(cx=null),isNaN(cy)&&(cy=null)),sx=toFloat(sx[0]),null==sy&&(sy=sx),null==cy&&(cx=cy),null==cx||null==cy)var bbox=this.getBBox(1);return cx=null==cx?bbox.x+bbox.width/2:cx,cy=null==cy?bbox.y+bbox.height/2:cy,this.transform(this._.transform.concat([["s",sx,sy,cx,cy]])),this._.dirtyT=1,this},elproto.hide=function(){return!this.removed&&(this.node.style.display="none"),this},elproto.show=function(){return!this.removed&&(this.node.style.display=E),this},elproto._getBBox=function(){return this.removed?{}:{x:this.X+(this.bbx||0)-this.W/2,y:this.Y-this.H,width:this.W,height:this.H}},elproto.remove=function(){if(!this.removed&&this.node.parentNode){this.paper.__set__&&this.paper.__set__.exclude(this),R.eve.unbind("raphael.*.*."+this.id),R._tear(this,this.paper),this.node.parentNode.removeChild(this.node),this.shape&&this.shape.parentNode.removeChild(this.shape);for(var i in this)this[i]="function"==typeof this[i]?R._removedFactory(i):null;this.removed=!0}},elproto.attr=function(name,value){if(this.removed)return this;if(null==name){var res={};for(var a in this.attrs)this.attrs[has](a)&&(res[a]=this.attrs[a]);return res.gradient&&"none"==res.fill&&(res.fill=res.gradient)&&delete res.gradient,res.transform=this._.transform,res}if(null==value&&R.is(name,"string")){if(name==fillString&&"none"==this.attrs.fill&&this.attrs.gradient)return this.attrs.gradient;for(var names=name.split(separator),out={},i=0,ii=names.length;i<ii;i++)name=names[i],name in this.attrs?out[name]=this.attrs[name]:R.is(this.paper.customAttributes[name],"function")?out[name]=this.paper.customAttributes[name].def:out[name]=R._availableAttrs[name];return ii-1?out:out[names[0]]}if(this.attrs&&null==value&&R.is(name,"array")){for(out={},i=0,ii=name.length;i<ii;i++)out[name[i]]=this.attr(name[i]);return out}var params;null!=value&&(params={},params[name]=value),null==value&&R.is(name,"object")&&(params=name);for(var key in params)eve("raphael.attr."+key+"."+this.id,this,params[key]);if(params){for(key in this.paper.customAttributes)if(this.paper.customAttributes[has](key)&&params[has](key)&&R.is(this.paper.customAttributes[key],"function")){var par=this.paper.customAttributes[key].apply(this,[].concat(params[key]));this.attrs[key]=params[key];for(var subkey in par)par[has](subkey)&&(params[subkey]=par[subkey])}params.text&&"text"==this.type&&(this.textpath.string=params.text),setFillAndStroke(this,params)}return this},elproto.toFront=function(){return!this.removed&&this.node.parentNode.appendChild(this.node),this.paper&&this.paper.top!=this&&R._tofront(this,this.paper),this},elproto.toBack=function(){return this.removed?this:(this.node.parentNode.firstChild!=this.node&&(this.node.parentNode.insertBefore(this.node,this.node.parentNode.firstChild),R._toback(this,this.paper)),this)},elproto.insertAfter=function(element){return this.removed?this:(element.constructor==R.st.constructor&&(element=element[element.length-1]),element.node.nextSibling?element.node.parentNode.insertBefore(this.node,element.node.nextSibling):element.node.parentNode.appendChild(this.node),R._insertafter(this,element,this.paper),this)},elproto.insertBefore=function(element){return this.removed?this:(element.constructor==R.st.constructor&&(element=element[0]),element.node.parentNode.insertBefore(this.node,element.node),R._insertbefore(this,element,this.paper),this)},elproto.blur=function(size){var s=this.node.runtimeStyle,f=s.filter;return f=f.replace(blurregexp,E),0!==+size?(this.attrs.blur=size,s.filter=f+S+ms+".Blur(pixelradius="+(+size||1.5)+")",s.margin=R.format("-{0}px 0 0 -{0}px",round(+size||1.5))):(s.filter=f,s.margin=0,delete this.attrs.blur),this},R._engine.path=function(pathString,vml){var el=createNode("shape");el.style.cssText=cssDot,el.coordsize=zoom+S+zoom,el.coordorigin=vml.coordorigin;var p=new Element(el,vml),attr={fill:"none",stroke:"#000"};pathString&&(attr.path=pathString),p.type="path",p.path=[],p.Path=E,setFillAndStroke(p,attr),vml.canvas.appendChild(el);var skew=createNode("skew");return skew.on=!0,el.appendChild(skew),p.skew=skew,p.transform(E),p},R._engine.rect=function(vml,x,y,w,h,r){var path=R._rectPath(x,y,w,h,r),res=vml.path(path),a=res.attrs;return res.X=a.x=x,res.Y=a.y=y,res.W=a.width=w,res.H=a.height=h,a.r=r,a.path=path,res.type="rect",res},R._engine.ellipse=function(vml,x,y,rx,ry){var res=vml.path();res.attrs;return res.X=x-rx,res.Y=y-ry,res.W=2*rx,res.H=2*ry,res.type="ellipse",setFillAndStroke(res,{cx:x,cy:y,rx:rx,ry:ry}),res},R._engine.circle=function(vml,x,y,r){var res=vml.path();res.attrs;return res.X=x-r,res.Y=y-r,res.W=res.H=2*r,res.type="circle",setFillAndStroke(res,{cx:x,cy:y,r:r}),res},R._engine.image=function(vml,src,x,y,w,h){var path=R._rectPath(x,y,w,h),res=vml.path(path).attr({stroke:"none"}),a=res.attrs,node=res.node,fill=node.getElementsByTagName(fillString)[0];return a.src=src,res.X=a.x=x,res.Y=a.y=y,res.W=a.width=w,res.H=a.height=h,a.path=path,res.type="image",fill.parentNode==node&&node.removeChild(fill),fill.rotate=!0,fill.src=src,fill.type="tile",res._.fillpos=[x,y],res._.fillsize=[w,h],node.appendChild(fill),setCoords(res,1,1,0,0,0),res},R._engine.text=function(vml,x,y,text){var el=createNode("shape"),path=createNode("path"),o=createNode("textpath");x=x||0,y=y||0,text=text||"",path.v=R.format("m{0},{1}l{2},{1}",round(x*zoom),round(y*zoom),round(x*zoom)+1),path.textpathok=!0,o.string=Str(text),o.on=!0,el.style.cssText=cssDot,el.coordsize=zoom+S+zoom,el.coordorigin="0 0";var p=new Element(el,vml),attr={fill:"#000",stroke:"none",font:R._availableAttrs.font,text:text};p.shape=el,p.path=path,p.textpath=o,p.type="text",p.attrs.text=Str(text),p.attrs.x=x,p.attrs.y=y,p.attrs.w=1,p.attrs.h=1,setFillAndStroke(p,attr),el.appendChild(o),el.appendChild(path),vml.canvas.appendChild(el);var skew=createNode("skew");return skew.on=!0,el.appendChild(skew),p.skew=skew,p.transform(E),p},R._engine.setSize=function(width,height){var cs=this.canvas.style;return this.width=width,this.height=height,width==+width&&(width+="px"),height==+height&&(height+="px"),cs.width=width,cs.height=height,cs.clip="rect(0 "+width+" "+height+" 0)",this._viewBox&&R._engine.setViewBox.apply(this,this._viewBox),this},R._engine.setViewBox=function(x,y,w,h,fit){R.eve("raphael.setViewBox",this,this._viewBox,[x,y,w,h,fit]);var H,W,width=this.width,height=this.height,size=1/mmax(w/width,h/height);return fit&&(H=height/h,W=width/w,w*H<width&&(x-=(width-w*H)/2/H),h*W<height&&(y-=(height-h*W)/2/W)),this._viewBox=[x,y,w,h,!!fit],this._viewBoxShift={dx:-x,dy:-y,scale:size},this.forEach(function(el){el.transform("...")}),this};var createNode;R._engine.initWin=function(win){var doc=win.document;doc.createStyleSheet().addRule(".rvml","behavior:url(#default#VML)");try{!doc.namespaces.rvml&&doc.namespaces.add("rvml","urn:schemas-microsoft-com:vml"),createNode=function(tagName){return doc.createElement("<rvml:"+tagName+' class="rvml">')}}catch(e){createNode=function(tagName){return doc.createElement("<"+tagName+' xmlns="urn:schemas-microsoft.com:vml" class="rvml">')}}},R._engine.initWin(R._g.win),R._engine.create=function(){var con=R._getContainer.apply(0,arguments),container=con.container,height=con.height,width=con.width,x=con.x,y=con.y;if(!container)throw new Error("VML container not found.");var res=new R._Paper,c=res.canvas=R._g.doc.createElement("div"),cs=c.style;return x=x||0,y=y||0,width=width||512,height=height||342,res.width=width,res.height=height,width==+width&&(width+="px"),height==+height&&(height+="px"),res.coordsize=1e3*zoom+S+1e3*zoom,res.coordorigin="0 0",res.span=R._g.doc.createElement("span"),res.span.style.cssText="position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;",c.appendChild(res.span),cs.cssText=R.format("top:0;left:0;width:{0};height:{1};display:inline-block;position:relative;clip:rect(0 {0} {1} 0);overflow:hidden",width,height),1==container?(R._g.doc.body.appendChild(c),cs.left=x+"px",cs.top=y+"px",cs.position="absolute"):container.firstChild?container.insertBefore(c,container.firstChild):container.appendChild(c),res.renderfix=function(){},res},R.prototype.clear=function(){R.eve("raphael.clear",this),this.canvas.innerHTML=E,this.span=R._g.doc.createElement("span"),this.span.style.cssText="position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;display:inline;",this.canvas.appendChild(this.span),this.bottom=this.top=null},R.prototype.remove=function(){R.eve("raphael.remove",this),this.canvas.parentNode.removeChild(this.canvas);for(var i in this)this[i]="function"==typeof this[i]?R._removedFactory(i):null;return!0};var setproto=R.st;for(var method in elproto)elproto[has](method)&&!setproto[has](method)&&(setproto[method]=function(methodname){return function(){var arg=arguments;return this.forEach(function(el){el[methodname].apply(el,arg)})}}(method))}}(),oldRaphael.was?g.win.Raphael=R:Raphael=R,R}),window.ABCJS||(window.ABCJS={}),function(){"use strict";function hasClass(element,cls){var elClass=element.getAttribute("class"),rclass=/[\t\r\n\f]/g,className=" "+cls+" ";return 1===element.nodeType&&(" "+elClass+" ").replace(rclass," ").indexOf(className)>=0}function getAllElementsByClasses(startingEl,class1,class2){for(var els=startingEl.getElementsByClassName(class1),ret=[],i=0;i<els.length;i++)hasClass(els[i],class2)&&ret.push(els[i]);return ret}function getCssRule(selector){for(var rule,i=0;i<document.styleSheets.length&&void 0===rule;i++){var css=document.styleSheets[i],rules=css.rules;if(rules)for(var j=0;j<rules.length&&void 0===rule;j++)rules[j].selectorText&&rules[j].selectorText===selector&&(rule=rules[j])}return rule?rule:(document.styleSheets[0].insertRule(selector+" { }",1),getCssRule(selector))}function getBeatsPerMinute(tune,options){var bpm;return bpm=options.bpm?options.bpm:tune&&tune.metaText&&tune.metaText.tempo&&tune.metaText.tempo.bpm?tune.metaText.tempo.bpm:120}function setMargin(margin){cssRule.style.marginTop=-margin+"px",currentMargin=margin}var scrollTimer,animateTimer,cssRule,currentMargin,animationTarget,shouldResetOverflow,cursor,stopNextTime=!1;ABCJS.startAnimation=function(paper,tune,options){function scrolling(){var currentPosition=paper.style.marginLeft;currentPosition=""===currentPosition?0:parseInt(currentPosition),currentPosition-=distance,paper.style.marginLeft=currentPosition+"px",currentPosition>outer.offsetWidth-paper.scrollWidth&&(scrollTimer=setTimeout(scrolling,interval))}function processMeasureHider(lineNum,measureNum){var els=getAllElementsByClasses(paper,"l"+lineNum,"m"+measureNum);if(els.length>0)for(var i=0;i<els.length;i++){var el=els[i];hasClass(el,"bar")||(el.style.display="none")}}function addVerticalInfo(timingEvents){for(var lastBarTop,lastBarBottom,lastEventTop,lastEventBottom,e=timingEvents.length-1;e>=0;e--){var ev=timingEvents[e];"bar"===ev.type?(ev.top=lastEventTop,ev.nextTop=lastBarTop,lastBarTop=lastEventTop,ev.bottom=lastEventBottom,ev.nextBottom=lastBarBottom,lastBarBottom=lastEventBottom):"event"===ev.type&&(lastEventTop=ev.top,lastEventBottom=ev.top+ev.height)}}function makeSortedArray(hash){var arr=[];for(var k in hash)hash.hasOwnProperty(k)&&arr.push(hash[k]);return arr=arr.sort(function(a,b){var diff=a.time-b.time;return 0!==diff?diff:"bar"===a.type?-1:1})}function setupEvents(engraver){for(var eventHash={},time=0,isTiedState=!1,line=0;line<engraver.staffgroups.length;line++){var group=engraver.staffgroups[line],voices=group.voices,firstStaff=group.staffs[0],middleC=firstStaff.absoluteY,top=middleC-firstStaff.top*ABCJS.write.spacing.STEP,lastStaff=group.staffs[group.staffs.length-1];middleC=lastStaff.absoluteY;for(var bottom=middleC-lastStaff.bottom*ABCJS.write.spacing.STEP,height=bottom-top,maxVoiceTime=0,v=0;v<voices.length;v++){for(var voiceTime=time,elements=voices[v].children,elem=0;elem<elements.length;elem++){var element=elements[elem];if(element.hint)break;if(element.duration>0){var isTiedToNext=element.startTie;isTiedState?isTiedToNext||(isTiedState=!1):(eventHash["event"+voiceTime]?eventHash["event"+voiceTime].left=Math.min(eventHash["event"+voiceTime].left,element.x):eventHash["event"+voiceTime]={type:"event",time:voiceTime,top:top,height:height,left:element.x,width:element.w},isTiedToNext&&(isTiedState=!0)),voiceTime+=element.duration}if("bar"===element.type&&(0===timingEvents.length||"bar"!==timingEvents[timingEvents.length-1])&&element.elemset&&element.elemset.length>0&&element.elemset[0].attrs){for(var lineNum,measureNum,klass=element.elemset[0].attrs.class,arr=klass.split(" "),i=0;i<arr.length;i++){var match=/m(\d+)/.exec(arr[i]);match&&(measureNum=match[1]),match=/l(\d+)/.exec(arr[i]),match&&(lineNum=match[1])}eventHash["bar"+voiceTime]={type:"bar",time:voiceTime,lineNum:lineNum,measureNum:measureNum}}}maxVoiceTime=Math.max(maxVoiceTime,voiceTime)}time=maxVoiceTime}timingEvents=makeSortedArray(eventHash),totalBeats=timingEvents[timingEvents.length-1].time/beatLength,options.scrollVertical&&addVerticalInfo(timingEvents)}function isEndOfLine(currentNote){return currentNote.top!==currentNote.nextTop&&void 0!==currentNote.nextTop}function shouldScroll(outer,scrollPos,currentNote){var height=parseInt(outer.clientHeight,10),isVisible=currentNote.nextBottom-scrollPos<height;return!isVisible}function processShowCursor(){var currentNote=timingEvents.shift();return currentNote?"bar"===currentNote.type?(options.scrollVertical&&isEndOfLine(currentNote)&&shouldScroll(outer,currentMargin,currentNote)&&setTimeout(function(){setMargin(currentNote.nextTop)},millisecondsPerHalfMeasure),options.hideFinishedMeasures&&processMeasureHider(currentNote.lineNum,currentNote.measureNum),timingEvents.length>0?timingEvents[0].time/beatLength:0):(options.scrollHint&&lastTop!==currentNote.top&&(lastTop=currentNote.top,setMargin(lastTop)),options.showCursor&&cursor.css({left:currentNote.left+"px",top:currentNote.top+"px",width:currentNote.width+"px",height:currentNote.height+"px"}),timingEvents.length>0?timingEvents[0].time/beatLength:(stopNextTime=!0,0)):(stopNextTime=!0,0)}function processNext(){if(stopNextTime)return void ABCJS.stopAnimation();var currentTime=(new Date).getTime();if(isPaused)return void(pausedDifference=currentTime-pausedTime);var nextTimeInBeats=processShowCursor(),nextTimeInMilliseconds=nextTimeInBeats/beatsPerMillisecond,interval=startTime+nextTimeInMilliseconds-currentTime;interval<=0?processNext():animateTimer=setTimeout(processNext,interval)}if(void 0===paper.getElementsByClassName)return void console.error("ABCJS.startAnimation: The first parameter must be a regular DOM element. (Did you pass a jQuery object or an ID?)");if(void 0===tune.getBeatLength)return void console.error("ABCJS.startAnimation: The second parameter must be a single tune. (Did you pass the entire array of tunes?)");if((options.scrollHorizontal||options.scrollVertical||options.scrollHint)&&(hasClass(paper,"abcjs-inner")||(paper.scrollTop=0,paper.style.overflow="hidden",paper=paper.children[0]),!hasClass(paper,"abcjs-inner")))return void console.error("ABCJS.startAnimation: When using scrollHorizontal/scrollVertical/scrollHint, the music must have been rendered using viewportHorizontal/viewportVertical.");ABCJS.stopAnimation(),animationTarget=paper,shouldResetOverflow=options.scrollVertical||options.scrollHint,options.showCursor&&(cursor=$('<div class="cursor" style="position: absolute;"></div>'),$(paper).append(cursor),$(paper).css({position:"relative"})),stopNextTime=!1;var millisecondsPerHalfMeasure,beatsPerMinute=getBeatsPerMinute(tune,options),beatsPerMillisecond=beatsPerMinute/6e4,beatLength=tune.getBeatLength(),totalBeats=0;if(options.scrollVertical){var millisecondsPerBeat=1/beatsPerMillisecond,beatsPerMeasure=1/beatLength,millisecondsPerMeasure=millisecondsPerBeat*beatsPerMeasure;millisecondsPerHalfMeasure=millisecondsPerMeasure/2,cssRule=getCssRule(".abcjs-inner")}var startTime,pausedTime,pausedDifference,isPaused=!1,initialWait=2700,interval=11,distance=1,outer=paper.parentNode;options.scrollHorizontal&&(paper.style.marginLeft="0px",scrollTimer=setTimeout(scrolling,initialWait));var timingEvents=[];setupEvents(tune.engraver);var lastTop=-1;$(outer).find(".abcjs-inner");currentMargin=0,options.scrollVertical&&setMargin(0),startTime=new Date,startTime=startTime.getTime(),isPaused=!1,processNext(),ABCJS.pauseAnimation=function(pause){if(pause&&!isPaused)isPaused=!0,pausedTime=(new Date).getTime();else if(!pause&&isPaused){var nowTime=(new Date).getTime(),elapsedTimeWhenPaused=nowTime-pausedTime;startTime+=elapsedTimeWhenPaused,pausedTime=void 0,isPaused=!1,animateTimer=setTimeout(processNext,pausedDifference),pausedDifference=void 0}}},ABCJS.stopAnimation=function(){clearTimeout(animateTimer),clearTimeout(scrollTimer),cursor&&(cursor.remove(),cursor=null),shouldResetOverflow&&(animationTarget&&animationTarget.parentNode&&(animationTarget.parentNode.style.overflowY="auto"),setMargin(0))}}(),window.ABCJS||(window.ABCJS={}),function(){"use strict";function renderEngine(callback,output,abc,parserParams,renderParams){var ret=[],isArray=function(testObject){return testObject&&!testObject.propertyIsEnumerable("length")&&"object"==typeof testObject&&"number"==typeof testObject.length};if(void 0!==output&&void 0!==abc){isArray(output)||(output=[output]),void 0===parserParams&&(parserParams={}),void 0===renderParams&&(renderParams={});for(var currentTune=renderParams.startingTune?renderParams.startingTune:0,book=new ABCJS.TuneBook(abc),abcParser=new window.ABCJS.parse.Parse,i=0;i<output.length;i++){var div=output[i];if("string"==typeof div&&(div=document.getElementById(div)),div&&(div.innerHTML="",currentTune<book.tunes.length)){abcParser.parse(book.tunes[currentTune].abc,parserParams);var tune=abcParser.getTune();ret.push(tune),callback(div,tune,i)}currentTune++}return ret}}function resizeOuter(){var width=window.innerWidth;for(var id in resizeDivs)if(resizeDivs.hasOwnProperty(id)){var outer=resizeDivs[id],ofs=outer.offsetLeft;width-=2*ofs,outer.style.width=width+"px"}}function renderOne(div,tune,renderParams,engraverParams){var width=renderParams.width?renderParams.width:800;renderParams.viewportHorizontal?(div.innerHTML='<div class="abcjs-inner"></div>',renderParams.scrollHorizontal?(div.style.overflowX="auto",div.style.overflowY="hidden"):div.style.overflow="hidden",resizeDivs[div.id]=div,div=div.children[0]):renderParams.viewportVertical&&(div.innerHTML='<div class="abcjs-inner scroll-amount"></div>',div.style.overflowX="hidden",div.style.overflowY="auto",div=div.children[0]);var paper=Raphael(div,width,400);void 0===engraverParams&&(engraverParams={});var engraver_controller=new ABCJS.write.EngraverController(paper,engraverParams);if(engraver_controller.engraveABC(tune),tune.engraver=engraver_controller,renderParams.viewportVertical||renderParams.viewportHorizontal){var parent=div.parentNode;parent.style.width=div.style.width}}function renderEachLineSeparately(div,tune,renderParams,engraverParams){function initializeTuneLine(tune){return{formatting:tune.formatting,media:tune.media,version:tune.version,metaText:{},lines:[]}}for(var tuneLine,tunes=[],i=0;i<tune.lines.length;i++){var line=tune.lines[i];tuneLine||(tuneLine=initializeTuneLine(tune)),0===i&&(tuneLine.metaText.tempo=tune.metaText.tempo,tuneLine.metaText.title=tune.metaText.title,tuneLine.metaText.header=tune.metaText.header,tuneLine.metaText.rhythm=tune.metaText.rhythm,tuneLine.metaText.origin=tune.metaText.origin,tuneLine.metaText.composer=tune.metaText.composer,tuneLine.metaText.author=tune.metaText.author,tuneLine.metaText.partOrder=tune.metaText.partOrder),tuneLine.lines.push(line),line.staff&&(tunes.push(tuneLine),tuneLine=void 0)}if(tuneLine)for(var lastLine=tunes[tunes.length-1],j=0;j<tuneLine.lines.length;j++)lastLine.lines.push(tuneLine.lines[j]);tuneLine=tunes[tunes.length-1],tuneLine.metaText.unalignedWords=tune.metaText.unalignedWords,tuneLine.metaText.book=tune.metaText.book,tuneLine.metaText.source=tune.metaText.source,tuneLine.metaText.discography=tune.metaText.discography,tuneLine.metaText.notes=tune.metaText.notes,tuneLine.metaText.transcription=tune.metaText.transcription,tuneLine.metaText.history=tune.metaText.history,tuneLine.metaText["abc-copyright"]=tune.metaText["abc-copyright"],tuneLine.metaText["abc-creator"]=tune.metaText["abc-creator"],tuneLine.metaText["abc-edited-by"]=tune.metaText["abc-edited-by"],tuneLine.metaText.footer=tune.metaText.footer;var eParamsFirst=JSON.parse(JSON.stringify(engraverParams)),eParamsMid=JSON.parse(JSON.stringify(engraverParams)),eParamsLast=JSON.parse(JSON.stringify(engraverParams)); eParamsFirst.paddingbottom=-20,eParamsMid.paddingbottom=-20,eParamsMid.paddingtop=10,eParamsLast.paddingtop=10;for(var k=0;k<tunes.length;k++){var lineEl=document.createElement("div");div.appendChild(lineEl);var ep=0===k?eParamsFirst:k===tunes.length-1?eParamsLast:eParamsMid;renderOne(lineEl,tunes[k],renderParams,ep)}}ABCJS.numberOfTunes=function(abc){var tunes=abc.split("\nX:"),num=tunes.length;return 0===num&&(num=1),num},ABCJS.TuneBook=function(book){var This=this,directives="";book=window.ABCJS.parse.strip(book);for(var tunes=book.split("\nX:"),i=1;i<tunes.length;i++)tunes[i]="X:"+tunes[i];var pos=0;if(This.tunes=[],window.ABCJS.parse.each(tunes,function(tune){This.tunes.push({abc:tune,startPos:pos}),pos+=tune.length}),This.tunes.length>1&&!window.ABCJS.parse.startsWith(This.tunes[0].abc,"X:")){var dir=This.tunes.shift(),arrDir=dir.abc.split("\n");window.ABCJS.parse.each(arrDir,function(line){window.ABCJS.parse.startsWith(line,"%%")&&(directives+=line+"\n")})}This.header=directives,window.ABCJS.parse.each(This.tunes,function(tune){var end=tune.abc.indexOf("\n\n");end>0&&(tune.abc=tune.abc.substring(0,end)),tune.pure=tune.abc,tune.abc=directives+tune.abc;var title=tune.pure.split("T:");title.length>1?(title=title[1].split("\n"),tune.title=title[0].replace(/^\s+|\s+$/g,"")):tune.title="";var id=tune.pure.substring(2,tune.pure.indexOf("\n"));tune.id=id.replace(/^\s+|\s+$/g,"")})},ABCJS.TuneBook.prototype.getTuneById=function(id){for(var i=0;i<this.tunes.length;i++)if(this.tunes[i].id===id)return this.tunes[i];return null},ABCJS.TuneBook.prototype.getTuneByTitle=function(title){for(var i=0;i<this.tunes.length;i++)if(this.tunes[i].title===title)return this.tunes[i];return null};var resizeDivs={};window.addEventListener("resize",resizeOuter),window.addEventListener("orientationChange",resizeOuter),ABCJS.renderAbc=function(output,abc,parserParams,engraverParams,renderParams){function callback(div,tune){!renderParams.oneSvgPerLine||tune.lines.length<2?renderOne(div,tune,renderParams,engraverParams):renderEachLineSeparately(div,tune,renderParams,engraverParams)}return void 0===renderParams&&(renderParams={}),renderEngine(callback,output,abc,parserParams,renderParams)},ABCJS.renderMidi=function(output,abc,parserParams,midiParams,renderParams){function callback(div,tune,index){var html="",midi=window.ABCJS.midi.create(tune,midiParams);if(midiParams.generateInline){var inlineMidi=midi.inline?midi.inline:midi;html+=window.ABCJS.midi.generateMidiControls(tune,midiParams,inlineMidi,index)}if(midiParams.generateDownload){var downloadMidi=midi.download?midi.download:midi;html+=window.ABCJS.midi.generateMidiDownloadLink(tune,midiParams,downloadMidi,index)}div.innerHTML=html;var find=function(element,cls){var els=element.getElementsByClassName(cls);return 0===els.length?null:els[0]};if(midiParams.generateInline&&(midiParams.animate||midiParams.listener)){var parent=find(div,"abcjs-inline-midi");if(parent.abcjsTune=tune,parent.abcjsListener=midiParams.listener,parent.abcjsQpm=midiParams.qpm,midiParams.animate){var drumIntro=midiParams.drumIntro?midiParams.drumIntro:0;parent.abcjsAnimate=midiParams.animate.listener,parent.abcjsTune=midiParams.animate.target,parent.abcjsTune.setTiming(midiParams.qpm,drumIntro)}}if(midiParams.generateInline&&midiParams.inlineControls&&midiParams.inlineControls.startPlaying){var startButton=find(div,"abcjs-midi-start");window.ABCJS.midi.startPlaying(startButton)}}return void 0===midiParams&&(midiParams={}),void 0===midiParams.generateInline&&(midiParams.generateInline=!0),midiParams.inlineControls&&(midiParams.inlineControls.selectionToggle=!1),renderEngine(callback,output,abc,parserParams,renderParams)}}(),window.ABCJS||(window.ABCJS={}),window.ABCJS.data||(window.ABCJS.data={}),window.ABCJS.data.Tune=function(){function addVerticalInfo(timingEvents){for(var lastBarTop,lastBarBottom,lastEventTop,lastEventBottom,e=timingEvents.length-1;e>=0;e--){var ev=timingEvents[e];"bar"===ev.type?(ev.top=lastEventTop,ev.nextTop=lastBarTop,lastBarTop=lastEventTop,ev.bottom=lastEventBottom,ev.nextBottom=lastBarBottom,lastBarBottom=lastEventBottom):"event"===ev.type&&(lastEventTop=ev.top,lastEventBottom=ev.top+ev.height)}}function makeSortedArray(hash){var arr=[];for(var k in hash)hash.hasOwnProperty(k)&&arr.push(hash[k]);return arr=arr.sort(function(a,b){var diff=a.seconds-b.seconds;return 0!==diff?diff:"bar"===a.type?-1:1})}this.getBeatLength=function(){for(var i=0;i<this.lines.length;i++)if(this.lines[i].staff)for(var j=0;j<this.lines[i].staff.length;j++)if(this.lines[i].staff[j].meter){var meter=this.lines[i].staff[j].meter;if("specified"===meter.type){if(meter.value.length>0){var num=parseInt(meter.value[0].num,10),den=parseInt(meter.value[0].den,10);return 6===num&&8===den?3/8:9===num&&8===den?3/8:12===num&&8===den?3/8:1/den}return null}return"cut_time"===meter.type?.5:.25}return null},this.reset=function(){this.version="1.0.1",this.media="screen",this.metaText={},this.formatting={},this.lines=[],this.staffNum=0,this.voiceNum=0,this.lineNum=0},this.cleanUp=function(defWidth,defLength,barsperstaff,staffnonote,currSlur){function cleanUpSlursInLine(line){for(var x,addEndSlur=function(obj,num,chordPos){if(void 0===currSlur[chordPos]){for(x=0;x<currSlur.length;x++)if(void 0!==currSlur[x]){chordPos=x;break}if(void 0===currSlur[chordPos]){var offNum=100*chordPos+1;window.ABCJS.parse.each(obj.endSlur,function(x){offNum===x&&--offNum}),currSlur[chordPos]=[offNum]}}for(var slurNum,i=0;i<num;i++)slurNum=currSlur[chordPos].pop(),obj.endSlur.push(slurNum);return 0===currSlur[chordPos].length&&delete currSlur[chordPos],slurNum},addStartSlur=function(obj,num,chordPos,usedNums){obj.startSlur=[],void 0===currSlur[chordPos]&&(currSlur[chordPos]=[]);for(var nextNum=100*chordPos+1,i=0;i<num;i++)usedNums&&(window.ABCJS.parse.each(usedNums,function(x){nextNum===x&&++nextNum}),window.ABCJS.parse.each(usedNums,function(x){nextNum===x&&++nextNum}),window.ABCJS.parse.each(usedNums,function(x){nextNum===x&&++nextNum})),window.ABCJS.parse.each(currSlur[chordPos],function(x){nextNum===x&&++nextNum}),window.ABCJS.parse.each(currSlur[chordPos],function(x){nextNum===x&&++nextNum}),currSlur[chordPos].push(nextNum),obj.startSlur.push({label:nextNum}),nextNum++},i=0;i<line.length;i++){var el=line[i];if("note"===el.el_type){if(el.gracenotes)for(var g=0;g<el.gracenotes.length;g++){if(el.gracenotes[g].endSlur){var gg=el.gracenotes[g].endSlur;el.gracenotes[g].endSlur=[];for(var ggg=0;ggg<gg;ggg++)addEndSlur(el.gracenotes[g],1,20)}el.gracenotes[g].startSlur&&(x=el.gracenotes[g].startSlur,addStartSlur(el.gracenotes[g],x,20))}if(el.endSlur&&(x=el.endSlur,el.endSlur=[],addEndSlur(el,x,0)),el.startSlur&&(x=el.startSlur,addStartSlur(el,x,0)),el.pitches){for(var usedNums=[],p=0;p<el.pitches.length;p++)if(el.pitches[p].endSlur){var k=el.pitches[p].endSlur;el.pitches[p].endSlur=[];for(var j=0;j<k;j++){var slurNum=addEndSlur(el.pitches[p],1,p+1);usedNums.push(slurNum)}}for(p=0;p<el.pitches.length;p++)el.pitches[p].startSlur&&(x=el.pitches[p].startSlur,addStartSlur(el.pitches[p],x,p+1,usedNums));el.gracenotes&&el.pitches[0].endSlur&&100===el.pitches[0].endSlur[0]&&el.pitches[0].startSlur&&(el.gracenotes[0].endSlur?el.gracenotes[0].endSlur.push(el.pitches[0].startSlur[0].label):el.gracenotes[0].endSlur=[el.pitches[0].startSlur[0].label],1===el.pitches[0].endSlur.length?delete el.pitches[0].endSlur:100===el.pitches[0].endSlur[0]?el.pitches[0].endSlur.shift():100===el.pitches[0].endSlur[el.pitches[0].endSlur.length-1]&&el.pitches[0].endSlur.pop(),1===currSlur[1].length?delete currSlur[1]:currSlur[1].pop())}}}}function fixClefPlacement(el){window.ABCJS.parse.parseKeyVoice.fixClef(el)}function getNextMusicLine(lines,currentLine){for(currentLine++;lines.length>currentLine;){if(lines[currentLine].staff)return lines[currentLine];currentLine++}return null}this.closeLine();var i,s,v,anyDeleted=!1;for(i=0;i<this.lines.length;i++)if(void 0!==this.lines[i].staff){var hasAny=!1;for(s=0;s<this.lines[i].staff.length;s++)if(void 0===this.lines[i].staff[s])anyDeleted=!0,this.lines[i].staff[s]=null;else for(v=0;v<this.lines[i].staff[s].voices.length;v++)void 0===this.lines[i].staff[s].voices[v]?this.lines[i].staff[s].voices[v]=[]:this.containsNotes(this.lines[i].staff[s].voices[v])&&(hasAny=!0);hasAny||(this.lines[i]=null,anyDeleted=!0)}if(anyDeleted&&(this.lines=window.ABCJS.parse.compact(this.lines),window.ABCJS.parse.each(this.lines,function(line){line.staff&&(line.staff=window.ABCJS.parse.compact(line.staff))})),barsperstaff)for(i=0;i<this.lines.length;i++)if(void 0!==this.lines[i].staff)for(s=0;s<this.lines[i].staff.length;s++)for(v=0;v<this.lines[i].staff[s].voices.length;v++)for(var barNumThisLine=0,n=0;n<this.lines[i].staff[s].voices[v].length;n++)if("bar"===this.lines[i].staff[s].voices[v][n].el_type&&(barNumThisLine++,barNumThisLine>=barsperstaff&&n<this.lines[i].staff[s].voices[v].length-1)){if(i===this.lines.length-1){var cp=JSON.parse(JSON.stringify(this.lines[i]));this.lines.push(window.ABCJS.parse.clone(cp));for(var ss=0;ss<this.lines[i+1].staff.length;ss++)for(var vv=0;vv<this.lines[i+1].staff[ss].voices.length;vv++)this.lines[i+1].staff[ss].voices[vv]=[]}var startElement=n+1,section=this.lines[i].staff[s].voices[v].slice(startElement);this.lines[i].staff[s].voices[v]=this.lines[i].staff[s].voices[v].slice(0,startElement),this.lines[i+1].staff[s].voices[v]=section.concat(this.lines[i+1].staff[s].voices[v])}if(barsperstaff){for(anyDeleted=!1,i=0;i<this.lines.length;i++)if(void 0!==this.lines[i].staff)for(s=0;s<this.lines[i].staff.length;s++){var keepThis=!1;for(v=0;v<this.lines[i].staff[s].voices.length;v++)this.containsNotesStrict(this.lines[i].staff[s].voices[v])&&(keepThis=!0);keepThis||(anyDeleted=!0,this.lines[i].staff[s]=null)}anyDeleted&&window.ABCJS.parse.each(this.lines,function(line){line.staff&&(line.staff=window.ABCJS.parse.compact(line.staff))})}for(i=0;i<this.lines.length;i++)if(this.lines[i].staff)for(s=0;s<this.lines[i].staff.length;s++)delete this.lines[i].staff[s].workingClef;for(this.lineNum=0;this.lineNum<this.lines.length;this.lineNum++){var staff=this.lines[this.lineNum].staff;if(staff)for(this.staffNum=0;this.staffNum<staff.length;this.staffNum++)for(staff[this.staffNum].clef&&fixClefPlacement(staff[this.staffNum].clef),this.voiceNum=0;this.voiceNum<staff[this.staffNum].voices.length;this.voiceNum++){var voice=staff[this.staffNum].voices[this.voiceNum];cleanUpSlursInLine(voice);for(var j=0;j<voice.length;j++)"clef"===voice[j].el_type&&fixClefPlacement(voice[j]);if(voice.length>0&&voice[voice.length-1].barNumber){var nextLine=getNextMusicLine(this.lines,this.lineNum);nextLine&&(nextLine.staff[0].barNumber=voice[voice.length-1].barNumber),delete voice[voice.length-1].barNumber}}}return this.formatting.pagewidth||(this.formatting.pagewidth=defWidth),this.formatting.pageheight||(this.formatting.pageheight=defLength),delete this.staffNum,delete this.voiceNum,delete this.lineNum,delete this.potentialStartBeam,delete this.potentialEndBeam,delete this.vskipPending,currSlur},this.reset(),this.getLastNote=function(){if(this.lines[this.lineNum]&&this.lines[this.lineNum].staff&&this.lines[this.lineNum].staff[this.staffNum]&&this.lines[this.lineNum].staff[this.staffNum].voices[this.voiceNum])for(var i=this.lines[this.lineNum].staff[this.staffNum].voices[this.voiceNum].length-1;i>=0;i--){var el=this.lines[this.lineNum].staff[this.staffNum].voices[this.voiceNum][i];if("note"===el.el_type)return el}return null},this.addTieToLastNote=function(){var el=this.getLastNote();return!!(el&&el.pitches&&el.pitches.length>0)&&(el.pitches[0].startTie={},!0)},this.getDuration=function(el){return el.duration?el.duration:0},this.closeLine=function(){this.potentialStartBeam&&this.potentialEndBeam&&(this.potentialStartBeam.startBeam=!0,this.potentialEndBeam.endBeam=!0),delete this.potentialStartBeam,delete this.potentialEndBeam},this.appendElement=function(type,startChar,endChar,hashParams){var This=this,pushNote=function(hp){if(void 0!==hp.pitches){var mid=This.lines[This.lineNum].staff[This.staffNum].workingClef.verticalPos;window.ABCJS.parse.each(hp.pitches,function(p){p.verticalPos=p.pitch-mid})}if(void 0!==hp.gracenotes){var mid2=This.lines[This.lineNum].staff[This.staffNum].workingClef.verticalPos;window.ABCJS.parse.each(hp.gracenotes,function(p){p.verticalPos=p.pitch-mid2})}This.lines[This.lineNum].staff[This.staffNum].voices[This.voiceNum].push(hp)};hashParams.el_type=type,null!==startChar&&(hashParams.startChar=startChar),null!==endChar&&(hashParams.endChar=endChar);var endBeamHere=function(){This.potentialStartBeam.startBeam=!0,hashParams.endBeam=!0,delete This.potentialStartBeam,delete This.potentialEndBeam},endBeamLast=function(){void 0!==This.potentialStartBeam&&void 0!==This.potentialEndBeam&&(This.potentialStartBeam.startBeam=!0,This.potentialEndBeam.endBeam=!0),delete This.potentialStartBeam,delete This.potentialEndBeam};if("note"===type){var dur=This.getDuration(hashParams);dur>=.25?endBeamLast():hashParams.force_end_beam_last&&void 0!==This.potentialStartBeam?endBeamLast():hashParams.end_beam&&void 0!==This.potentialStartBeam?void 0===hashParams.rest?endBeamHere():endBeamLast():void 0===hashParams.rest&&(void 0===This.potentialStartBeam?hashParams.end_beam||(This.potentialStartBeam=hashParams,delete This.potentialEndBeam):This.potentialEndBeam=hashParams)}else endBeamLast();delete hashParams.end_beam,delete hashParams.force_end_beam_last,pushNote(hashParams)},this.appendStartingElement=function(type,startChar,endChar,hashParams2){this.closeLine();var impliedNaturals;"key"===type&&(impliedNaturals=hashParams2.impliedNaturals,delete hashParams2.impliedNaturals);var hashParams=window.ABCJS.parse.clone(hashParams2);if(this.lines[this.lineNum].staff){"clef"===type&&(this.lines[this.lineNum].staff[this.staffNum].workingClef=hashParams),this.lines[this.lineNum].staff.length<=this.staffNum&&(this.lines[this.lineNum].staff[this.staffNum]={},this.lines[this.lineNum].staff[this.staffNum].clef=window.ABCJS.parse.clone(this.lines[this.lineNum].staff[0].clef),this.lines[this.lineNum].staff[this.staffNum].key=window.ABCJS.parse.clone(this.lines[this.lineNum].staff[0].key),this.lines[this.lineNum].staff[this.staffNum].meter=window.ABCJS.parse.clone(this.lines[this.lineNum].staff[0].meter),this.lines[this.lineNum].staff[this.staffNum].workingClef=window.ABCJS.parse.clone(this.lines[this.lineNum].staff[0].workingClef),this.lines[this.lineNum].staff[this.staffNum].voices=[[]]);for(var voice=this.lines[this.lineNum].staff[this.staffNum].voices[this.voiceNum],i=0;i<voice.length;i++){if("note"===voice[i].el_type||"bar"===voice[i].el_type)return hashParams.el_type=type,hashParams.startChar=startChar,hashParams.endChar=endChar,impliedNaturals&&(hashParams.accidentals=impliedNaturals.concat(hashParams.accidentals)),void voice.push(hashParams);if(voice[i].el_type===type)return hashParams.el_type=type,hashParams.startChar=startChar,hashParams.endChar=endChar,impliedNaturals&&(hashParams.accidentals=impliedNaturals.concat(hashParams.accidentals)),void(voice[i]=hashParams)}this.lines[this.lineNum].staff[this.staffNum][type]=hashParams2}},this.getNumLines=function(){return this.lines.length},this.pushLine=function(hash){this.vskipPending&&(hash.vskip=this.vskipPending,delete this.vskipPending),this.lines.push(hash)},this.addSubtitle=function(str){this.pushLine({subtitle:str})},this.addSpacing=function(num){this.vskipPending=num},this.addNewPage=function(num){this.pushLine({newpage:num})},this.addSeparator=function(spaceAbove,spaceBelow,lineLength){this.pushLine({separator:{spaceAbove:spaceAbove,spaceBelow:spaceBelow,lineLength:lineLength}})},this.addText=function(str){this.pushLine({text:str})},this.addCentered=function(str){this.pushLine({text:[{text:str,center:!0}]})},this.containsNotes=function(voice){for(var i=0;i<voice.length;i++)if("note"===voice[i].el_type||"bar"===voice[i].el_type)return!0;return!1},this.containsNotesStrict=function(voice){for(var i=0;i<voice.length;i++)if("note"===voice[i].el_type&&void 0===voice[i].rest)return!0;return!1},this.startNewLine=function(params){var This=this;this.closeLine();var createVoice=function(params){if(This.lines[This.lineNum].staff[This.staffNum].voices[This.voiceNum]=[],This.isFirstLine(This.lineNum)?params.name&&(This.lines[This.lineNum].staff[This.staffNum].title||(This.lines[This.lineNum].staff[This.staffNum].title=[]),This.lines[This.lineNum].staff[This.staffNum].title[This.voiceNum]=params.name):params.subname&&(This.lines[This.lineNum].staff[This.staffNum].title||(This.lines[This.lineNum].staff[This.staffNum].title=[]),This.lines[This.lineNum].staff[This.staffNum].title[This.voiceNum]=params.subname),params.style&&This.appendElement("style",null,null,{head:params.style}),params.stem)This.appendElement("stem",null,null,{direction:params.stem});else if(This.voiceNum>0){if(void 0!==This.lines[This.lineNum].staff[This.staffNum].voices[0]){for(var found=!1,i=0;i<This.lines[This.lineNum].staff[This.staffNum].voices[0].length;i++)"stem"===This.lines[This.lineNum].staff[This.staffNum].voices[0].el_type&&(found=!0);if(!found){var stem={el_type:"stem",direction:"up"};This.lines[This.lineNum].staff[This.staffNum].voices[0].splice(0,0,stem)}}This.appendElement("stem",null,null,{direction:"down"})}params.scale&&This.appendElement("scale",null,null,{size:params.scale})},createStaff=function(params){This.lines[This.lineNum].staff[This.staffNum]={voices:[],clef:params.clef,key:params.key,workingClef:params.clef},params.vocalfont&&(This.lines[This.lineNum].staff[This.staffNum].vocalfont=params.vocalfont),params.bracket&&(This.lines[This.lineNum].staff[This.staffNum].bracket=params.bracket),params.brace&&(This.lines[This.lineNum].staff[This.staffNum].brace=params.brace),params.connectBarLines&&(This.lines[This.lineNum].staff[This.staffNum].connectBarLines=params.connectBarLines),params.barNumber&&(This.lines[This.lineNum].staff[This.staffNum].barNumber=params.barNumber),createVoice(params),params.part&&This.appendElement("part",params.startChar,params.endChar,{title:params.part}),void 0!==params.meter&&(This.lines[This.lineNum].staff[This.staffNum].meter=params.meter)},createLine=function(params){This.lines[This.lineNum]={staff:[]},createStaff(params)};if(void 0===this.lines[this.lineNum])createLine(params);else if(void 0===this.lines[this.lineNum].staff)this.lineNum++,this.startNewLine(params);else if(void 0===this.lines[this.lineNum].staff[this.staffNum])createStaff(params);else if(void 0===this.lines[this.lineNum].staff[this.staffNum].voices[this.voiceNum])createVoice(params);else{if(!this.containsNotes(this.lines[this.lineNum].staff[this.staffNum].voices[this.voiceNum]))return;this.lineNum++,this.startNewLine(params)}},this.hasBeginMusic=function(){for(var i=0;i<this.lines.length;i++)if(this.lines[i].staff)return!0;return!1},this.isFirstLine=function(index){for(var i=index-1;i>=0;i--)if(void 0!==this.lines[i].staff)return!1;return!0},this.getMeter=function(){for(var i=0;i<this.lines.length;i++){var line=this.lines[i];if(line.staff)for(var j=0;j<line.staff.length;j++){var meter=line.staff[j].meter;if(meter)return meter}}return{type:"common_time"}},this.getCurrentVoice=function(){return void 0!==this.lines[this.lineNum]&&void 0!==this.lines[this.lineNum].staff[this.staffNum]&&void 0!==this.lines[this.lineNum].staff[this.staffNum].voices[this.voiceNum]?this.lines[this.lineNum].staff[this.staffNum].voices[this.voiceNum]:null},this.setCurrentVoice=function(staffNum,voiceNum){this.staffNum=staffNum,this.voiceNum=voiceNum;for(var i=0;i<this.lines.length;i++)if(this.lines[i].staff&&(void 0===this.lines[i].staff[staffNum]||void 0===this.lines[i].staff[staffNum].voices[voiceNum]||!this.containsNotes(this.lines[i].staff[staffNum].voices[voiceNum])))return void(this.lineNum=i);this.lineNum=i},this.addMetaText=function(key,value){void 0===this.metaText[key]?this.metaText[key]=value:this.metaText[key]+="\n"+value},this.addMetaTextArray=function(key,value){void 0===this.metaText[key]?this.metaText[key]=[value]:this.metaText[key].push(value)},this.addMetaTextObj=function(key,value){this.metaText[key]=value},this.setupEvents=function(startingDelay,timeDivider){for(var timingEvents=[],eventHash={},time=startingDelay,isTiedState=!1,line=0;line<this.engraver.staffgroups.length;line++){var group=this.engraver.staffgroups[line],voices=group.voices,firstStaff=group.staffs[0],middleC=firstStaff.absoluteY,top=middleC-firstStaff.top*ABCJS.write.spacing.STEP,lastStaff=group.staffs[group.staffs.length-1];middleC=lastStaff.absoluteY;for(var bottom=middleC-lastStaff.bottom*ABCJS.write.spacing.STEP,height=bottom-top,maxVoiceTime=0,v=0;v<voices.length;v++){for(var voiceTime=time,elements=voices[v].children,elem=0;elem<elements.length;elem++){var element=elements[elem];if(element.hint)break;if(element.duration>0){var isTiedToNext=element.startTie;isTiedState?isTiedToNext||(isTiedState=!1):(eventHash["event"+voiceTime]?(eventHash["event"+voiceTime].left=Math.min(eventHash["event"+voiceTime].left,element.x),eventHash["event"+voiceTime].elements.push(element.elemset)):eventHash["event"+voiceTime]={type:"event",seconds:voiceTime,top:top,height:height,left:element.x,width:element.w,elements:[element.elemset]},isTiedToNext&&(isTiedState=!0)),voiceTime+=element.duration/timeDivider}}maxVoiceTime=Math.max(maxVoiceTime,voiceTime)}time=maxVoiceTime}return timingEvents=makeSortedArray(eventHash),addVerticalInfo(timingEvents),timingEvents},this.setTiming=function(bpm,measuresOfDelay){var meter=this.getMeter();this.barTimings=[];var measureLength,beatLength=this.getBeatLength(),beatsPerSecond=bpm/60;switch(meter.type){case"common_time":measureLength=1,this.meter={num:4,den:4};break;case"cut_time":measureLength=1,this.meter={num:2,den:2};break;default:measureLength=meter.value[0].num/meter.value[0].den,this.meter={num:meter.value[0].num,den:meter.value[0].den}}var startingDelay=measureLength/beatLength*measuresOfDelay/beatsPerSecond,timeDivider=beatLength*beatsPerSecond;this.noteTimings=this.setupEvents(startingDelay,timeDivider)}},window.ABCJS||(window.ABCJS={}),window.ABCJS.midi||(window.ABCJS.midi={}),function(){"use strict";function isFunction(functionToCheck){var getType={};return functionToCheck&&"[object Function]"===getType.toString.call(functionToCheck)}function preprocessLabel(label,title){return label.replace(/%T/g,title)}function hasClass(element,cls){return!!element&&(" "+element.className+" ").indexOf(" "+cls+" ")>-1}function addClass(element,cls){element&&(hasClass(element,cls)||(element.className=element.className+" "+cls))}function removeClass(element,cls){element&&(element.className=element.className.replace(cls,"").trim().replace(" "," "))}function toggleClass(element,cls){element&&(hasClass(element,cls)?removeClass(element,cls):addClass(element,cls))}function closest(element,cls){if(!element)return null;for(;element!==document.body;){if(hasClass(element,cls))return element;element=element.parentNode}return null}function find(element,cls){if(!element)return null;var els=element.getElementsByClassName(cls);return 0===els.length?null:els[0]}function addLoadEvent(func){var oldOnLoad=window.onload;"function"!=typeof window.onload?window.onload=func:window.onload=function(){oldOnLoad&&oldOnLoad(),func()}}function afterSetup(timeWarp,data,onSuccess){MIDI.player.currentTime=0,MIDI.player.warp=timeWarp,MIDI.player.load({events:data}),onSuccess()}function setCurrentMidiTune(timeWarp,data,onSuccess){midiJsInitialized?afterSetup(timeWarp,data,onSuccess):MIDI.setup({debug:!0,soundfontUrl:window.ABCJS.midi.soundfontUrl}).then(function(){midiJsInitialized=!0,afterSetup(timeWarp,data,onSuccess)})}function startCurrentlySelectedTune(){MIDI.player.start(MIDI.player.currentTime)}function stopCurrentlyPlayingTune(){MIDI.player.stop()}function pauseCurrentlyPlayingTune(){MIDI.player.pause()}function setMidiCallback(midiJsListener){MIDI.player.setAnimation(midiJsListener)}function jumpToMidiPosition(play,offset,width){var ratio=offset/width,endTime=MIDI.player.duration;play&&pauseCurrentlyPlayingTune(),MIDI.player.currentTime=endTime*ratio,play&&startCurrentlySelectedTune()}function setTimeWarp(percent){MIDI.player.warp=percent>0?100/percent:1}function loadMidi(target,onSuccess){var dataEl=find(target,"abcjs-data"),data=JSON.parse(dataEl.innerHTML),timeWarp=1,tempoEl=find(target,"abcjs-midi-tempo");if(tempoEl){var percent=parseInt(tempoEl.value,10);percent>0&&(timeWarp=100/percent)}setCurrentMidiTune(timeWarp,data,onSuccess)}function deselectMidiControl(){var otherMidi=find(document,"abcjs-midi-current");if(otherMidi){stopCurrentlyPlayingTune(),removeClass(otherMidi,"abcjs-midi-current");var otherMidiStart=find(otherMidi,"abcjs-midi-start");removeClass(otherMidiStart,"abcjs-pushed")}}function findElements(visualItems,currentTime,epsilon){for(var currentIndex,currentElement,minIndex=0,maxIndex=visualItems.length-1;minIndex<=maxIndex;)if(currentIndex=(minIndex+maxIndex)/2|0,currentElement=visualItems[currentIndex],currentElement.seconds-epsilon<currentTime)minIndex=currentIndex+1;else{if(!(currentElement.seconds-epsilon>currentTime))return currentIndex;maxIndex=currentIndex-1}for(;visualItems[currentIndex].seconds-epsilon>=currentTime&&currentIndex>0;)currentIndex--;return 0===currentIndex&&visualItems[currentIndex].seconds-epsilon>=currentTime?-1:currentIndex}function midiJsListener(position){var midiControl;if(position.duration>0&&lastNow!==position.progress&&(lastNow=position.progress,midiControl=find(document,"abcjs-midi-current"))){var startButton=find(midiControl,"abcjs-midi-start");if(hasClass(startButton,"abcjs-pushed")){var progressBackground=find(midiControl,"abcjs-midi-progress-background"),totalWidth=progressBackground.offsetWidth,progressIndicator=find(midiControl,"abcjs-midi-progress-indicator"),scaled=totalWidth*lastNow;progressIndicator.style.left=scaled+"px";var clock=find(midiControl,"abcjs-midi-clock");if(clock){var seconds=Math.floor(position.currentTime),minutes=Math.floor(seconds/60);seconds%=60,seconds<10&&(seconds="0"+seconds),minutes<10&&(minutes=" "+minutes),clock.innerHTML=minutes+":"+seconds}var beatsPerSecond=parseInt(midiControl.abcjsQpm,10)/60,currentTime=position.currentTime;if(midiControl.abcjsListener){var thisBeat=Math.floor(currentTime/beatsPerSecond);position.newBeat=thisBeat!==midiControl.abcjsLastBeat,midiControl.abcjsLastBeat=thisBeat,midiControl.abcjsListener(midiControl,position)}if(midiControl.abcjsAnimate){var epsilon=beatsPerSecond/64,index=findElements(midiControl.abcjsTune.noteTimings,currentTime,epsilon);if(index!==midiControl.abcjsLastIndex){var last=midiControl.abcjsLastIndex>=0?midiControl.abcjsTune.noteTimings[midiControl.abcjsLastIndex]:null;midiControl.abcjsAnimate(last,midiControl.abcjsTune.noteTimings[index]),midiControl.abcjsLastIndex=index}}}}if(1===position.progress){midiControl=find(document,"abcjs-midi-current");var loopControl=find(midiControl,"abcjs-midi-loop"),finishedResetting=function(){loopControl&&hasClass(loopControl,"abcjs-pushed")&&onStart(find(midiControl,"abcjs-midi-start"))};setTimeout(function(){doReset(midiControl,finishedResetting),midiControl.abcjsAnimate&&midiControl.abcjsAnimate(midiControl.abcjsTune.noteTimings[midiControl.abcjsLastIndex],null)},1)}}function onStart(target){var parent=closest(target,"abcjs-inline-midi");if(hasClass(target,"abcjs-pushed"))pauseCurrentlyPlayingTune(),removeClass(target,"abcjs-pushed");else{if(hasClass(parent,"abcjs-midi-current"))startCurrentlySelectedTune();else{deselectMidiControl();var onSuccess=function(){startCurrentlySelectedTune(),addClass(parent,"abcjs-midi-current")};loadMidi(parent,onSuccess)}addClass(target,"abcjs-pushed")}parent.abcjsLastBeat=-1,parent.abcjsLastIndex=-1,setMidiCallback(midiJsListener)}function onSelection(target){toggleClass(target,"abcjs-pushed")}function onLoop(target){toggleClass(target,"abcjs-pushed")}function doReset(target,callback){function onSuccess(){addClass(parent,"abcjs-midi-current");var progressIndicator=find(parent,"abcjs-midi-progress-indicator");progressIndicator.style.left="0px";var clock=find(parent,"abcjs-midi-clock");clock.innerHTML=" 0:00",callback&&callback()}var parent=closest(target,"abcjs-inline-midi");deselectMidiControl(),parent&&loadMidi(parent,onSuccess)}function onReset(target){function keepPlaying(){play&&(startCurrentlySelectedTune(),addClass(playEl,"abcjs-pushed"))}var parent=closest(target,"abcjs-inline-midi"),playEl=find(parent,"abcjs-midi-start"),play=hasClass(playEl,"abcjs-pushed");hasClass(parent,"abcjs-midi-current")&&doReset(target,keepPlaying)}function relMouseX(target,event){var totalOffsetX=0;do totalOffsetX+=target.offsetLeft-target.scrollLeft,target=target.offsetParent;while(target);return event.pageX-totalOffsetX}function onProgress(target,event){var parent=closest(target,"abcjs-inline-midi");if(hasClass(parent,"abcjs-midi-current")){var play=find(parent,"abcjs-midi-start");play=hasClass(play,"abcjs-pushed");var width=target.offsetWidth,offset=relMouseX(target,event);jumpToMidiPosition(play,offset,width)}}function onTempo(el){for(var percent=parseInt(el.value,10),startTempo=parseInt(el.getAttribute("data-start-tempo"),10);el&&!hasClass(el,"abcjs-midi-current-tempo");)el=el.nextSibling;el.innerHTML=Math.floor(percent*startTempo/100),setTimeWarp(percent)}function addDelegates(){if(document.body.addEventListener("click",function(event){event=event||window.event;for(var target=event.target||event.srcElement;target&&target!==document.body;){if(hasClass(target,"abcjs-midi-start"))return void onStart(target,event);if(hasClass(target,"abcjs-midi-selection"))return void onSelection(target,event);if(hasClass(target,"abcjs-midi-loop"))return void onLoop(target,event);if(hasClass(target,"abcjs-midi-reset"))return void onReset(target,event);if(hasClass(target,"abcjs-midi-progress-background"))return void onProgress(target,event);target=target.parentNode}}),document.body.addEventListener("change",function(event){event=event||window.event;for(var target=event.target||event.srcElement;target!==document.body;)hasClass(target,"abcjs-midi-tempo")&&onTempo(target,event),target=target.parentNode}),void 0===window.MIDI){window.ABCJS.midi.midiInlineInitialized="not loaded";for(var els=document.getElementsByClassName("abcjs-inline-midi"),i=0;i<els.length;i++)els[i].innerHTML="MIDI NOT PRESENT"}}window.ABCJS.midi.generateMidiDownloadLink=function(tune,midiParams,midi,index){var html='<div class="download-midi midi-'+index+'">';midiParams.preTextDownload&&(html+=midiParams.preTextDownload);var label,title=tune.metaText&&tune.metaText.title?tune.metaText.title:"Untitled";return label=midiParams.downloadLabel&&isFunction(midiParams.downloadLabel)?midiParams.downloadLabel(tune,index):midiParams.downloadLabel?midiParams.downloadLabel.replace(/%T/,title):'Download MIDI for "'+title+'"',title=title.toLowerCase().replace(/'/g,"").replace(/\W/g,"_").replace(/__/g,"_"),html+='<a download="'+title+'.midi" href="'+midi+'">'+label+"</a>",midiParams.postTextDownload&&(html+=midiParams.postTextDownload),html+"</div>"},window.ABCJS.midi.generateMidiControls=function(tune,midiParams,midi,index){if("failed"===window.ABCJS.midiInlineInitialized)return'<div class="abcjs-inline-midi abcjs-midi-'+index+'">ERROR</div>';if("not loaded"===window.ABCJS.midiInlineInitialized)return'<div class="abcjs-inline-midi abcjs-midi-'+index+'">MIDI NOT PRESENT</div>';var title=tune.metaText&&tune.metaText.title?tune.metaText.title:"Untitled",options=midiParams.inlineControls||{};void 0===options.standard&&(options.standard=!0),void 0===options.tooltipSelection&&(options.tooltipSelection="Click to toggle play selection/play all."),void 0===options.tooltipLoop&&(options.tooltipLoop="Click to toggle play once/repeat."),void 0===options.tooltipReset&&(options.tooltipReset="Click to go to beginning."),void 0===options.tooltipPlay&&(options.tooltipPlay="Click to play/pause."),void 0===options.tooltipProgress&&(options.tooltipProgress="Click to change the playback position."), void 0===options.tooltipTempo&&(options.tooltipTempo="Change the playback speed.");var style="";options.hide&&(style='style="display:none;"');var html='<div class="abcjs-inline-midi abcjs-midi-'+index+'" '+style+">";if(html+='<span class="abcjs-data" style="display:none;">'+JSON.stringify(midi)+"</span>",midiParams.preTextInline&&(html+='<span class="abcjs-midi-pre">'+preprocessLabel(midiParams.preTextInline,title)+"</span>"),options.selectionToggle&&(html+='<button class="abcjs-midi-selection abcjs-btn" title="'+options.tooltipSelection+'"></button>'),options.loopToggle&&(html+='<button class="abcjs-midi-loop abcjs-btn" title="'+options.tooltipLoop+'"></button>'),options.standard&&(html+='<button class="abcjs-midi-reset abcjs-btn" title="'+options.tooltipReset+'"></button><button class="abcjs-midi-start abcjs-btn" title="'+options.tooltipPlay+'"></button><button class="abcjs-midi-progress-background" title="'+options.tooltipProgress+'"><span class="abcjs-midi-progress-indicator"></span></button><span class="abcjs-midi-clock"> 0:00</span>'),options.tempo){var startTempo=tune&&tune.metaText&&tune.metaText.tempo?tune.metaText.tempo.bpm:180;html+='<span class="abcjs-tempo-wrapper"><input class="abcjs-midi-tempo" value="100" type="number" min="1" max="300" data-start-tempo="'+startTempo+'" title="'+options.tooltipTempo+'" />% (<span class="abcjs-midi-current-tempo">'+startTempo+"</span> BPM)</span>"}return midiParams.postTextInline&&(html+='<span class="abcjs-midi-post">'+preprocessLabel(midiParams.postTextInline,title)+"</span>"),html+"</div>"},window.ABCJS.midi.soundfontUrl="/soundfont/";var lastNow,midiJsInitialized=!1;window.ABCJS.midi.startPlaying=function(target){onStart(target)},window.ABCJS.midi.stopPlaying=function(){stopCurrentlyPlayingTune()},addLoadEvent(addDelegates)}(),window.ABCJS||(window.ABCJS={}),window.ABCJS.midi||(window.ABCJS.midi={}),function(){"use strict";function convertPitch(pitch){return 60+pitch}var baseDuration=1920;window.ABCJS.midi.create=function(abcTune,options){void 0===options&&(options={});var sequence=window.ABCJS.midi.sequence(abcTune,options),commands=window.ABCJS.midi.flatten(sequence,options),midi=window.ABCJS.midi.rendererFactory(),midiJs=new window.ABCJS.midi.Preparer,title=abcTune.metaText?abcTune.metaText.title:void 0;title&&title.length>128&&(title=title.substring(0,124)+"..."),midi.setGlobalInfo(commands.tempo,title),midiJs.setGlobalInfo(commands.tempo,title),void 0!==commands.instrument&&(midi.setInstrument(commands.instrument),midiJs.setInstrument(commands.instrument)),void 0!==commands.channel&&(midi.setChannel(commands.channel),midiJs.setChannel(commands.channel));for(var i=0;i<commands.tracks.length;i++){midi.startTrack(),midiJs.startTrack();for(var j=0;j<commands.tracks[i].length;j++){var event=commands.tracks[i][j];switch(event.cmd){case"instrument":midi.setInstrument(event.instrument),midiJs.setInstrument(event.instrument);break;case"channel":midi.setChannel(event.channel),midiJs.setChannel(event.channel);break;case"start":midi.startNote(convertPitch(event.pitch),event.volume),midiJs.startNote(convertPitch(event.pitch),event.volume);break;case"stop":midi.endNote(convertPitch(event.pitch),0),midiJs.endNote(convertPitch(event.pitch));break;case"move":midi.addRest(event.duration*baseDuration),midiJs.addRest(event.duration*baseDuration);break;default:console.log("MIDI create Unknown: "+event.cmd)}}midi.endTrack(),midiJs.endTrack()}var midiFile=midi.getData(),midiInline=midiJs.getData();return void 0===options.generateInline&&(options.generateInline=!0),options.generateInline&&options.generateDownload?{download:midiFile,inline:midiInline}:options.generateInline?midiInline:midiFile}}(),window.ABCJS||(window.ABCJS={}),window.ABCJS.midi||(window.ABCJS.midi={}),function(){"use strict";function findChord(elem){if(chordTrackFinished||!elem.chord||0===elem.chord.length)return null;for(var i=0;i<elem.chord.length;i++){var ch=elem.chord[i];if("default"===ch.position)return ch.name;if(breakSynonyms.indexOf(ch.name.toLowerCase())>=0)return"break"}return null}function timeFromStart(){for(var distance=0,ct=0;ct<currentTrack.length;ct++)"move"===currentTrack[ct].cmd&&(distance+=currentTrack[ct].duration);return distance}function writeNote(elem,voiceOff){var velocity=voiceOff?0:64,chord=findChord(elem);if(chord){var c=interpretChord(chord);if(c){if(0===chordTrack.length){chordTrack.push({cmd:"instrument",instrument:0});var distance=timeFromStart();distance>0&&chordTrack.push({cmd:"move",duration:distance*tempoChangeFactor})}lastChord=c,currentChords.push({chord:lastChord,beat:barBeat})}}elem.startTriplet&&(multiplier=2===elem.startTriplet?1.5:(elem.startTriplet-1)/elem.startTriplet);var duration=elem.duration*multiplier;barBeat+=duration;var graces;if(elem.gracenotes){var stealFromCurrent=bagpipes||lastNoteDurationPosition<0||0===currentTrack.length,stealFromDuration=stealFromCurrent?duration:currentTrack[lastNoteDurationPosition].duration;graces=processGraceNotes(elem.gracenotes,stealFromDuration),bagpipes||(duration=writeGraceNotes(graces,stealFromCurrent,duration,null,velocity))}if(elem.pitches){graces&&bagpipes&&(duration=writeGraceNotes(graces,!0,duration,null,velocity));for(var pitches=[],i=0;i<elem.pitches.length;i++){var note=elem.pitches[i],actualPitch=adjustPitch(note);pitches.push({pitch:actualPitch,startTie:note.startTie}),pitchesTied[""+actualPitch]||currentTrack.push({cmd:"start",pitch:actualPitch,volume:velocity}),note.startTie?pitchesTied[""+actualPitch]=!0:note.endTie&&(pitchesTied[""+actualPitch]=!1)}currentTrack.push({cmd:"move",duration:(duration-normalBreakBetweenNotes)*tempoChangeFactor}),lastNoteDurationPosition=currentTrack.length-1;for(var ii=0;ii<pitches.length;ii++)pitchesTied[""+pitches[ii].pitch]||currentTrack.push({cmd:"stop",pitch:pitches[ii].pitch});currentTrack.push({cmd:"move",duration:normalBreakBetweenNotes*tempoChangeFactor})}else elem.rest&&currentTrack.push({cmd:"move",duration:duration*tempoChangeFactor});elem.endTriplet&&(multiplier=1)}function adjustPitch(note){var pitch=note.pitch;if(note.accidental)switch(note.accidental){case"sharp":barAccidentals[pitch]=1;break;case"flat":barAccidentals[pitch]=-1;break;case"natural":barAccidentals[pitch]=0;break;case"dblsharp":barAccidentals[pitch]=2;break;case"dblflat":barAccidentals[pitch]=-2}var actualPitch=12*extractOctave(pitch)+scale[extractNote(pitch)];return actualPitch+=void 0!==barAccidentals[pitch]?barAccidentals[pitch]:accidentals[extractNote(pitch)],actualPitch+=transpose}function setKeySignature(elem){var accidentals=[0,0,0,0,0,0,0];if(!elem.accidentals)return accidentals;for(var i=0;i<elem.accidentals.length;i++){var acc=elem.accidentals[i],d="sharp"===acc.acc?1:"natural"===acc.acc?0:-1,lowercase=acc.note.toLowerCase(),note=extractNote(lowercase.charCodeAt(0)-"c".charCodeAt(0));accidentals[note]+=d}return accidentals}function processGraceNotes(graces,companionDuration){for(var grace,graceDuration=0,ret=[],g=0;g<graces.length;g++)grace=graces[g],graceDuration+=grace.duration;graceDuration/=graceDivider;var multiplier=2*graceDuration>companionDuration?companionDuration/(2*graceDuration):1;for(g=0;g<graces.length;g++)grace=graces[g],ret.push({pitch:grace.pitch,duration:grace.duration/graceDivider*multiplier});return ret}function writeGraceNotes(graces,stealFromCurrent,duration,skipNote,velocity){for(var g=0;g<graces.length;g++){var gp=adjustPitch(graces[g]);gp!==skipNote&&currentTrack.push({cmd:"start",pitch:gp,volume:velocity}),currentTrack.push({cmd:"move",duration:graces[g].duration*tempoChangeFactor}),gp!==skipNote&&currentTrack.push({cmd:"stop",pitch:gp}),stealFromCurrent||(currentTrack[lastNoteDurationPosition].duration-=graces[g].duration),duration-=graces[g].duration}return duration}function extractOctave(pitch){return Math.floor(pitch/7)}function extractNote(pitch){return pitch%=7,pitch<0&&(pitch+=7),pitch}function interpretChord(name){if(0!==name.length){if("break"===name)return{chick:[]};var root=name.substring(0,1);if("("===root){if(name=name.substring(1,name.length-2),0===name.length)return;root=name.substring(0,1)}var bass=basses[root];if(bass){bass+=transpose;var chick,bass2=bass-5;1===name.length&&(chick=chordNotes(bass,""));var remaining=name.substring(1),acc=remaining.substring(0,1);"b"===acc||"♭"===acc?(bass--,bass2--,remaining=remaining.substring(1)):"#"!==acc&&"♯"!==acc||(bass++,bass2++,remaining=remaining.substring(1));var arr=remaining.split("/");if(chick=chordNotes(bass,arr[0]),2===arr.length){var explicitBass=basses[arr[1]];explicitBass&&(bass=basses[arr[1]]+transpose,bass2=bass)}return{boom:bass,boom2:bass2,chick:chick}}}}function chordNotes(bass,modifier){var intervals=chordIntervals[modifier];intervals||(intervals=chordIntervals.M),bass+=12;for(var notes=[],i=0;i<intervals.length;i++)notes.push(bass+intervals[i]);return notes}function writeBoom(boom,beatLength){void 0!==boom&&chordTrack.push({cmd:"start",pitch:boom,volume:64}),chordTrack.push({cmd:"move",duration:beatLength/2*tempoChangeFactor}),void 0!==boom&&chordTrack.push({cmd:"stop",pitch:boom}),chordTrack.push({cmd:"move",duration:beatLength/2*tempoChangeFactor})}function writeChick(chick,beatLength){for(var c=0;c<chick.length;c++)chordTrack.push({cmd:"start",pitch:chick[c],volume:48});for(chordTrack.push({cmd:"move",duration:beatLength/2*tempoChangeFactor}),c=0;c<chick.length;c++)chordTrack.push({cmd:"stop",pitch:chick[c]});chordTrack.push({cmd:"move",duration:beatLength/2*tempoChangeFactor})}function resolveChords(){var num=meter.num,den=meter.den,beatLength=1/den,pattern=rhythmPatterns[num+"/"+den],thisMeasureLength=parseInt(num,10)/parseInt(den,10),portionOfAMeasure=Math.abs(thisMeasureLength-barBeat);if(!pattern||portionOfAMeasure>.0078125){pattern=[];for(var beatsPresent=barBeat/beatLength,p=0;p<beatsPresent;p++)pattern.push("chick")}if(0===currentChords.length&&currentChords.push({beat:0,chord:lastChord}),0!==currentChords[0].beat&&lastChord&&currentChords.unshift({beat:0,chord:lastChord}),1!==currentChords.length){for(var beats={},i=0;i<currentChords.length;i++){var cc=currentChords[i],beat=Math.floor(cc.beat/beatLength);beats[""+beat]=cc}for(var m2=0;m2<pattern.length;m2++){var thisChord;switch(beats[""+m2]&&(thisChord=beats[""+m2]),pattern[m2]){case"boom":beats[""+(m2+1)]?writeChick(thisChord.chord.chick,beatLength):writeBoom(thisChord.chord.boom,beatLength);break;case"boom2":beats[""+(m2+1)]?writeChick(thisChord.chord.chick,beatLength):writeBoom(thisChord.chord.boom2,beatLength);break;case"chick":writeChick(thisChord.chord.chick,beatLength);break;case"":beats[""+m2]?writeChick(thisChord.chord.chick,beatLength):chordTrack.push({cmd:"move",duration:beatLength*tempoChangeFactor})}}}else for(var m=0;m<pattern.length;m++)switch(pattern[m]){case"boom":writeBoom(currentChords[0].chord.boom,beatLength);break;case"boom2":writeBoom(currentChords[0].chord.boom2,beatLength);break;case"chick":writeChick(currentChords[0].chord.chick,beatLength);break;case"":chordTrack.push({cmd:"move",duration:beatLength*tempoChangeFactor})}}function normalizeDrumDefinition(params){if(0===params.pattern.length||params.on===!1)return{on:!1};for(var str=params.pattern[0],events=[],event="",totalPlay=0,i=0;i<str.length;i++)if("d"===str[i]&&totalPlay++,"d"===str[i]||"z"===str[i])0!==event.length?(events.push(event),event=str[i]):event+=str[i];else{if(0===event.length)return{on:!1};event+=str[i]}if(0!==event.length&&events.push(event),params.pattern.length!==2*totalPlay+1)return{on:!1};for(var ret={on:!0,bars:params.bars,pattern:[]},beatLength=1/meter.den,playCount=0,j=0;j<events.length;j++){event=events[j];for(var len=1,div=!1,num=0,k=1;k<event.length;k++)switch(event[k]){case"/":0!==num&&(len*=num),num=0,div=!0;break;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":num=10*num+event[k];break;default:return{on:!1}}div?(0===num&&(num=2),len/=num):num&&(len*=num),"d"===event[0]?(ret.pattern.push({len:len*beatLength,pitch:params.pattern[1+playCount],velocity:params.pattern[1+playCount+totalPlay]}),playCount++):ret.pattern.push({len:len*beatLength,pitch:null})}for(var totalTime=0,measuresPerBeat=meter.num/meter.den,ii=0;ii<ret.pattern.length;ii++)totalTime+=ret.pattern[ii].len;var numBars=params.bars?params.bars:1,factor=totalTime/numBars/measuresPerBeat;for(ii=0;ii<ret.pattern.length;ii++)ret.pattern[ii].len=ret.pattern[ii].len/factor;return ret}function drumBeat(pitch,soundLength,volume){drumTrack.push({cmd:"start",pitch:pitch-60,volume:volume}),drumTrack.push({cmd:"move",duration:soundLength}),drumTrack.push({cmd:"stop",pitch:pitch-60})}function writeDrum(){if(0!==drumTrack.length||drumDefinition.on){var measureLen=meter.num/meter.den;if(0===drumTrack.length){drumTrack.push({cmd:"channel",channel:10}),drumTrack.push({cmd:"instrument",instrument:10});var distance=timeFromStart();if(distance>0&&distance<measureLen-.01)return void drumTrack.push({cmd:"move",duration:distance*tempoChangeFactor})}if(!drumDefinition.on)return void drumTrack.push({cmd:"move",duration:measureLen*tempoChangeFactor});for(var i=0;i<drumDefinition.pattern.length;i++){var len=drumDefinition.pattern[i].len*tempoChangeFactor;drumDefinition.pattern[i].pitch?drumBeat(drumDefinition.pattern[i].pitch,len,drumDefinition.pattern[i].velocity):drumTrack.push({cmd:"move",duration:len})}}}var barAccidentals,accidentals,transpose,bagpipes,multiplier,tracks,startingTempo,startingMeter,instrument,channel,currentTrack,pitchesTied,lastNoteDurationPosition,chordTrack,chordTrackFinished,currentChords,lastChord,barBeat,drumTrack,drumTrackFinished,tempoChangeFactor=1,meter={num:4,den:4},drumDefinition={},normalBreakBetweenNotes=1/128;window.ABCJS.midi.flatten=function(voices,options){options||(options={}),barAccidentals=[],accidentals=[0,0,0,0,0,0,0],bagpipes=!1,multiplier=1,tracks=[],startingTempo=void 0,startingMeter=void 0,tempoChangeFactor=1,instrument=void 0,channel=void 0,currentTrack=void 0,pitchesTied={},meter={num:4,den:4},chordTrack=[],chordTrackFinished=!1,currentChords=[],lastChord=void 0,barBeat=0,drumTrack=[],drumTrackFinished=!1,drumDefinition={};for(var i=0;i<voices.length;i++){transpose=0,lastNoteDurationPosition=-1;var voice=voices[i];currentTrack=[],pitchesTied={};for(var j=0;j<voice.length;j++){var element=voice[j];switch(element.el_type){case"note":writeNote(element,options.voicesOff);break;case"key":accidentals=setKeySignature(element);break;case"meter":startingMeter||(startingMeter=element),meter=element;break;case"tempo":startingTempo?tempoChangeFactor=element.qpm?startingTempo/element.qpm:1:startingTempo=element.qpm;break;case"transpose":transpose=element.transpose;break;case"bar":chordTrack.length>0&&(resolveChords(),currentChords=[]),barBeat=0,barAccidentals=[],0===i&&writeDrum();break;case"bagpipes":bagpipes=!0;break;case"instrument":instrument=element.program;break;case"channel":channel=element.channel;break;case"drum":drumDefinition=normalizeDrumDefinition(element.params);break;default:console.log("MIDI creation. Unknown el_type: "+element.el_type+"\n")}}tracks.push(currentTrack),chordTrack.length>0&&(chordTrackFinished=!0),drumTrack.length>0&&(drumTrackFinished=!0)}chordTrack.length>0&&tracks.push(chordTrack),drumTrack.length>0&&tracks.push(drumTrack);var num=parseInt(startingMeter.num,10),den=parseInt(startingMeter.den,10);return 2===den?startingTempo*=2:8===den?parseInt(num,10)%3===0?startingTempo*=1.5:startingTempo/=2:16===den&&(num%3===0?startingTempo*=.75:startingTempo/=4),{tempo:startingTempo,instrument:instrument,channel:channel,tracks:tracks}};var breakSynonyms=["break","(break)","no chord","n.c.","tacet"],scale=[0,2,4,5,7,9,11],graceDivider=8,basses={A:-27,B:-25,C:-24,D:-22,E:-20,F:-19,G:-17},chordIntervals={M:[0,4,7],6:[0,4,7,9],7:[0,4,7,10],"+7":[0,4,8,10],aug7:[0,4,8,10],maj7:[0,4,7,11],"∆7":[0,4,7,11],9:[0,4,7,10,14],11:[0,4,7,10,14,16],13:[0,4,7,10,14,18],"+":[0,4,8],"7#5":[0,4,8,10],"7+5":[0,4,8,10],"7b9":[0,4,7,10,13],"7b5":[0,4,6,10],"9#5":[0,4,8,10,14],"9+5":[0,4,8,10,14],m:[0,3,7],"-":[0,3,7],m6:[0,3,7,9],"-6":[0,3,7,9],m7:[0,3,7,10],"-7":[0,3,7,10],dim:[0,3,6],dim7:[0,3,6,9],"°7":[0,3,6,9],"ø7":[0,3,6,9],"7sus4":[0,5,7,10],m7sus4:[0,5,7,10],sus4:[0,5,7]},rhythmPatterns={"2/2":["boom","chick"],"2/4":["boom","chick"],"3/4":["boom","chick","chick"],"4/4":["boom","chick","boom2","chick"],"6/8":["boom","","chick","boom2","","chick"]}}(),window.ABCJS||(window.ABCJS={}),window.ABCJS.midi||(window.ABCJS.midi={}),function(){"use strict";function addAbsoluteTime(tracks){for(var i=0;i<tracks.length;i++)for(var absTime=0,j=0;j<tracks[i].length;j++)absTime+=tracks[i][j][1],tracks[i][j].absTime=absTime}function combineTracks(tracks){for(var output=[],i=0;i<tracks.length;i++)for(var j=0;j<tracks[i].length;j++)output.push(tracks[i][j]);return output}function sortTracks(output){return output.sort(function(a,b){return a.absTime>b.absTime?1:-1})}function adjustTime(output){for(var lastTime=0,i=0;i<output.length;i++){var thisTime=output[i].absTime;output[i][1]=thisTime-lastTime,lastTime=thisTime}}function weaveTracks(tracks){addAbsoluteTime(tracks);var output=combineTracks(tracks);return output=sortTracks(output),adjustTime(output),output}window.ABCJS.midi.Preparer=function(){this.tempo=0,this.timeFactor=0,this.output=[],this.currentChannel=0,this.currentInstrument=0,this.track=0,this.nextDuration=0,this.tracks=[[]]};var Preparer=window.ABCJS.midi.Preparer;Preparer.prototype.setInstrument=function(instrument){var ev=[{ticksToEvent:0,track:this.track,event:{channel:this.currentChannel,deltaTime:0,programNumber:this.currentInstrument,subtype:"programChange",type:"channel"}},this.nextDuration*this.timeFactor];this.tracks[this.track].push(ev)},Preparer.prototype.setChannel=function(channel){},Preparer.prototype.startTrack=function(){this.track++,this.tracks[this.track]=[],this.nextDuration=0},Preparer.prototype.setGlobalInfo=function(tempo,title){this.tempo=tempo;var mspb=Math.round(1/tempo*6e7);this.timeFactor=mspb/48e4;var ev=[{ticksToEvent:0,track:this.track,event:{deltaTime:0,microsecondsPerBeat:mspb,subtype:"setTempo",type:"meta"}},this.nextDuration*this.timeFactor];ev=[{ticksToEvent:0,track:this.track,event:{deltaTime:0,subtype:"trackName",text:title,type:"meta"}},this.nextDuration*this.timeFactor],ev=[{ticksToEvent:0,track:this.track,event:{deltaTime:0,subtype:"endOfTrack",type:"meta"}},this.nextDuration*this.timeFactor]},Preparer.prototype.startNote=function(pitch,volume){var deltaTime=5*Math.floor(this.nextDuration/5),ev=[{ticksToEvent:deltaTime,track:this.track,event:{deltaTime:deltaTime,channel:this.currentChannel,type:"channel",noteNumber:pitch,velocity:volume,subtype:"noteOn"}},this.nextDuration*this.timeFactor];this.tracks[this.track].push(ev),this.nextDuration=0},Preparer.prototype.endNote=function(pitch){var deltaTime=5*Math.floor(this.nextDuration/5),ev=[{ticksToEvent:deltaTime,track:this.track,event:{deltaTime:deltaTime,channel:this.currentChannel,type:"channel",noteNumber:pitch,velocity:0,subtype:"noteOff"}},this.nextDuration*this.timeFactor];this.tracks[this.track].push(ev),this.nextDuration=0},Preparer.prototype.addRest=function(duration){this.nextDuration+=duration},Preparer.prototype.endTrack=function(){[{ticksToEvent:0,track:this.track,event:{deltaTime:0,type:"meta",subtype:"endOfTrack"}},0]},Preparer.prototype.getData=function(){return weaveTracks(this.tracks)}}(),window.ABCJS||(window.ABCJS={}),window.ABCJS.midi||(window.ABCJS.midi={}),function(){"use strict";function setAttributes(elm,attrs){for(var attr in attrs)attrs.hasOwnProperty(attr)&&elm.setAttribute(attr,attrs[attr]);return elm}function Midi(){this.trackstrings="",this.trackcount=0,this.noteOnAndChannel="%90"}function encodeHex(s){for(var ret="",i=0;i<s.length;i+=2)ret+="%",ret+=s.substr(i,2);return ret}function toHex(n,padding){for(var s=n.toString(16);s.length<padding;)s="0"+s;return encodeHex(s)}function toDurationHex(n){for(var res=0,a=[];0!==n;)a.push(127&n),n>>=7;for(var i=a.length-1;i>=0;i--){res<<=8;var bits=a[i];0!==i&&(bits|=128),res|=bits}var padding=res.toString(16).length;return padding+=padding%2,toHex(res,padding)}Midi.prototype.setTempo=function(qpm){0===this.trackcount&&(this.startTrack(),this.track+="%00%FF%51%03"+toHex(Math.round(6e7/qpm),6),this.endTrack())},Midi.prototype.setGlobalInfo=function(qpm,name){if(0===this.trackcount){if(this.startTrack(),this.track+="%00%FF%51%03"+toHex(Math.round(6e7/qpm),6),name){this.track+="%00%FF%03"+toHex(name.length,2);for(var i=0;i<name.length;i++)this.track+=toHex(name.charCodeAt(i),2)}this.endTrack()}},Midi.prototype.startTrack=function(){this.track="",this.silencelength=0,this.trackcount++,this.first=!0,this.instrument&&this.setInstrument(this.instrument)},Midi.prototype.endTrack=function(){var tracklength=toHex(this.track.length/3+4,8);this.track="MTrk"+tracklength+this.track+"%00%FF%2F%00",this.trackstrings+=this.track},Midi.prototype.setInstrument=function(number){this.track?this.track="%00%C0"+toHex(number,2)+this.track:this.track="%00%C0"+toHex(number,2),this.instrument=number},Midi.prototype.setChannel=function(number){this.channel=number-1,this.noteOnAndChannel="%9"+this.channel.toString(16)},Midi.prototype.startNote=function(pitch,loudness){this.track+=toDurationHex(this.silencelength),this.silencelength=0,this.first&&(this.first=!1,this.track+=this.noteOnAndChannel),this.track+="%"+pitch.toString(16)+toHex(loudness,2)},Midi.prototype.endNote=function(pitch,length){this.track+=toDurationHex(this.silencelength+length),this.silencelength=0,this.track+="%"+pitch.toString(16)+"%00"},Midi.prototype.addRest=function(length){this.silencelength+=length},Midi.prototype.getData=function(){return"data:audio/midi,MThd%00%00%00%06%00%01"+toHex(this.trackcount,4)+"%01%e0"+this.trackstrings},Midi.prototype.embed=function(parent,noplayer){var data=this.getData(),link=setAttributes(document.createElement("a"),{href:data});if(link.innerHTML="download midi",parent.insertBefore(link,parent.firstChild),!noplayer){var embed=setAttributes(document.createElement("embed"),{src:data,type:"video/quicktime",controller:"true",autoplay:"false",loop:"false",enablejavascript:"true",style:"display:block; height: 20px;"});parent.insertBefore(embed,parent.firstChild)}},window.ABCJS.midi.rendererFactory=function(){return new Midi}}(),window.ABCJS||(window.ABCJS={}),window.ABCJS.midi||(window.ABCJS.midi={}),function(){"use strict";function interpretTempo(element){var duration=.25;element.duration&&(duration=element.duration[0]);var bpm=60;return element.bpm&&(bpm=element.bpm),bpm*duration*4}function interpretMeter(element){var meter;switch(element.type){case"common_time":meter={el_type:"meter",num:4,den:4};break;case"cut_time":meter={el_type:"meter",num:2,den:2};break;case"specified":meter={el_type:"meter",num:element.value[0].num,den:element.value[0].den};break;default:meter={el_type:"meter"}}return measureLength=meter.num/meter.den,meter}var measureLength;window.ABCJS.midi.sequence=function(abctune,options){options=options||{};var qpm=180,program=options.program||0,transpose=options.transpose||0,channel=options.channel||0,drumPattern=options.drum||"",drumBars=options.drumBars||1,drumIntro=options.drumIntro||0,drumOn=""!==drumPattern;program=parseInt(program,10),transpose=parseInt(transpose,10),channel=parseInt(channel,10),drumPattern=drumPattern.split(" "),drumBars=parseInt(drumBars,10),drumIntro=parseInt(drumIntro,10);var bagpipes=abctune.formatting.bagpipes;if(bagpipes&&(program=71),abctune.formatting.midi){var globals=abctune.formatting.midi;globals.program&&(program=globals.program[0],globals.program.length>1&&(channel=globals.program[1])),globals.transpose&&(transpose=globals.transpose[0]),globals.channel&&(channel=globals.channel[0]),globals.drum&&(drumPattern=globals.drum),globals.drumbars&&(drumBars=globals.drumbars[0]),globals.drumon&&(drumOn=!0)}abctune.metaText.tempo&&(qpm=interpretTempo(abctune.metaText.tempo)),options.qpm&&(qpm=parseInt(options.qpm,10));var startVoice=[];bagpipes&&startVoice.push({el_type:"bagpipes"}),startVoice.push({el_type:"instrument",program:program}),channel&&startVoice.push({el_type:"channel",channel:channel}),transpose&&startVoice.push({el_type:"transpose",transpose:transpose}),startVoice.push({el_type:"tempo",qpm:qpm});for(var voices=[],startRepeatPlaceholder=[],skipEndingPlaceholder=[],startingDrumSet=!1,i=0;i<abctune.lines.length;i++){var line=abctune.lines[i];if(line.staff)for(var staves=line.staff,voiceNumber=0,j=0;j<staves.length;j++)for(var staff=staves[j],k=0;k<staff.voices.length;k++){var voice=staff.voices[k];voices[voiceNumber]||(voices[voiceNumber]=[].concat(startVoice)),staff.key&&("HP"===staff.key.root?voices[voiceNumber].push({el_type:"key",accidentals:[{acc:"natural",note:"g"},{acc:"sharp",note:"f"},{acc:"sharp",note:"c"}]}):voices[voiceNumber].push({el_type:"key",accidentals:staff.key.accidentals})),staff.meter&&voices[voiceNumber].push(interpretMeter(staff.meter)),!startingDrumSet&&drumOn&&(voices[voiceNumber].push({el_type:"drum",params:{pattern:drumPattern,bars:drumBars,on:drumOn,intro:drumIntro}}),startingDrumSet=!0),staff.clef&&staff.clef.transpose&&(staff.clef.el_type="clef",voices[voiceNumber].push({el_type:"transpose",transpose:staff.clef.transpose})),abctune.formatting.midi&&abctune.formatting.midi.drumoff&&(voices[voiceNumber].push({el_type:"bar"}),voices[voiceNumber].push({el_type:"drum",params:{pattern:"",on:!1}}));for(var noteEventsInBar=0,v=0;v<voice.length;v++){var elem=voice[v];switch(elem.el_type){case"note":elem.rest&&"spacer"===elem.rest.type||(voices[voiceNumber].push(elem),noteEventsInBar++);break;case"key":"HP"===elem.root?voices[voiceNumber].push({el_type:"key",accidentals:[{acc:"natural",note:"g"},{acc:"sharp",note:"f"},{acc:"sharp",note:"c"}]}):voices[voiceNumber].push({el_type:"key",accidentals:elem.accidentals});break;case"meter":voices[voiceNumber].push(interpretMeter(elem));break;case"clef":elem.transpose&&voices[voiceNumber].push({el_type:"transpose",transpose:elem.transpose});break;case"tempo":qpm=interpretTempo(elem),voices[voiceNumber].push({el_type:"tempo",qpm:qpm});break;case"bar":noteEventsInBar>0&&voices[voiceNumber].push({el_type:"bar"}),noteEventsInBar=0;var endRepeat="bar_right_repeat"===elem.type||"bar_dbl_repeat"===elem.type,startEnding="1"===elem.startEnding,startRepeat="bar_left_repeat"===elem.type||"bar_dbl_repeat"===elem.type||"bar_thick_thin"===elem.type||"bar_thin_thick"===elem.type||"bar_thin_thin"===elem.type||"bar_right_repeat"===elem.type;if(endRepeat){var s=startRepeatPlaceholder[voiceNumber];s||(s=0);var e=skipEndingPlaceholder[voiceNumber];e||(e=voices[voiceNumber].length),voices[voiceNumber]=voices[voiceNumber].concat(voices[voiceNumber].slice(s,e)),skipEndingPlaceholder[voiceNumber]=void 0,startRepeatPlaceholder[voiceNumber]=void 0}startEnding&&(skipEndingPlaceholder[voiceNumber]=voices[voiceNumber].length),startRepeat&&(startRepeatPlaceholder[voiceNumber]=voices[voiceNumber].length);break;case"style":break;case"part":break;case"stem":case"scale":break;case"midi":var drumChange=!1;switch(elem.cmd){case"drumon":drumOn=!0,drumChange=!0;break;case"drumoff":drumOn=!1,drumChange=!0;break;case"drum":drumPattern=elem.params,drumChange=!0;break;case"drumbars":drumBars=elem.params[0],drumChange=!0}drumChange&&(voices[0].push({el_type:"drum",params:{pattern:drumPattern,bars:drumBars,intro:drumIntro,on:drumOn}}),startingDrumSet=!0);break;default:console.log("MIDI: element type "+elem.el_type+" not handled.")}}voiceNumber++}}if(drumIntro)for(var vv=0;vv<voices.length;vv++){for(var insertPoint=0;"note"!==voices[vv][insertPoint].el_type&&voices[vv].length>insertPoint;)insertPoint++;if(voices[vv].length>insertPoint)for(var w=0;w<drumIntro;w++)voices[vv].splice(insertPoint,0,{el_type:"note",rest:{type:"rest"},duration:measureLength},{el_type:"bar"})}return voices}}(),window.ABCJS||(window.ABCJS={}),window.ABCJS.parse||(window.ABCJS.parse={}),window.ABCJS.parse.clone=function(source){var destination={};for(var property in source)source.hasOwnProperty(property)&&(destination[property]=source[property]);return destination},window.ABCJS.parse.cloneArray=function(source){for(var destination=[],i=0;i<source.length;i++)destination.push(ABCJS.parse.clone(source[i]));return destination},window.ABCJS.parse.cloneHashOfHash=function(source){var destination={};for(var property in source)source.hasOwnProperty(property)&&(destination[property]=ABCJS.parse.clone(source[property]));return destination},window.ABCJS.parse.cloneHashOfArrayOfHash=function(source){var destination={};for(var property in source)source.hasOwnProperty(property)&&(destination[property]=ABCJS.parse.cloneArray(source[property]));return destination},window.ABCJS.parse.gsub=function(source,pattern,replacement){return source.split(pattern).join(replacement)},window.ABCJS.parse.strip=function(str){return str.replace(/^\s+/,"").replace(/\s+$/,"")},window.ABCJS.parse.startsWith=function(str,pattern){return 0===str.indexOf(pattern)},window.ABCJS.parse.endsWith=function(str,pattern){var d=str.length-pattern.length;return d>=0&&str.lastIndexOf(pattern)===d},window.ABCJS.parse.each=function(arr,iterator,context){for(var i=0,length=arr.length;i<length;i++)iterator.apply(context,[arr[i],i])},window.ABCJS.parse.last=function(arr){return 0===arr.length?null:arr[arr.length-1]},window.ABCJS.parse.compact=function(arr){for(var output=[],i=0;i<arr.length;i++)arr[i]&&output.push(arr[i]);return output},window.ABCJS.parse.detect=function(arr,iterator){for(var i=0;i<arr.length;i++)if(iterator(arr[i]))return!0;return!1},window.ABCJS||(window.ABCJS={}),window.ABCJS.parse||(window.ABCJS.parse={}),window.ABCJS.parse.Parse=function(){"use strict";function addPositioning(el,type,value){el.positioning||(el.positioning={}),el.positioning[type]=value}function addFont(el,type,value){el.fonts||(el.fonts={}),el.fonts[type]=value}function startNewLine(){var params={startChar:-1,endChar:-1};if(multilineVars.partForNextLine.length&&(params.part=multilineVars.partForNextLine),params.clef=multilineVars.currentVoice&&void 0!==multilineVars.staves[multilineVars.currentVoice.staffNum].clef?window.ABCJS.parse.clone(multilineVars.staves[multilineVars.currentVoice.staffNum].clef):window.ABCJS.parse.clone(multilineVars.clef),params.key=window.ABCJS.parse.parseKeyVoice.deepCopyKey(multilineVars.key),window.ABCJS.parse.parseKeyVoice.addPosToKey(params.clef,params.key),null!==multilineVars.meter?(multilineVars.currentVoice?(window.ABCJS.parse.each(multilineVars.staves,function(st){st.meter=multilineVars.meter}),params.meter=multilineVars.staves[multilineVars.currentVoice.staffNum].meter,multilineVars.staves[multilineVars.currentVoice.staffNum].meter=null):params.meter=multilineVars.meter,multilineVars.meter=null):multilineVars.currentVoice&&multilineVars.staves[multilineVars.currentVoice.staffNum].meter&&(params.meter=multilineVars.staves[multilineVars.currentVoice.staffNum].meter,multilineVars.staves[multilineVars.currentVoice.staffNum].meter=null),multilineVars.currentVoice&&multilineVars.currentVoice.name&&(params.name=multilineVars.currentVoice.name),multilineVars.vocalfont&&(params.vocalfont=multilineVars.vocalfont),multilineVars.style&&(params.style=multilineVars.style),multilineVars.currentVoice){var staff=multilineVars.staves[multilineVars.currentVoice.staffNum];staff.brace&&(params.brace=staff.brace),staff.bracket&&(params.bracket=staff.bracket),staff.connectBarLines&&(params.connectBarLines=staff.connectBarLines),staff.name&&(params.name=staff.name[multilineVars.currentVoice.index]),staff.subname&&(params.subname=staff.subname[multilineVars.currentVoice.index]),multilineVars.currentVoice.stem&&(params.stem=multilineVars.currentVoice.stem),multilineVars.currentVoice.scale&&(params.scale=multilineVars.currentVoice.scale),multilineVars.currentVoice.style&&(params.style=multilineVars.currentVoice.style),multilineVars.currentVoice.transpose&&(params.clef.transpose=multilineVars.currentVoice.transpose)}var isFirstVoice=void 0===multilineVars.currentVoice||0===multilineVars.currentVoice.staffNum&&0===multilineVars.currentVoice.index; 0===multilineVars.barNumbers&&isFirstVoice&&1!==multilineVars.currBarNumber&&(params.barNumber=multilineVars.currBarNumber),tune.startNewLine(params),multilineVars.partForNextLine=""}function durationOfMeasure(multilineVars){var meter=multilineVars.origMeter;return meter&&"specified"===meter.type&&meter.value&&0!==meter.value.length?parseInt(meter.value[0].num,10)/parseInt(meter.value[0].den,10):1}function appendLastMeasure(voice,nextVoice){voice.push({el_type:"hint"});for(var i=0;i<nextVoice.length;i++){var element=nextVoice[i],hint=window.ABCJS.parse.clone(element);if(voice.push(hint),"bar"===element.el_type)return}}function addHintMeasure(staff,nextStaff){for(var i=0;i<staff.length;i++){var stave=staff[i],nextStave=nextStaff[i];if(nextStave)for(var j=0;j<nextStave.voices.length;j++){var nextVoice=nextStave.voices[j],voice=stave.voices[j];voice&&appendLastMeasure(voice,nextVoice)}}}function addHintMeasures(){for(var i=0;i<tune.lines.length;i++){var line=tune.lines[i].staff;if(line){for(var j=i+1;j<tune.lines.length&&void 0===tune.lines[j].staff;)j++;if(j<tune.lines.length){var nextLine=tune.lines[j].staff;addHintMeasure(line,nextLine)}}}}var tune=new window.ABCJS.data.Tune,tokenizer=new window.ABCJS.parse.tokenizer;this.getTune=function(){return tune};var multilineVars={reset:function(){for(var property in this)this.hasOwnProperty(property)&&"function"!=typeof this[property]&&delete this[property];this.iChar=0,this.key={accidentals:[],root:"none",acc:"",mode:""},this.meter={type:"specified",value:[{num:"4",den:"4"}]},this.origMeter={type:"specified",value:[{num:"4",den:"4"}]},this.hasMainTitle=!1,this.default_length=.125,this.clef={type:"treble",verticalPos:0},this.next_note_duration=0,this.start_new_line=!0,this.is_in_header=!0,this.is_in_history=!1,this.partForNextLine="",this.havent_set_length=!0,this.voices={},this.staves=[],this.macros={},this.currBarNumber=1,this.inTextBlock=!1,this.inPsBlock=!1,this.ignoredDecorations=[],this.textBlock="",this.score_is_present=!1,this.inEnding=!1,this.inTie=!1,this.inTieChord={},this.vocalPosition="auto",this.dynamicPosition="auto",this.chordPosition="auto",this.ornamentPosition="auto",this.volumePosition="auto",this.openSlurs=[]},differentFont:function(type,defaultFonts){return this[type].decoration!==defaultFonts[type].decoration||(this[type].face!==defaultFonts[type].face||(this[type].size!==defaultFonts[type].size||(this[type].style!==defaultFonts[type].style||this[type].weight!==defaultFonts[type].weight)))},addFormattingOptions:function(el,defaultFonts,elType){"note"===elType?("auto"!==this.vocalPosition&&addPositioning(el,"vocalPosition",this.vocalPosition),"auto"!==this.dynamicPosition&&addPositioning(el,"dynamicPosition",this.dynamicPosition),"auto"!==this.chordPosition&&addPositioning(el,"chordPosition",this.chordPosition),"auto"!==this.ornamentPosition&&addPositioning(el,"ornamentPosition",this.ornamentPosition),"auto"!==this.volumePosition&&addPositioning(el,"volumePosition",this.volumePosition),this.differentFont("annotationfont",defaultFonts)&&addFont(el,"annotationfont",this.annotationfont),this.differentFont("gchordfont",defaultFonts)&&addFont(el,"gchordfont",this.gchordfont),this.differentFont("vocalfont",defaultFonts)&&addFont(el,"vocalfont",this.vocalfont)):"bar"===elType&&("auto"!==this.dynamicPosition&&addPositioning(el,"dynamicPosition",this.dynamicPosition),"auto"!==this.chordPosition&&addPositioning(el,"chordPosition",this.chordPosition),"auto"!==this.ornamentPosition&&addPositioning(el,"ornamentPosition",this.ornamentPosition),"auto"!==this.volumePosition&&addPositioning(el,"volumePosition",this.volumePosition),this.differentFont("measurefont",defaultFonts)&&addFont(el,"measurefont",this.measurefont),this.differentFont("repeatfont",defaultFonts)&&addFont(el,"repeatfont",this.repeatfont))}},addWarning=function(str){multilineVars.warnings||(multilineVars.warnings=[]),multilineVars.warnings.push(str)},encode=function(str){var ret=window.ABCJS.parse.gsub(str,""," ");return ret=window.ABCJS.parse.gsub(ret,"&","&amp;"),ret=window.ABCJS.parse.gsub(ret,"<","&lt;"),window.ABCJS.parse.gsub(ret,">","&gt;")},warn=function(str,line,col_num){line||(line=" ");var bad_char=line.charAt(col_num);" "===bad_char&&(bad_char="SPACE");var clean_line=encode(line.substring(0,col_num))+'<span style="text-decoration:underline;font-size:1.3em;font-weight:bold;">'+bad_char+"</span>"+encode(line.substring(col_num+1));addWarning("Music Line:"+tune.getNumLines()+":"+(col_num+1)+": "+str+": "+clean_line)},header=new window.ABCJS.parse.ParseHeader(tokenizer,warn,multilineVars,tune);this.getWarnings=function(){return multilineVars.warnings};var letter_to_chord=function(line,i){if('"'===line.charAt(i)){var chord=tokenizer.getBrackettedSubstring(line,i,5);if(chord[2]||warn("Missing the closing quote while parsing the chord symbol",line,i),chord[0]>0&&chord[1].length>0&&"^"===chord[1].charAt(0))chord[1]=chord[1].substring(1),chord[2]="above";else if(chord[0]>0&&chord[1].length>0&&"_"===chord[1].charAt(0))chord[1]=chord[1].substring(1),chord[2]="below";else if(chord[0]>0&&chord[1].length>0&&"<"===chord[1].charAt(0))chord[1]=chord[1].substring(1),chord[2]="left";else if(chord[0]>0&&chord[1].length>0&&">"===chord[1].charAt(0))chord[1]=chord[1].substring(1),chord[2]="right";else if(chord[0]>0&&chord[1].length>0&&"@"===chord[1].charAt(0)){chord[1]=chord[1].substring(1);var x=tokenizer.getFloat(chord[1]);0===x.digits&&warn("Missing first position in absolutely positioned annotation.",line,i),chord[1]=chord[1].substring(x.digits),","!==chord[1][0]&&warn("Missing comma absolutely positioned annotation.",line,i),chord[1]=chord[1].substring(1);var y=tokenizer.getFloat(chord[1]);0===y.digits&&warn("Missing second position in absolutely positioned annotation.",line,i),chord[1]=chord[1].substring(y.digits);var ws=tokenizer.skipWhiteSpace(chord[1]);chord[1]=chord[1].substring(ws),chord[2]=null,chord[3]={x:x.value,y:y.value}}else chord[1]=chord[1].replace(/([ABCDEFG])b/g,"$1♭"),chord[1]=chord[1].replace(/([ABCDEFG])#/g,"$1♯"),chord[2]="default";return chord}return[0,""]},legalAccents=["trill","lowermordent","uppermordent","mordent","pralltriller","accent","fermata","invertedfermata","tenuto","0","1","2","3","4","5","+","wedge","open","thumb","snap","turn","roll","breath","shortphrase","mediumphrase","longphrase","segno","coda","D.S.","D.C.","fine","slide","^","marcato","upbow","downbow","/","//","///","////","trem1","trem2","trem3","trem4","turnx","invertedturn","invertedturnx","trill(","trill)","arpeggio","xstem","mark","umarcato","style=normal","style=harmonic","style=rhythm","style=x"],volumeDecorations=["p","pp","f","ff","mf","mp","ppp","pppp","fff","ffff","sfz"],dynamicDecorations=["crescendo(","crescendo)","diminuendo(","diminuendo)"],accentPseudonyms=[["<","accent"],[">","accent"],["tr","trill"],["plus","+"],["emphasis","accent"],["^","umarcato"],["marcato","umarcato"]],accentDynamicPseudonyms=[["<(","crescendo("],["<)","crescendo)"],[">(","diminuendo("],[">)","diminuendo)"]],letter_to_accent=function(line,i){var macro=multilineVars.macros[line.charAt(i)];if(void 0!==macro)return"!"!==macro.charAt(0)&&"+"!==macro.charAt(0)||(macro=macro.substring(1)),"!"!==macro.charAt(macro.length-1)&&"+"!==macro.charAt(macro.length-1)||(macro=macro.substring(0,macro.length-1)),window.ABCJS.parse.detect(legalAccents,function(acc){return macro===acc})?[1,macro]:window.ABCJS.parse.detect(volumeDecorations,function(acc){return macro===acc})?("hidden"===multilineVars.volumePosition&&(macro=""),[1,macro]):window.ABCJS.parse.detect(dynamicDecorations,function(acc){return"hidden"===multilineVars.dynamicPosition&&(macro=""),macro===acc})?[1,macro]:(window.ABCJS.parse.detect(multilineVars.ignoredDecorations,function(dec){return macro===dec})||warn("Unknown macro: "+macro,line,i),[1,""]);switch(line.charAt(i)){case".":return[1,"staccato"];case"u":return[1,"upbow"];case"v":return[1,"downbow"];case"~":return[1,"irishroll"];case"!":case"+":var ret=tokenizer.getBrackettedSubstring(line,i,5);return ret[1].length>0&&("^"===ret[1].charAt(0)||"_"===ret[1].charAt(0))&&(ret[1]=ret[1].substring(1)),window.ABCJS.parse.detect(legalAccents,function(acc){return ret[1]===acc})?ret:window.ABCJS.parse.detect(volumeDecorations,function(acc){return ret[1]===acc})?("hidden"===multilineVars.volumePosition&&(ret[1]=""),ret):window.ABCJS.parse.detect(dynamicDecorations,function(acc){return ret[1]===acc})?("hidden"===multilineVars.dynamicPosition&&(ret[1]=""),ret):window.ABCJS.parse.detect(accentPseudonyms,function(acc){return ret[1]===acc[0]&&(ret[1]=acc[1],!0)})?ret:window.ABCJS.parse.detect(accentDynamicPseudonyms,function(acc){return ret[1]===acc[0]&&(ret[1]=acc[1],!0)})?("hidden"===multilineVars.dynamicPosition&&(ret[1]=""),ret):"!"!==line.charAt(i)||1!==ret[0]&&"!"===line.charAt(i+ret[0]-1)?(warn("Unknown decoration: "+ret[1],line,i),ret[1]="",ret):[1,null];case"H":return[1,"fermata"];case"J":return[1,"slide"];case"L":return[1,"accent"];case"M":return[1,"mordent"];case"O":return[1,"coda"];case"P":return[1,"pralltriller"];case"R":return[1,"roll"];case"S":return[1,"segno"];case"T":return[1,"trill"]}return[0,0]},letter_to_spacer=function(line,i){for(var start=i;tokenizer.isWhiteSpace(line.charAt(i));)i++;return[i-start]},letter_to_bar=function(line,curr_pos){var ret=tokenizer.getBarLine(line,curr_pos);if(0===ret.len)return[0,""];if(ret.warn)return warn(ret.warn,line,curr_pos),[ret.len,""];for(var ws=0;ws<line.length&&" "===line.charAt(curr_pos+ret.len+ws);ws++);var orig_bar_len=ret.len;if("["===line.charAt(curr_pos+ret.len+ws)&&(ret.len+=ws+1),'"'===line.charAt(curr_pos+ret.len)&&"["===line.charAt(curr_pos+ret.len-1)){var ending=tokenizer.getBrackettedSubstring(line,curr_pos+ret.len,5);return[ret.len+ending[0],ret.token,ending[1]]}var retRep=tokenizer.getTokenOf(line.substring(curr_pos+ret.len),"1234567890-,");return 0===retRep.len||"-"===retRep.token[0]?[orig_bar_len,ret.token]:[ret.len+retRep.len,ret.token,retRep.token]},letter_to_open_slurs_and_triplets=function(line,i){for(var ret={},start=i;"("===line.charAt(i)||tokenizer.isWhiteSpace(line.charAt(i));)"("===line.charAt(i)&&(i+1<line.length&&line.charAt(i+1)>="2"&&line.charAt(i+1)<="9"?(void 0!==ret.triplet?warn("Can't nest triplets",line,i):(ret.triplet=line.charAt(i+1)-"0",i+2<line.length&&":"===line.charAt(i+2)&&(i+3<line.length&&":"===line.charAt(i+3)?i+4<line.length&&line.charAt(i+4)>="1"&&line.charAt(i+4)<="9"?(ret.num_notes=line.charAt(i+4)-"0",i+=3):warn("expected number after the two colons after the triplet to mark the duration",line,i):i+3<line.length&&line.charAt(i+3)>="1"&&line.charAt(i+3)<="9"?i+4<line.length&&":"===line.charAt(i+4)?i+5<line.length&&line.charAt(i+5)>="1"&&line.charAt(i+5)<="9"&&(ret.num_notes=line.charAt(i+5)-"0",i+=4):(ret.num_notes=ret.triplet,i+=3):warn("expected number after the triplet to mark the duration",line,i))),i++):void 0===ret.startSlur?ret.startSlur=1:ret.startSlur++),i++;return ret.consumed=i-start,ret},addWords=function(line,words){if(!line)return void warn("Can't add words before the first line of music",line,0);words=window.ABCJS.parse.strip(words),"-"!==words.charAt(words.length-1)&&(words+=" ");for(var word_list=[],last_divider=0,replace=!1,addWord=function(i){var word=window.ABCJS.parse.strip(words.substring(last_divider,i));if(last_divider=i+1,word.length>0){replace&&(word=window.ABCJS.parse.gsub(word,"~"," "));var div=words.charAt(i);return"_"!==div&&"-"!==div&&(div=" "),word_list.push({syllable:tokenizer.translateString(word),divider:div}),replace=!1,!0}return!1},i=0;i<words.length;i++)switch(words.charAt(i)){case" ":case"":addWord(i);break;case"-":!addWord(i)&&word_list.length>0&&(window.ABCJS.parse.last(word_list).divider="-",word_list.push({skip:!0,to:"next"}));break;case"_":addWord(i),word_list.push({skip:!0,to:"slur"});break;case"*":addWord(i),word_list.push({skip:!0,to:"next"});break;case"|":addWord(i),word_list.push({skip:!0,to:"bar"});break;case"~":replace=!0}var inSlur=!1;window.ABCJS.parse.each(line,function(el){if(0!==word_list.length)if(word_list[0].skip)switch(word_list[0].to){case"next":"note"!==el.el_type||null===el.pitches||inSlur||word_list.shift();break;case"slur":"note"===el.el_type&&null!==el.pitches&&word_list.shift();break;case"bar":"bar"===el.el_type&&word_list.shift()}else if("note"===el.el_type&&void 0===el.rest&&!inSlur){var lyric=word_list.shift();void 0===el.lyric?el.lyric=[lyric]:el.lyric.push(lyric)}})},addSymbols=function(line,words){if(!line)return void warn("Can't add symbols before the first line of music",line,0);words=window.ABCJS.parse.strip(words),"-"!==words.charAt(words.length-1)&&(words+=" ");for(var word_list=[],last_divider=0,replace=!1,addWord=function(i){var word=window.ABCJS.parse.strip(words.substring(last_divider,i));if(last_divider=i+1,word.length>0){replace&&(word=window.ABCJS.parse.gsub(word,"~"," "));var div=words.charAt(i);return"_"!==div&&"-"!==div&&(div=" "),word_list.push({syllable:tokenizer.translateString(word),divider:div}),replace=!1,!0}return!1},i=0;i<words.length;i++)switch(words.charAt(i)){case" ":case"":addWord(i);break;case"-":!addWord(i)&&word_list.length>0&&(window.ABCJS.parse.last(word_list).divider="-",word_list.push({skip:!0,to:"next"}));break;case"_":addWord(i),word_list.push({skip:!0,to:"slur"});break;case"*":addWord(i),word_list.push({skip:!0,to:"next"});break;case"|":addWord(i),word_list.push({skip:!0,to:"bar"});break;case"~":replace=!0}var inSlur=!1;window.ABCJS.parse.each(line,function(el){if(0!==word_list.length)if(word_list[0].skip)switch(word_list[0].to){case"next":"note"!==el.el_type||null===el.pitches||inSlur||word_list.shift();break;case"slur":"note"===el.el_type&&null!==el.pitches&&word_list.shift();break;case"bar":"bar"===el.el_type&&word_list.shift()}else if("note"===el.el_type&&void 0===el.rest&&!inSlur){var lyric=word_list.shift();void 0===el.lyric?el.lyric=[lyric]:el.lyric.push(lyric)}})},getBrokenRhythm=function(line,index){switch(line.charAt(index)){case">":return index<line.length-1&&">"===line.charAt(index+1)?[2,1.75,.25]:[1,1.5,.5];case"<":return index<line.length-1&&"<"===line.charAt(index+1)?[2,.25,1.75]:[1,.5,1.5]}return null},addEndBeam=function(el){return void 0!==el.duration&&el.duration<.25&&(el.end_beam=!0),el},pitches={A:5,B:6,C:0,D:1,E:2,F:3,G:4,a:12,b:13,c:7,d:8,e:9,f:10,g:11},rests={x:"invisible",y:"spacer",z:"rest",Z:"multimeasure"},getCoreNote=function(line,index,el,canHaveBrokenRhythm){for(var isComplete=function(state){return"octave"===state||"duration"===state||"Zduration"===state||"broken_rhythm"===state||"end_slur"===state},state="startSlur",durationSetByPreviousNote=!1;;){switch(line.charAt(index)){case"(":if("startSlur"!==state)return isComplete(state)?(el.endChar=index,el):null;void 0===el.startSlur?el.startSlur=1:el.startSlur++;break;case")":if(!isComplete(state))return null;void 0===el.endSlur?el.endSlur=1:el.endSlur++;break;case"^":if("startSlur"===state)el.accidental="sharp",state="sharp2";else{if("sharp2"!==state)return isComplete(state)?(el.endChar=index,el):null;el.accidental="dblsharp",state="pitch"}break;case"_":if("startSlur"===state)el.accidental="flat",state="flat2";else{if("flat2"!==state)return isComplete(state)?(el.endChar=index,el):null;el.accidental="dblflat",state="pitch"}break;case"=":if("startSlur"!==state)return isComplete(state)?(el.endChar=index,el):null;el.accidental="natural",state="pitch";break;case"A":case"B":case"C":case"D":case"E":case"F":case"G":case"a":case"b":case"c":case"d":case"e":case"f":case"g":if("startSlur"!==state&&"sharp2"!==state&&"flat2"!==state&&"pitch"!==state)return isComplete(state)?(el.endChar=index,el):null;el.pitch=pitches[line.charAt(index)],state="octave",canHaveBrokenRhythm&&0!==multilineVars.next_note_duration?(el.duration=multilineVars.default_length*multilineVars.next_note_duration,multilineVars.next_note_duration=0,durationSetByPreviousNote=!0):el.duration=multilineVars.default_length;break;case",":if("octave"!==state)return isComplete(state)?(el.endChar=index,el):null;el.pitch-=7;break;case"'":if("octave"!==state)return isComplete(state)?(el.endChar=index,el):null;el.pitch+=7;break;case"x":case"y":case"z":case"Z":if("startSlur"!==state)return isComplete(state)?(el.endChar=index,el):null;el.rest={type:rests[line.charAt(index)]},delete el.accidental,delete el.startSlur,delete el.startTie,delete el.endSlur,delete el.endTie,delete el.end_beam,delete el.grace_notes,"multimeasure"===el.rest.type?(el.duration=1,state="Zduration"):(canHaveBrokenRhythm&&0!==multilineVars.next_note_duration?(el.duration=multilineVars.default_length*multilineVars.next_note_duration,multilineVars.next_note_duration=0,durationSetByPreviousNote=!0):el.duration=multilineVars.default_length,state="duration");break;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"0":case"/":if("octave"===state||"duration"===state){var fraction=tokenizer.getFraction(line,index);for(el.duration=el.duration*fraction.value,el.endChar=fraction.index;fraction.index<line.length&&(tokenizer.isWhiteSpace(line.charAt(fraction.index))||"-"===line.charAt(fraction.index));)"-"===line.charAt(fraction.index)?el.startTie={}:el=addEndBeam(el),fraction.index++;index=fraction.index-1,state="broken_rhythm"}else if("sharp2"===state)el.accidental="quartersharp",state="pitch";else{if("flat2"!==state){if("Zduration"===state){var num=tokenizer.getNumber(line,index);return el.duration=num.num,el.endChar=num.index,el}return null}el.accidental="quarterflat",state="pitch"}break;case"-":if("startSlur"===state)tune.addTieToLastNote(),el.endTie=!0;else{if("octave"!==state&&"duration"!==state&&"end_slur"!==state)return"broken_rhythm"===state?(el.endChar=index,el):null;if(el.startTie={},durationSetByPreviousNote||!canHaveBrokenRhythm)return tokenizer.isWhiteSpace(line.charAt(index+1))&&addEndBeam(el),el.endChar=index+1,el;state="broken_rhythm"}break;case" ":case"\t":if(!isComplete(state))return null;el.end_beam=!0;do"-"===line.charAt(index)&&(el.startTie={}),index++;while(index<line.length&&(tokenizer.isWhiteSpace(line.charAt(index))||"-"===line.charAt(index)));if(el.endChar=index,durationSetByPreviousNote||!canHaveBrokenRhythm||"<"!==line.charAt(index)&&">"!==line.charAt(index))return el;index--,state="broken_rhythm";break;case">":case"<":if(!isComplete(state))return null;if(!canHaveBrokenRhythm)return el.endChar=index,el;var br2=getBrokenRhythm(line,index);index+=br2[0]-1,multilineVars.next_note_duration=br2[2],el.duration=br2[1]*el.duration,state="end_slur";break;default:return isComplete(state)?(el.endChar=index,el):null}if(index++,index===line.length)return isComplete(state)?(el.endChar=index,el):null}return null},letter_to_grace=function(line,i){if("{"===line.charAt(i)){var gra=tokenizer.getBrackettedSubstring(line,i,1,"}");gra[2]||warn("Missing the closing '}' while parsing grace note",line,i),")"===line[i+gra[0]]&&(gra[0]++,gra[1]+=")");for(var gracenotes=[],ii=0,inTie=!1;ii<gra[1].length;){var acciaccatura=!1;"/"===gra[1].charAt(ii)&&(acciaccatura=!0,ii++);var note=getCoreNote(gra[1],ii,{},!1);null!==note?(note.duration=note.duration/(8*multilineVars.default_length),acciaccatura&&(note.acciaccatura=!0),gracenotes.push(note),inTie&&(note.endTie=!0,inTie=!1),note.startTie&&(inTie=!0),ii=note.endChar,delete note.endChar):(" "===gra[1].charAt(ii)?gracenotes.length>0&&(gracenotes[gracenotes.length-1].end_beam=!0):warn("Unknown character '"+gra[1].charAt(ii)+"' while parsing grace note",line,i),ii++)}if(gracenotes.length)return[gra[0],gracenotes]}return[0]},nonDecorations="ABCDEFGabcdefgxyzZ[]|^_{",parseRegularMusicLine=function(line){header.resolveTempo(),multilineVars.is_in_header=!1;for(var i=0,startOfLine=multilineVars.iChar;tokenizer.isWhiteSpace(line.charAt(i))&&i<line.length;)i++;if(i!==line.length&&"%"!==line.charAt(i)){var delayStartNewLine=multilineVars.start_new_line;void 0===multilineVars.continueall?multilineVars.start_new_line=!0:multilineVars.start_new_line=!1;var tripletNotesLeft=0,retHeader=header.letter_to_body_header(line,i);retHeader[0]>0&&(i+=retHeader[0]);for(var el={};i<line.length;){var startI=i;if("%"===line.charAt(i))break;var retInlineHeader=header.letter_to_inline_header(line,i);if(retInlineHeader[0]>0)i+=retInlineHeader[0];else{delayStartNewLine&&(startNewLine(),delayStartNewLine=!1);for(var ret;;)if(ret=tokenizer.eatWhiteSpace(line,i),ret>0&&(i+=ret),i>0&&""===line.charAt(i-1)&&(ret=header.letter_to_body_header(line,i),ret[0]>0&&(i=ret[0],multilineVars.start_new_line=!1)),ret=letter_to_spacer(line,i),ret[0]>0&&(i+=ret[0]),ret=letter_to_chord(line,i),ret[0]>0){el.chord||(el.chord=[]);var chordName=tokenizer.translateString(ret[1]);chordName=chordName.replace(/;/g,"\n");for(var addedChord=!1,ci=0;ci<el.chord.length;ci++)el.chord[ci].position===ret[2]&&(addedChord=!0,el.chord[ci].name+="\n"+chordName);addedChord===!1&&(null===ret[2]&&ret[3]?el.chord.push({name:chordName,rel_position:ret[3]}):el.chord.push({name:chordName,position:ret[2]})),i+=ret[0];var ii=tokenizer.skipWhiteSpace(line.substring(i));ii>0&&(el.force_end_beam_last=!0),i+=ii}else if(ret=nonDecorations.indexOf(line.charAt(i))===-1?letter_to_accent(line,i):[0],ret[0]>0)null===ret[1]?i+1<line.length&&startNewLine():ret[1].length>0&&(0===ret[1].indexOf("style=")?el.style=ret[1].substr(6):(void 0===el.decoration&&(el.decoration=[]),el.decoration.push(ret[1]))),i+=ret[0];else{if(ret=letter_to_grace(line,i),!(ret[0]>0))break;el.gracenotes=ret[1],i+=ret[0]}if(ret=letter_to_bar(line,i),ret[0]>0){void 0!==el.gracenotes&&(el.rest={type:"spacer"},el.duration=.125,multilineVars.addFormattingOptions(el,tune.formatting,"note"),tune.appendElement("note",startOfLine+i,startOfLine+i+ret[0],el),multilineVars.measureNotEmpty=!0,el={});var bar={type:ret[1]};if(0===bar.type.length)warn("Unknown bar type",line,i);else{if(multilineVars.inEnding&&"bar_thin"!==bar.type&&(bar.endEnding=!0,multilineVars.inEnding=!1),ret[2]&&(bar.startEnding=ret[2],multilineVars.inEnding&&(bar.endEnding=!0),multilineVars.inEnding=!0),void 0!==el.decoration&&(bar.decoration=el.decoration),void 0!==el.chord&&(bar.chord=el.chord),bar.startEnding&&void 0===multilineVars.barFirstEndingNum?multilineVars.barFirstEndingNum=multilineVars.currBarNumber:bar.startEnding&&bar.endEnding&&multilineVars.barFirstEndingNum?multilineVars.currBarNumber=multilineVars.barFirstEndingNum:bar.endEnding&&(multilineVars.barFirstEndingNum=void 0),"bar_invisible"!==bar.type&&multilineVars.measureNotEmpty){var isFirstVoice=void 0===multilineVars.currentVoice||0===multilineVars.currentVoice.staffNum&&0===multilineVars.currentVoice.index;isFirstVoice&&(multilineVars.currBarNumber++,multilineVars.barNumbers&&multilineVars.currBarNumber%multilineVars.barNumbers===0&&(bar.barNumber=multilineVars.currBarNumber))}multilineVars.addFormattingOptions(el,tune.formatting,"bar"),tune.appendElement("bar",startOfLine+i,startOfLine+i+ret[0],bar),multilineVars.measureNotEmpty=!1,el={}}i+=ret[0]}else if("&"===line[i])warn("Overlay not yet supported",line,i),i++;else{if(ret=letter_to_open_slurs_and_triplets(line,i),ret.consumed>0&&(void 0!==ret.startSlur&&(el.startSlur=ret.startSlur),void 0!==ret.triplet&&(tripletNotesLeft>0?warn("Can't nest triplets",line,i):(el.startTriplet=ret.triplet,tripletNotesLeft=void 0===ret.num_notes?ret.triplet:ret.num_notes)),i+=ret.consumed),"["===line.charAt(i)){var chordStartChar=i;i++;for(var chordDuration=null,done=!1;!done;){var chordNote=getCoreNote(line,i,{},!1);if(null!==chordNote)chordNote.end_beam&&(el.end_beam=!0,delete chordNote.end_beam),void 0===el.pitches?(el.duration=chordNote.duration,el.pitches=[chordNote]):el.pitches.push(chordNote),delete chordNote.duration,multilineVars.inTieChord[el.pitches.length]&&(chordNote.endTie=!0,multilineVars.inTieChord[el.pitches.length]=void 0),chordNote.startTie&&(multilineVars.inTieChord[el.pitches.length]=!0),i=chordNote.endChar,delete chordNote.endChar;else if(" "===line.charAt(i))warn("Spaces are not allowed in chords",line,i),i++;else{if(i<line.length&&"]"===line.charAt(i)){i++,0!==multilineVars.next_note_duration&&(el.duration=el.duration*multilineVars.next_note_duration,multilineVars.next_note_duration=0),multilineVars.inTie&&(window.ABCJS.parse.each(el.pitches,function(pitch){pitch.endTie=!0}),multilineVars.inTie=!1),tripletNotesLeft>0&&(tripletNotesLeft--,0===tripletNotesLeft&&(el.endTriplet=!0));for(var postChordDone=!1;i<line.length&&!postChordDone;){switch(line.charAt(i)){case" ":case"\t":addEndBeam(el);break;case")":void 0===el.endSlur?el.endSlur=1:el.endSlur++;break;case"-":window.ABCJS.parse.each(el.pitches,function(pitch){pitch.startTie={}}),multilineVars.inTie=!0;break;case">":case"<":var br2=getBrokenRhythm(line,i);i+=br2[0]-1,multilineVars.next_note_duration=br2[2],chordDuration?chordDuration*=br2[1]:chordDuration=br2[1];break;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"/":var fraction=tokenizer.getFraction(line,i);chordDuration=fraction.value,i=fraction.index,"-"===line.charAt(i)||")"===line.charAt(i)||" "===line.charAt(i)||"<"===line.charAt(i)||">"===line.charAt(i)?i--:postChordDone=!0;break;default:postChordDone=!0}postChordDone||i++}}else warn("Expected ']' to end the chords",line,i);void 0!==el.pitches&&(null!==chordDuration&&(el.duration=el.duration*chordDuration),multilineVars.addFormattingOptions(el,tune.formatting,"note"),tune.appendElement("note",startOfLine+chordStartChar,startOfLine+i,el),multilineVars.measureNotEmpty=!0,el={}),done=!0}}}else{var el2={},core=getCoreNote(line,i,el2,!0);void 0!==el2.endTie&&(multilineVars.inTie=!0),null!==core&&(void 0!==core.pitch?(el.pitches=[{}],void 0!==core.accidental&&(el.pitches[0].accidental=core.accidental),el.pitches[0].pitch=core.pitch,void 0!==core.endSlur&&(el.pitches[0].endSlur=core.endSlur),void 0!==core.endTie&&(el.pitches[0].endTie=core.endTie),void 0!==core.startSlur&&(el.pitches[0].startSlur=core.startSlur),void 0!==el.startSlur&&(el.pitches[0].startSlur=el.startSlur),void 0!==core.startTie&&(el.pitches[0].startTie=core.startTie),void 0!==el.startTie&&(el.pitches[0].startTie=el.startTie)):(el.rest=core.rest,void 0!==core.endSlur&&(el.endSlur=core.endSlur),void 0!==core.endTie&&(el.rest.endTie=core.endTie),void 0!==core.startSlur&&(el.startSlur=core.startSlur),void 0!==core.startTie&&(el.rest.startTie=core.startTie),void 0!==el.startTie&&(el.rest.startTie=el.startTie)),void 0!==core.chord&&(el.chord=core.chord),void 0!==core.duration&&(el.duration=core.duration),void 0!==core.decoration&&(el.decoration=core.decoration),void 0!==core.graceNotes&&(el.graceNotes=core.graceNotes),delete el.startSlur,multilineVars.inTie&&(void 0!==el.pitches?(el.pitches[0].endTie=!0,multilineVars.inTie=!1):"spacer"!==el.rest.type&&(el.rest.endTie=!0,multilineVars.inTie=!1)),(core.startTie||el.startTie)&&(multilineVars.inTie=!0),i=core.endChar,tripletNotesLeft>0&&(tripletNotesLeft--,0===tripletNotesLeft&&(el.endTriplet=!0)),core.end_beam&&addEndBeam(el),el.rest&&"rest"===el.rest.type&&1===el.duration&&(el.rest.type="whole",el.duration=durationOfMeasure(multilineVars)),multilineVars.addFormattingOptions(el,tune.formatting,"note"),tune.appendElement("note",startOfLine+startI,startOfLine+i,el),multilineVars.measureNotEmpty=!0,el={})}i===startI&&(" "!==line.charAt(i)&&"`"!==line.charAt(i)&&warn("Unknown character ignored",line,i),i++)}}}}},parseLine=function(line){var ret=header.parseHeader(line);ret.regular&&parseRegularMusicLine(ret.str),ret.newline&&void 0===multilineVars.continueall&&startNewLine(),ret.words&&addWords(tune.getCurrentVoice(),line.substring(2)),ret.symbols&&addSymbols(tune.getCurrentVoice(),line.substring(2)),ret.recurse&&parseLine(ret.str)};this.parse=function(strTune,switches){switches||(switches={}),tune.reset(),switches.print&&(tune.media="print"),multilineVars.reset(),header.reset(tokenizer,warn,multilineVars,tune),strTune=window.ABCJS.parse.gsub(strTune,"\r\n","\n"),strTune=window.ABCJS.parse.gsub(strTune,"\r","\n"),strTune+="\n",strTune=strTune.replace(/\n\\.*\n/g,"\n");var continuationReplacement=function(all,backslash,comment){var spaces=" ",padding=comment?spaces.substring(0,comment.length):"";return backslash+" "+padding};strTune=strTune.replace(/\\([ \t]*)(%.*)*\n/g,continuationReplacement);var lines=strTune.split("\n");0===window.ABCJS.parse.last(lines).length&&lines.pop();try{switches.format&&window.ABCJS.parse.parseDirective.globalFormatting(switches.format),window.ABCJS.parse.each(lines,function(line){if(switches.header_only&&multilineVars.is_in_header===!1)throw"normal_abort";if(switches.stop_on_warning&&multilineVars.warnings)throw"normal_abort";multilineVars.is_in_history?":"===line.charAt(1)?(multilineVars.is_in_history=!1,parseLine(line)):tune.addMetaText("history",tokenizer.translateString(tokenizer.stripComment(line))):multilineVars.inTextBlock?window.ABCJS.parse.startsWith(line,"%%endtext")?(tune.addText(multilineVars.textBlock),multilineVars.inTextBlock=!1):window.ABCJS.parse.startsWith(line,"%%")?multilineVars.textBlock+=" "+line.substring(2):multilineVars.textBlock+=" "+line:multilineVars.inPsBlock?window.ABCJS.parse.startsWith(line,"%%endps")?multilineVars.inPsBlock=!1:multilineVars.textBlock+=" "+line:parseLine(line),multilineVars.iChar+=line.length+1});var ph=792,pl=612;switch(multilineVars.papersize){case"legal":ph=1008,pl=612;break;case"A4":ph=842.4,pl=597.6}if(multilineVars.landscape){var x=ph;ph=pl,pl=x}multilineVars.openSlurs=tune.cleanUp(pl,ph,multilineVars.barsperstaff,multilineVars.staffnonote,multilineVars.openSlurs)}catch(err){if("normal_abort"!==err)throw err}switches.hint_measures&&addHintMeasures()}},window.ABCJS||(window.ABCJS={}),window.ABCJS.parse||(window.ABCJS.parse={}),window.ABCJS.parse.parseDirective={},function(){"use strict";function initializeFonts(){multilineVars.annotationfont={face:"Helvetica",size:12,weight:"normal",style:"normal",decoration:"none"},multilineVars.gchordfont={face:"Helvetica",size:12,weight:"normal",style:"normal",decoration:"none"},multilineVars.historyfont={face:'"Times New Roman"',size:16,weight:"normal",style:"normal",decoration:"none"},multilineVars.infofont={face:'"Times New Roman"',size:14,weight:"normal",style:"italic",decoration:"none"},multilineVars.measurefont={face:'"Times New Roman"',size:14,weight:"normal",style:"italic",decoration:"none"},multilineVars.partsfont={face:'"Times New Roman"',size:15,weight:"normal",style:"normal",decoration:"none"},multilineVars.repeatfont={face:'"Times New Roman"',size:13,weight:"normal",style:"normal",decoration:"none"},multilineVars.textfont={face:'"Times New Roman"',size:16,weight:"normal",style:"normal",decoration:"none"},multilineVars.vocalfont={face:'"Times New Roman"',size:13,weight:"bold",style:"normal",decoration:"none"},multilineVars.wordsfont={face:'"Times New Roman"',size:16,weight:"normal",style:"normal",decoration:"none"},tune.formatting.composerfont={face:'"Times New Roman"',size:14,weight:"normal",style:"italic",decoration:"none"},tune.formatting.subtitlefont={face:'"Times New Roman"',size:16,weight:"normal",style:"normal",decoration:"none"},tune.formatting.tempofont={face:'"Times New Roman"',size:15,weight:"bold",style:"normal",decoration:"none"},tune.formatting.titlefont={face:'"Times New Roman"',size:20,weight:"normal",style:"normal",decoration:"none"},tune.formatting.footerfont={face:'"Times New Roman"',size:12,weight:"normal",style:"normal",decoration:"none"},tune.formatting.headerfont={face:'"Times New Roman"',size:12,weight:"normal",style:"normal",decoration:"none"},tune.formatting.voicefont={face:'"Times New Roman"',size:13,weight:"bold",style:"normal",decoration:"none"},tune.formatting.annotationfont=multilineVars.annotationfont,tune.formatting.gchordfont=multilineVars.gchordfont,tune.formatting.historyfont=multilineVars.historyfont,tune.formatting.infofont=multilineVars.infofont, tune.formatting.measurefont=multilineVars.measurefont,tune.formatting.partsfont=multilineVars.partsfont,tune.formatting.repeatfont=multilineVars.repeatfont,tune.formatting.textfont=multilineVars.textfont,tune.formatting.vocalfont=multilineVars.vocalfont,tune.formatting.wordsfont=multilineVars.wordsfont}var tokenizer,warn,multilineVars,tune;window.ABCJS.parse.parseDirective.initialize=function(tokenizer_,warn_,multilineVars_,tune_){tokenizer=tokenizer_,warn=warn_,multilineVars=multilineVars_,tune=tune_,initializeFonts()};var fontTypeCanHaveBox={gchordfont:!0,measurefont:!0,partsfont:!0},fontTranslation=function(fontFace){switch(fontFace){case"Arial-Italic":return{face:"Arial",weight:"normal",style:"italic",decoration:"none"};case"Arial-Bold":return{face:"Arial",weight:"bold",style:"normal",decoration:"none"};case"Bookman-Demi":return{face:"Bookman,serif",weight:"bold",style:"normal",decoration:"none"};case"Bookman-DemiItalic":return{face:"Bookman,serif",weight:"bold",style:"italic",decoration:"none"};case"Bookman-Light":return{face:"Bookman,serif",weight:"normal",style:"normal",decoration:"none"};case"Bookman-LightItalic":return{face:"Bookman,serif",weight:"normal",style:"italic",decoration:"none"};case"Courier":return{face:'"Courier New"',weight:"normal",style:"normal",decoration:"none"};case"Courier-Oblique":return{face:'"Courier New"',weight:"normal",style:"italic",decoration:"none"};case"Courier-Bold":return{face:'"Courier New"',weight:"bold",style:"normal",decoration:"none"};case"Courier-BoldOblique":return{face:'"Courier New"',weight:"bold",style:"italic",decoration:"none"};case"AvantGarde-Book":return{face:"AvantGarde,Arial",weight:"normal",style:"normal",decoration:"none"};case"AvantGarde-BookOblique":return{face:"AvantGarde,Arial",weight:"normal",style:"italic",decoration:"none"};case"AvantGarde-Demi":case"Avant-Garde-Demi":return{face:"AvantGarde,Arial",weight:"bold",style:"normal",decoration:"none"};case"AvantGarde-DemiOblique":return{face:"AvantGarde,Arial",weight:"bold",style:"italic",decoration:"none"};case"Helvetica-Oblique":return{face:"Helvetica",weight:"normal",style:"italic",decoration:"none"};case"Helvetica-Bold":return{face:"Helvetica",weight:"bold",style:"normal",decoration:"none"};case"Helvetica-BoldOblique":return{face:"Helvetica",weight:"bold",style:"italic",decoration:"none"};case"Helvetica-Narrow":return{face:'"Helvetica Narrow",Helvetica',weight:"normal",style:"normal",decoration:"none"};case"Helvetica-Narrow-Oblique":return{face:'"Helvetica Narrow",Helvetica',weight:"normal",style:"italic",decoration:"none"};case"Helvetica-Narrow-Bold":return{face:'"Helvetica Narrow",Helvetica',weight:"bold",style:"normal",decoration:"none"};case"Helvetica-Narrow-BoldOblique":return{face:'"Helvetica Narrow",Helvetica',weight:"bold",style:"italic",decoration:"none"};case"Palatino-Roman":return{face:"Palatino",weight:"normal",style:"normal",decoration:"none"};case"Palatino-Italic":return{face:"Palatino",weight:"normal",style:"italic",decoration:"none"};case"Palatino-Bold":return{face:"Palatino",weight:"bold",style:"normal",decoration:"none"};case"Palatino-BoldItalic":return{face:"Palatino",weight:"bold",style:"italic",decoration:"none"};case"NewCenturySchlbk-Roman":return{face:'"New Century",serif',weight:"normal",style:"normal",decoration:"none"};case"NewCenturySchlbk-Italic":return{face:'"New Century",serif',weight:"normal",style:"italic",decoration:"none"};case"NewCenturySchlbk-Bold":return{face:'"New Century",serif',weight:"bold",style:"normal",decoration:"none"};case"NewCenturySchlbk-BoldItalic":return{face:'"New Century",serif',weight:"bold",style:"italic",decoration:"none"};case"Times":case"Times-Roman":case"Times-Narrow":case"Times-Courier":case"Times-New-Roman":return{face:'"Times New Roman"',weight:"normal",style:"normal",decoration:"none"};case"Times-Italic":case"Times-Italics":return{face:'"Times New Roman"',weight:"normal",style:"italic",decoration:"none"};case"Times-Bold":return{face:'"Times New Roman"',weight:"bold",style:"normal",decoration:"none"};case"Times-BoldItalic":return{face:'"Times New Roman"',weight:"bold",style:"italic",decoration:"none"};case"ZapfChancery-MediumItalic":return{face:'"Zapf Chancery",cursive,serif',weight:"normal",style:"normal",decoration:"none"};default:return null}},getFontParameter=function(tokens,currentSetting,str,position,cmd){function processNumberOnly(){var size=parseInt(tokens[0].token);return tokens.shift(),currentSetting?0===tokens.length?{face:currentSetting.face,weight:currentSetting.weight,style:currentSetting.style,decoration:currentSetting.decoration,size:size}:1===tokens.length&&"box"===tokens[0].token&&fontTypeCanHaveBox[cmd]?{face:currentSetting.face,weight:currentSetting.weight,style:currentSetting.style,decoration:currentSetting.decoration,size:size,box:!0}:(warn("Extra parameters in font definition.",str,position),{face:currentSetting.face,weight:currentSetting.weight,style:currentSetting.style,decoration:currentSetting.decoration,size:size}):(warn("Can't set just the size of the font since there is no default value.",str,position),{face:'"Times New Roman"',weight:"normal",style:"normal",decoration:"none",size:size})}if("*"===tokens[0].token){if(tokens.shift(),"number"===tokens[0].type)return processNumberOnly();warn("Expected font size number after *.",str,position)}if("number"===tokens[0].type)return processNumberOnly();for(var size,face=[],weight="normal",style="normal",decoration="none",box=!1,state="face",hyphenLast=!1;tokens.length;){var currToken=tokens.shift(),word=currToken.token.toLowerCase();switch(state){case"face":hyphenLast||"utf"!==word&&"number"!==currToken.type&&"bold"!==word&&"italic"!==word&&"underline"!==word&&"box"!==word?face.length>0&&"-"===currToken.token?(hyphenLast=!0,face[face.length-1]=face[face.length-1]+currToken.token):hyphenLast?(hyphenLast=!1,face[face.length-1]=face[face.length-1]+currToken.token):face.push(currToken.token):"number"===currToken.type?(size?warn("Font size specified twice in font definition.",str,position):size=currToken.token,state="modifier"):"bold"===word?weight="bold":"italic"===word?style="italic":"underline"===word?decoration="underline":"box"===word?(fontTypeCanHaveBox[cmd]?box=!0:warn('This font style doesn\'t support "box"',str,position),state="finished"):"utf"===word?(currToken=tokens.shift(),state="size"):warn("Unknown parameter "+currToken.token+" in font definition.",str,position);break;case"size":"number"===currToken.type?size?warn("Font size specified twice in font definition.",str,position):size=currToken.token:warn("Expected font size in font definition.",str,position),state="modifier";break;case"modifier":"bold"===word?weight="bold":"italic"===word?style="italic":"underline"===word?decoration="underline":"box"===word?(fontTypeCanHaveBox[cmd]?box=!0:warn('This font style doesn\'t support "box"',str,position),state="finished"):warn("Unknown parameter "+currToken.token+" in font definition.",str,position);break;case"finished":warn('Extra characters found after "box" in font definition.',str,position)}}void 0===size?currentSetting?size=currentSetting.size:(warn("Must specify the size of the font since there is no default value.",str,position),size=12):size=parseFloat(size),face=face.join(" ");var psFont=fontTranslation(face),font={};return psFont?(font.face=psFont.face,font.weight=psFont.weight,font.style=psFont.style,font.decoration=psFont.decoration,font.size=size,box&&(font.box=!0),font):(font.face=face,font.weight=weight,font.style=style,font.decoration=decoration,font.size=size,box&&(font.box=!0),font)},getChangingFont=function(cmd,tokens,str){return 0===tokens.length?'Directive "'+cmd+'" requires a font as a parameter.':(multilineVars[cmd]=getFontParameter(tokens,multilineVars[cmd],str,0,cmd),multilineVars.is_in_header&&(tune.formatting[cmd]=multilineVars[cmd]),null)},getGlobalFont=function(cmd,tokens,str){return 0===tokens.length?'Directive "'+cmd+'" requires a font as a parameter.':(tune.formatting[cmd]=getFontParameter(tokens,tune.formatting[cmd],str,0,cmd),null)},setScale=function(cmd,tokens){var scratch="";window.ABCJS.parse.each(tokens,function(tok){scratch+=tok.token});var num=parseFloat(scratch);return isNaN(num)||0===num?'Directive "'+cmd+'" requires a number as a parameter.':void(tune.formatting.scale=num)},getRequiredMeasurement=function(cmd,tokens){var points=tokenizer.getMeasurement(tokens);return 0===points.used||0!==tokens.length?{error:'Directive "'+cmd+'" requires a measurement as a parameter.'}:points.value},oneParameterMeasurement=function(cmd,tokens){var points=tokenizer.getMeasurement(tokens);return 0===points.used||0!==tokens.length?'Directive "'+cmd+'" requires a measurement as a parameter.':(tune.formatting[cmd]=points.value,null)},addMultilineVar=function(key,cmd,tokens,min,max){if(1!==tokens.length||"number"!==tokens[0].type)return'Directive "'+cmd+'" requires a number as a parameter.';var i=tokens[0].intt;return void 0!==min&&i<min?'Directive "'+cmd+'" requires a number greater than or equal to '+min+" as a parameter.":void 0!==max&&i>max?'Directive "'+cmd+'" requires a number less than or equal to '+max+" as a parameter.":(multilineVars[key]=i,null)},addMultilineVarBool=function(key,cmd,tokens){var str=addMultilineVar(key,cmd,tokens,0,1);return null!==str?str:(multilineVars[key]=1===multilineVars[key],null)},addMultilineVarOneParamChoice=function(key,cmd,tokens,choices){if(1!==tokens.length)return'Directive "'+cmd+'" requires one of [ '+choices.join(", ")+" ] as a parameter.";for(var choice=tokens[0].token,found=!1,i=0;!found&&i<choices.length;i++)choices[i]===choice&&(found=!0);return found?(multilineVars[key]=choice,null):'Directive "'+cmd+'" requires one of [ '+choices.join(", ")+" ] as a parameter."},midiCmdParam0=["nobarlines","barlines","beataccents","nobeataccents","droneon","droneoff","drumon","drumoff","fermatafixed","fermataproportional","gchordon","gchordoff","controlcombo","temperamentnormal","noportamento"],midiCmdParam1String=["gchord","ptstress","beatstring"],midiCmdParam1Integer=["bassvol","chordvol","c","channel","beatmod","deltaloudness","drumbars","gracedivider","makechordchannels","randomchordattack","chordattack","stressmodel","transpose","rtranspose","volinc"],midiCmdParam1Integer1OptionalInteger=["program"],midiCmdParam2Integer=["ratio","snt","bendvelocity","pitchbend","control","temperamentlinear"],midiCmdParam4Integer=["beat"],midiCmdParam5Integer=["drone"],midiCmdParam1String1Integer=["drummap","portamento"],midiCmdParamFraction=["expand","grace","trim"],midiCmdParam1StringVariableIntegers=["drum","chordname"],parseMidiCommand=function(midi,tune,restOfString){var midi_cmd=midi.shift().token,midi_params=[];if(midiCmdParam0.indexOf(midi_cmd)>=0)0!==midi.length&&warn("Unexpected parameter in MIDI "+midi_cmd,restOfString,0);else if(midiCmdParam1String.indexOf(midi_cmd)>=0)1!==midi.length?warn("Expected one parameter in MIDI "+midi_cmd,restOfString,0):midi_params.push(midi[0].token);else if(midiCmdParam1Integer.indexOf(midi_cmd)>=0)1!==midi.length?warn("Expected one parameter in MIDI "+midi_cmd,restOfString,0):"number"!==midi[0].type?warn("Expected one integer parameter in MIDI "+midi_cmd,restOfString,0):midi_params.push(midi[0].intt);else if(midiCmdParam1Integer1OptionalInteger.indexOf(midi_cmd)>=0)1!==midi.length&&2!==midi.length?warn("Expected one or two parameters in MIDI "+midi_cmd,restOfString,0):"number"!==midi[0].type?warn("Expected integer parameter in MIDI "+midi_cmd,restOfString,0):2===midi.length&&"number"!==midi[1].type?warn("Expected integer parameter in MIDI "+midi_cmd,restOfString,0):(midi_params.push(midi[0].intt),2===midi.length&&midi_params.push(midi[1].intt));else if(midiCmdParam2Integer.indexOf(midi_cmd)>=0)2!==midi.length?warn("Expected two parameters in MIDI "+midi_cmd,restOfString,0):"number"!==midi[0].type||"number"!==midi[1].type?warn("Expected two integer parameters in MIDI "+midi_cmd,restOfString,0):(midi_params.push(midi[0].intt),midi_params.push(midi[1].intt));else if(midiCmdParam1String1Integer.indexOf(midi_cmd)>=0)2!==midi.length?warn("Expected two parameters in MIDI "+midi_cmd,restOfString,0):"alpha"!==midi[0].type||"number"!==midi[1].type?warn("Expected one string and one integer parameters in MIDI "+midi_cmd,restOfString,0):(midi_params.push(midi[0].token),midi_params.push(midi[1].intt));else if(midiCmdParamFraction.indexOf(midi_cmd)>=0)3!==midi.length?warn("Expected fraction parameter in MIDI "+midi_cmd,restOfString,0):"number"!==midi[0].type||"/"!==midi[1].token||"number"!==midi[2].type?warn("Expected fraction parameter in MIDI "+midi_cmd,restOfString,0):(midi_params.push(midi[0].intt),midi_params.push(midi[2].intt));else if(midiCmdParam4Integer.indexOf(midi_cmd)>=0)4!==midi.length?warn("Expected four parameters in MIDI "+midi_cmd,restOfString,0):"number"!==midi[0].type||"number"!==midi[1].type||"number"!==midi[2].type||"number"!==midi[3].type?warn("Expected four integer parameters in MIDI "+midi_cmd,restOfString,0):(midi_params.push(midi[0].intt),midi_params.push(midi[1].intt),midi_params.push(midi[2].intt),midi_params.push(midi[3].intt));else if(midiCmdParam5Integer.indexOf(midi_cmd)>=0)5!==midi.length?warn("Expected five parameters in MIDI "+midi_cmd,restOfString,0):"number"!==midi[0].type||"number"!==midi[1].type||"number"!==midi[2].type||"number"!==midi[3].type||"number"!==midi[4].type?warn("Expected five integer parameters in MIDI "+midi_cmd,restOfString,0):(midi_params.push(midi[0].intt),midi_params.push(midi[1].intt),midi_params.push(midi[2].intt),midi_params.push(midi[3].intt),midi_params.push(midi[4].intt));else if(midiCmdParam1Integer1OptionalInteger.indexOf(midi_cmd)>=0)1!==midi.length||4!==midi.length?warn("Expected one or two parameters in MIDI "+midi_cmd,restOfString,0):"number"!==midi[0].type?warn("Expected integer parameter in MIDI "+midi_cmd,restOfString,0):4===midi.length?("octave"!==midi[1].token&&warn("Expected octave parameter in MIDI "+midi_cmd,restOfString,0),"="!==midi[2].token&&warn("Expected octave parameter in MIDI "+midi_cmd,restOfString,0),"number"!==midi[3].type&&warn("Expected integer parameter for octave in MIDI "+midi_cmd,restOfString,0)):(midi_params.push(midi[0].intt),4===midi.length&&midi_params.push(midi[3].intt));else if(midiCmdParam1StringVariableIntegers.indexOf(midi_cmd)>=0)if(midi.length<2)warn("Expected string parameter and at least one integer parameter in MIDI "+midi_cmd,restOfString,0);else if("alpha"!==midi[0].type)warn("Expected string parameter and at least one integer parameter in MIDI "+midi_cmd,restOfString,0);else{var p=midi.shift();for(midi_params.push(p.token);midi.length>0;)p=midi.shift(),"number"!==p.type&&warn("Expected integer parameter in MIDI "+midi_cmd,restOfString,0),midi_params.push(p.intt)}tune.hasBeginMusic()?tune.appendElement("midi",-1,-1,{cmd:midi_cmd,params:midi_params}):(void 0===tune.formatting.midi&&(tune.formatting.midi={}),tune.formatting.midi[midi_cmd]=midi_params)};window.ABCJS.parse.parseDirective.parseFontChangeLine=function(textstr){var textParts=textstr.split("$");if(textParts.length>1&&multilineVars.setfont){for(var textarr=[{text:textParts[0]}],i=1;i<textParts.length;i++)"0"===textParts[i].charAt(0)?textarr.push({text:textParts[i].substring(1)}):"1"===textParts[i].charAt(0)&&multilineVars.setfont[1]?textarr.push({font:multilineVars.setfont[1],text:textParts[i].substring(1)}):"2"===textParts[i].charAt(0)&&multilineVars.setfont[2]?textarr.push({font:multilineVars.setfont[2],text:textParts[i].substring(1)}):"3"===textParts[i].charAt(0)&&multilineVars.setfont[3]?textarr.push({font:multilineVars.setfont[3],text:textParts[i].substring(1)}):"4"===textParts[i].charAt(0)&&multilineVars.setfont[4]?textarr.push({font:multilineVars.setfont[4],text:textParts[i].substring(1)}):textarr[textarr.length-1].text+="$"+textParts[i];if(textarr.length>1)return textarr}return textstr};var positionChoices=["auto","above","below","hidden"];window.ABCJS.parse.parseDirective.addDirective=function(str){var tokens=tokenizer.tokenize(str,0,str.length);if(0===tokens.length||"alpha"!==tokens[0].type)return null;var restOfString=str.substring(str.indexOf(tokens[0].token)+tokens[0].token.length);restOfString=tokenizer.stripComment(restOfString);var cmd=tokens.shift().token.toLowerCase(),scratch="";switch(cmd){case"bagpipes":tune.formatting.bagpipes=!0;break;case"landscape":multilineVars.landscape=!0;break;case"papersize":multilineVars.papersize=restOfString;break;case"slurgraces":tune.formatting.slurgraces=!0;break;case"stretchlast":tune.formatting.stretchlast=!0;break;case"titlecaps":multilineVars.titlecaps=!0;break;case"titleleft":tune.formatting.titleleft=!0;break;case"measurebox":tune.formatting.measurebox=!0;break;case"vocal":return addMultilineVarOneParamChoice("vocalPosition",cmd,tokens,positionChoices);case"dynamic":return addMultilineVarOneParamChoice("dynamicPosition",cmd,tokens,positionChoices);case"gchord":return addMultilineVarOneParamChoice("chordPosition",cmd,tokens,positionChoices);case"ornament":return addMultilineVarOneParamChoice("ornamentPosition",cmd,tokens,positionChoices);case"volume":return addMultilineVarOneParamChoice("volumePosition",cmd,tokens,positionChoices);case"botmargin":case"botspace":case"composerspace":case"indent":case"leftmargin":case"linesep":case"musicspace":case"partsspace":case"pageheight":case"pagewidth":case"rightmargin":case"staffsep":case"staffwidth":case"subtitlespace":case"sysstaffsep":case"systemsep":case"textspace":case"titlespace":case"topmargin":case"topspace":case"vocalspace":case"wordsspace":return oneParameterMeasurement(cmd,tokens);case"vskip":var vskip=getRequiredMeasurement(cmd,tokens);return vskip.error?vskip.error:(tune.addSpacing(vskip),null);case"scale":setScale(cmd,tokens);break;case"sep":if(0===tokens.length)tune.addSeparator();else{var points=tokenizer.getMeasurement(tokens);if(0===points.used)return'Directive "'+cmd+'" requires 3 numbers: space above, space below, length of line';var spaceAbove=points.value;if(points=tokenizer.getMeasurement(tokens),0===points.used)return'Directive "'+cmd+'" requires 3 numbers: space above, space below, length of line';var spaceBelow=points.value;if(points=tokenizer.getMeasurement(tokens),0===points.used||0!==tokens.length)return'Directive "'+cmd+'" requires 3 numbers: space above, space below, length of line';var lenLine=points.value;tune.addSeparator(spaceAbove,spaceBelow,lenLine)}break;case"barsperstaff":if(scratch=addMultilineVar("barsperstaff",cmd,tokens),null!==scratch)return scratch;break;case"staffnonote":if(scratch=addMultilineVarBool("staffnonote",cmd,tokens),null!==scratch)return scratch;break;case"printtempo":if(scratch=addMultilineVarBool("printTempo",cmd,tokens),null!==scratch)return scratch;break;case"partsbox":if(scratch=addMultilineVarBool("partsBox",cmd,tokens),null!==scratch)return scratch;break;case"measurenb":case"barnumbers":if(scratch=addMultilineVar("barNumbers",cmd,tokens),null!==scratch)return scratch;break;case"begintext":multilineVars.inTextBlock=!0;break;case"continueall":multilineVars.continueall=!0;break;case"beginps":multilineVars.inPsBlock=!0,warn("Postscript ignored",str,0);break;case"deco":restOfString.length>0&&multilineVars.ignoredDecorations.push(restOfString.substring(0,restOfString.indexOf(" "))),warn("Decoration redefinition ignored",str,0);break;case"text":var textstr=tokenizer.translateString(restOfString);tune.addText(window.ABCJS.parse.parseDirective.parseFontChangeLine(textstr));break;case"center":var centerstr=tokenizer.translateString(restOfString);tune.addCentered(window.ABCJS.parse.parseDirective.parseFontChangeLine(centerstr));break;case"font":break;case"setfont":var sfTokens=tokenizer.tokenize(restOfString,0,restOfString.length);if(sfTokens.length>=4&&"-"===sfTokens[0].token&&"number"===sfTokens[1].type){var sfNum=parseInt(sfTokens[1].token);sfNum>=1&&sfNum<=4&&(multilineVars.setfont||(multilineVars.setfont=[]),sfTokens.shift(),sfTokens.shift(),multilineVars.setfont[sfNum]=getFontParameter(sfTokens,multilineVars.setfont[sfNum],str,0,"setfont"))}break;case"gchordfont":case"partsfont":case"vocalfont":case"textfont":case"annotationfont":case"historyfont":case"infofont":case"measurefont":case"repeatfont":case"wordsfont":return getChangingFont(cmd,tokens,str);case"composerfont":case"subtitlefont":case"tempofont":case"titlefont":case"voicefont":case"footerfont":case"headerfont":return getGlobalFont(cmd,tokens,str);case"barlabelfont":case"barnumberfont":case"barnumfont":return getChangingFont("measurefont",tokens,str);case"staves":case"score":multilineVars.score_is_present=!0;for(var lastVoice,addVoice=function(id,newStaff,bracket,brace,continueBar){(newStaff||0===multilineVars.staves.length)&&multilineVars.staves.push({index:multilineVars.staves.length,numVoices:0});var staff=window.ABCJS.parse.last(multilineVars.staves);void 0!==bracket&&(staff.bracket=bracket),void 0!==brace&&(staff.brace=brace),continueBar&&(staff.connectBarLines="end"),void 0===multilineVars.voices[id]&&(multilineVars.voices[id]={staffNum:staff.index,index:staff.numVoices},staff.numVoices++)},openParen=!1,openBracket=!1,openBrace=!1,justOpenParen=!1,justOpenBracket=!1,justOpenBrace=!1,continueBar=!1,addContinueBar=function(){if(continueBar=!0,lastVoice){var ty="start";lastVoice.staffNum>0&&("start"!==multilineVars.staves[lastVoice.staffNum-1].connectBarLines&&"continue"!==multilineVars.staves[lastVoice.staffNum-1].connectBarLines||(ty="continue")),multilineVars.staves[lastVoice.staffNum].connectBarLines=ty}};tokens.length;){var t=tokens.shift();switch(t.token){case"(":openParen?warn("Can't nest parenthesis in %%score",str,t.start):(openParen=!0,justOpenParen=!0);break;case")":!openParen||justOpenParen?warn("Unexpected close parenthesis in %%score",str,t.start):openParen=!1;break;case"[":openBracket?warn("Can't nest brackets in %%score",str,t.start):(openBracket=!0,justOpenBracket=!0);break;case"]":!openBracket||justOpenBracket?warn("Unexpected close bracket in %%score",str,t.start):(openBracket=!1,multilineVars.staves[lastVoice.staffNum].bracket="end");break;case"{":openBrace?warn("Can't nest braces in %%score",str,t.start):(openBrace=!0,justOpenBrace=!0);break;case"}":!openBrace||justOpenBrace?warn("Unexpected close brace in %%score",str,t.start):(openBrace=!1,multilineVars.staves[lastVoice.staffNum].brace="end");break;case"|":addContinueBar();break;default:for(var vc="";("alpha"===t.type||"number"===t.type)&&(vc+=t.token,t.continueId);)t=tokens.shift();var newStaff=!openParen||justOpenParen,bracket=justOpenBracket?"start":openBracket?"continue":void 0,brace=justOpenBrace?"start":openBrace?"continue":void 0;addVoice(vc,newStaff,bracket,brace,continueBar),justOpenParen=!1,justOpenBracket=!1,justOpenBrace=!1,continueBar=!1,lastVoice=multilineVars.voices[vc],"staves"===cmd&&addContinueBar()}}break;case"newpage":var pgNum=tokenizer.getInt(restOfString);tune.addNewPage(0===pgNum.digits?-1:pgNum.value);break;case"abc":var arr=restOfString.split(" ");switch(arr[0]){case"-copyright":case"-creator":case"-edited-by":case"-version":case"-charset":var subCmd=arr.shift();tune.addMetaText(cmd+subCmd,arr.join(" "));break;default:return"Unknown directive: "+cmd+arr[0]}break;case"header":case"footer":var footerStr=tokenizer.getMeat(restOfString,0,restOfString.length);footerStr=restOfString.substring(footerStr.start,footerStr.end),'"'===footerStr.charAt(0)&&'"'===footerStr.charAt(footerStr.length-1)&&(footerStr=footerStr.substring(1,footerStr.length-1));var footerArr=footerStr.split("\t"),footer={};footer=1===footerArr.length?{left:"",center:footerArr[0],right:""}:2===footerArr.length?{left:footerArr[0],center:footerArr[1],right:""}:{left:footerArr[0],center:footerArr[1],right:footerArr[2]},footerArr.length>3&&warn("Too many tabs in "+cmd+": "+footerArr.length+" found.",restOfString,0),tune.addMetaTextObj(cmd,footer);break;case"midi":var midi=tokenizer.tokenize(restOfString,0,restOfString.length,!0);midi.length>0&&"="===midi[0].token&&midi.shift(),0===midi.length?warn("Expected midi command",restOfString,0):parseMidiCommand(midi,tune,restOfString);break;case"playtempo":case"auquality":case"continuous":case"nobarcheck":tune.formatting[cmd]=restOfString;break;default:return"Unknown directive: "+cmd}return null},window.ABCJS.parse.parseDirective.globalFormatting=function(formatHash){for(var cmd in formatHash)if(formatHash.hasOwnProperty(cmd)){var scratch,value=""+formatHash[cmd],tokens=tokenizer.tokenize(value,0,value.length);switch(cmd){case"titlefont":case"gchordfont":getChangingFont(cmd,tokens,value);break;case"scale":setScale(cmd,tokens);break;case"partsbox":scratch=addMultilineVarBool("partsBox",cmd,tokens),null!==scratch&&warn(scratch);break;default:warn("Formatting directive unrecognized: ",cmd,0)}}}}(),window.ABCJS||(window.ABCJS={}),window.ABCJS.parse||(window.ABCJS.parse={}),window.ABCJS.parse.ParseHeader=function(tokenizer,warn,multilineVars,tune){this.reset=function(tokenizer,warn,multilineVars,tune){window.ABCJS.parse.parseKeyVoice.initialize(tokenizer,warn,multilineVars,tune),window.ABCJS.parse.parseDirective.initialize(tokenizer,warn,multilineVars,tune)},this.reset(tokenizer,warn,multilineVars,tune),this.setTitle=function(title){if(multilineVars.hasMainTitle)tune.addSubtitle(tokenizer.translateString(tokenizer.stripComment(title)));else{var titleStr=tokenizer.translateString(tokenizer.theReverser(tokenizer.stripComment(title)));multilineVars.titlecaps&&(titleStr=titleStr.toUpperCase()),tune.addMetaText("title",titleStr),multilineVars.hasMainTitle=!0}},this.setMeter=function(line){if(line=tokenizer.stripComment(line),"C"===line)return multilineVars.havent_set_length===!0&&(multilineVars.default_length=.125),{type:"common_time"};if("C|"===line)return multilineVars.havent_set_length===!0&&(multilineVars.default_length=.125),{type:"cut_time"};if("o"===line)return multilineVars.havent_set_length===!0&&(multilineVars.default_length=.125),{type:"tempus_perfectum"};if("c"===line)return multilineVars.havent_set_length===!0&&(multilineVars.default_length=.125),{type:"tempus_imperfectum"};if("o."===line)return multilineVars.havent_set_length===!0&&(multilineVars.default_length=.125),{type:"tempus_perfectum_prolatio"};if("c."===line)return multilineVars.havent_set_length===!0&&(multilineVars.default_length=.125),{type:"tempus_imperfectum_prolatio"};if(0===line.length||"none"===line.toLowerCase())return multilineVars.havent_set_length===!0&&(multilineVars.default_length=.125),null;var tokens=tokenizer.tokenize(line,0,line.length);try{var parseNum=function(){var ret={value:0,num:""},tok=tokens.shift();for("("===tok.token&&(tok=tokens.shift());;){if("number"!==tok.type)throw"Expected top number of meter";if(ret.value+=parseInt(tok.token),ret.num+=tok.token,0===tokens.length||"/"===tokens[0].token)return ret;if(tok=tokens.shift(),")"===tok.token){if(0===tokens.length||"/"===tokens[0].token)return ret;throw"Unexpected paren in meter"}if("."!==tok.token&&"+"!==tok.token)throw"Expected top number of meter";if(ret.num+=tok.token,0===tokens.length)throw"Expected top number of meter";tok=tokens.shift()}return ret},parseFraction=function(){var ret=parseNum();if(0===tokens.length)return ret;var tok=tokens.shift();if("/"!==tok.token)throw"Expected slash in meter";if(tok=tokens.shift(),"number"!==tok.type)throw"Expected bottom number of meter";return ret.den=tok.token,ret.value=ret.value/parseInt(ret.den),ret};if(0===tokens.length)throw"Expected meter definition in M: line";for(var meter={type:"specified",value:[]},totalLength=0;;){var ret=parseFraction();totalLength+=ret.value;var mv={num:ret.num};if(void 0!==ret.den&&(mv.den=ret.den),meter.value.push(mv),0===tokens.length)break}return multilineVars.havent_set_length===!0&&(multilineVars.default_length=totalLength<.75?.0625:.125),meter}catch(e){warn(e,line,0)}return null},this.calcTempo=function(relTempo){var dur=.25;multilineVars.meter&&"specified"===multilineVars.meter.type?dur=1/parseInt(multilineVars.meter.value[0].den):multilineVars.origMeter&&"specified"===multilineVars.origMeter.type&&(dur=1/parseInt(multilineVars.origMeter.value[0].den));for(var i=0;i<relTempo.duration;i++)relTempo.duration[i]=dur*relTempo.duration[i];return relTempo},this.resolveTempo=function(){multilineVars.tempo&&(this.calcTempo(multilineVars.tempo),tune.metaText.tempo=multilineVars.tempo,delete multilineVars.tempo)},this.addUserDefinition=function(line,start,end){var equals=line.indexOf("=",start);if(equals===-1)return void warn("Need an = in a macro definition",line,start);var before=window.ABCJS.parse.strip(line.substring(start,equals)),after=window.ABCJS.parse.strip(line.substring(equals+1));if(1!==before.length)return void warn("Macro definitions can only be one character",line,start);var legalChars="HIJKLMNOPQRSTUVWXYhijklmnopqrstuvw~";return legalChars.indexOf(before)===-1?void warn("Macro definitions must be H-Y, h-w, or tilde",line,start):0===after.length?void warn("Missing macro definition",line,start):(void 0===multilineVars.macros&&(multilineVars.macros={}),void(multilineVars.macros[before]=after))},this.setDefaultLength=function(line,start,end){var len=window.ABCJS.parse.gsub(line.substring(start,end)," ",""),len_arr=len.split("/");if(2===len_arr.length){var n=parseInt(len_arr[0]),d=parseInt(len_arr[1]);d>0&&(multilineVars.default_length=n/d,multilineVars.havent_set_length=!1)}},this.setTempo=function(line,start,end){try{var tokens=tokenizer.tokenize(line,start,end);if(0===tokens.length)throw"Missing parameter in Q: field";var tempo={},delaySet=!0,token=tokens.shift();if("quote"===token.type&&(tempo.preString=token.token,token=tokens.shift(),0===tokens.length))return{type:"immediate",tempo:tempo};if("alpha"===token.type&&"C"===token.token){if(0===tokens.length)throw"Missing tempo after C in Q: field";if(token=tokens.shift(),"punct"===token.type&&"="===token.token){if(0===tokens.length)throw"Missing tempo after = in Q: field";if(token=tokens.shift(),"number"!==token.type)throw"Expected number after = in Q: field";tempo.duration=[1],tempo.bpm=parseInt(token.token)}else{if("number"!==token.type)throw"Expected number or equal after C in Q: field";if(tempo.duration=[parseInt(token.token)],0===tokens.length)throw"Missing = after duration in Q: field";if(token=tokens.shift(),"punct"!==token.type||"="!==token.token)throw"Expected = after duration in Q: field";if(0===tokens.length)throw"Missing tempo after = in Q: field";if(token=tokens.shift(),"number"!==token.type)throw"Expected number after = in Q: field";tempo.bpm=parseInt(token.token)}}else{if("number"!==token.type)throw"Unknown value in Q: field";var num=parseInt(token.token);if(0===tokens.length||"quote"===tokens[0].type)tempo.duration=[1],tempo.bpm=num;else{if(delaySet=!1,token=tokens.shift(),"punct"!==token.type&&"/"!==token.token)throw"Expected fraction in Q: field";if(token=tokens.shift(),"number"!==token.type)throw"Expected fraction in Q: field";var den=parseInt(token.token);for(tempo.duration=[num/den];tokens.length>0&&"="!==tokens[0].token&&"quote"!==tokens[0].type;){if(token=tokens.shift(),"number"!==token.type)throw"Expected fraction in Q: field";if(num=parseInt(token.token),token=tokens.shift(),"punct"!==token.type&&"/"!==token.token)throw"Expected fraction in Q: field";if(token=tokens.shift(),"number"!==token.type)throw"Expected fraction in Q: field";den=parseInt(token.token),tempo.duration.push(num/den)}if(token=tokens.shift(),"punct"!==token.type&&"="!==token.token)throw"Expected = in Q: field";if(token=tokens.shift(),"number"!==token.type)throw"Expected tempo in Q: field";tempo.bpm=parseInt(token.token)}}if(0!==tokens.length&&(token=tokens.shift(),"quote"===token.type&&(tempo.postString=token.token,token=tokens.shift()),0!==tokens.length))throw"Unexpected string at end of Q: field";return multilineVars.printTempo===!1&&(tempo.suppress=!0),{type:delaySet?"delaySet":"immediate",tempo:tempo}}catch(msg){return warn(msg,line,start),{type:"none"}}},this.letter_to_inline_header=function(line,i){var ws=tokenizer.eatWhiteSpace(line,i); if(i+=ws,line.length>=i+5&&"["===line.charAt(i)&&":"===line.charAt(i+2)){var e=line.indexOf("]",i);switch(line.substring(i,i+3)){case"[I:":var err=window.ABCJS.parse.parseDirective.addDirective(line.substring(i+3,e));return err&&warn(err,line,i),[e-i+1+ws];case"[M:":var meter=this.setMeter(line.substring(i+3,e));return tune.hasBeginMusic()&&meter?tune.appendStartingElement("meter",-1,-1,meter):multilineVars.meter=meter,[e-i+1+ws];case"[K:":var result=window.ABCJS.parse.parseKeyVoice.parseKey(line.substring(i+3,e));return result.foundClef&&tune.hasBeginMusic()&&tune.appendStartingElement("clef",-1,-1,multilineVars.clef),result.foundKey&&tune.hasBeginMusic()&&tune.appendStartingElement("key",-1,-1,window.ABCJS.parse.parseKeyVoice.fixKey(multilineVars.clef,multilineVars.key)),[e-i+1+ws];case"[P:":return tune.lines.length<=tune.lineNum?multilineVars.partForNextLine=line.substring(i+3,e):tune.appendElement("part",-1,-1,{title:line.substring(i+3,e)}),[e-i+1+ws];case"[L:":return this.setDefaultLength(line,i+3,e),[e-i+1+ws];case"[Q:":if(e>0){var tempo=this.setTempo(line,i+3,e);return"delaySet"===tempo.type?tune.appendElement("tempo",-1,-1,this.calcTempo(tempo.tempo)):"immediate"===tempo.type&&tune.appendElement("tempo",-1,-1,tempo.tempo),[e-i+1+ws,line.charAt(i+1),line.substring(i+3,e)]}break;case"[V:":if(e>0)return window.ABCJS.parse.parseKeyVoice.parseVoice(line,i+3,e),[e-i+1+ws,line.charAt(i+1),line.substring(i+3,e)]}}return[0]},this.letter_to_body_header=function(line,i){if(line.length>=i+3)switch(line.substring(i,i+2)){case"I:":var err=window.ABCJS.parse.parseDirective.addDirective(line.substring(i+2));return err&&warn(err,line,i),[line.length];case"M:":var meter=this.setMeter(line.substring(i+2));return tune.hasBeginMusic()&&meter&&tune.appendStartingElement("meter",-1,-1,meter),[line.length];case"K:":var result=window.ABCJS.parse.parseKeyVoice.parseKey(line.substring(i+2));return result.foundClef&&tune.hasBeginMusic()&&tune.appendStartingElement("clef",-1,-1,multilineVars.clef),result.foundKey&&tune.hasBeginMusic()&&tune.appendStartingElement("key",-1,-1,window.ABCJS.parse.parseKeyVoice.fixKey(multilineVars.clef,multilineVars.key)),[line.length];case"P:":return tune.hasBeginMusic()&&tune.appendElement("part",-1,-1,{title:line.substring(i+2)}),[line.length];case"L:":return this.setDefaultLength(line,i+2,line.length),[line.length];case"Q:":var e=line.indexOf("",i+2);e===-1&&(e=line.length);var tempo=this.setTempo(line,i+2,e);return"delaySet"===tempo.type?tune.appendElement("tempo",-1,-1,this.calcTempo(tempo.tempo)):"immediate"===tempo.type&&tune.appendElement("tempo",-1,-1,tempo.tempo),[e,line.charAt(i),window.ABCJS.parse.strip(line.substring(i+2))];case"V:":return window.ABCJS.parse.parseKeyVoice.parseVoice(line,2,line.length),[line.length,line.charAt(i),window.ABCJS.parse(line.substring(i+2))]}return[0]};var metaTextHeaders={A:"author",B:"book",C:"composer",D:"discography",F:"url",G:"group",I:"instruction",N:"notes",O:"origin",R:"rhythm",S:"source",W:"unalignedWords",Z:"transcription"};this.parseHeader=function(line){if(window.ABCJS.parse.startsWith(line,"%%")){var err=window.ABCJS.parse.parseDirective.addDirective(line.substring(2));return err&&warn(err,line,2),{}}var i=line.indexOf("%");if(i>=0&&(line=line.substring(0,i)),line=line.replace(/\s+$/,""),0===line.length)return{};if(line.length>=2&&":"===line.charAt(1)){var nextLine="";line.indexOf("")>=0&&"w"!==line.charAt(0)&&(nextLine=line.substring(line.indexOf("")+1),line=line.substring(0,line.indexOf("")));var field=metaTextHeaders[line.charAt(0)];if(void 0!==field)return"unalignedWords"===field?tune.addMetaTextArray(field,window.ABCJS.parse.parseDirective.parseFontChangeLine(tokenizer.translateString(tokenizer.stripComment(line.substring(2))))):tune.addMetaText(field,tokenizer.translateString(tokenizer.stripComment(line.substring(2)))),{};switch(line.charAt(0)){case"H":tune.addMetaText("history",tokenizer.translateString(tokenizer.stripComment(line.substring(2)))),multilineVars.is_in_history=!0;break;case"K":this.resolveTempo();var result=window.ABCJS.parse.parseKeyVoice.parseKey(line.substring(2));!multilineVars.is_in_header&&tune.hasBeginMusic()&&(result.foundClef&&tune.appendStartingElement("clef",-1,-1,multilineVars.clef),result.foundKey&&tune.appendStartingElement("key",-1,-1,window.ABCJS.parse.parseKeyVoice.fixKey(multilineVars.clef,multilineVars.key))),multilineVars.is_in_header=!1;break;case"L":this.setDefaultLength(line,2,line.length);break;case"M":multilineVars.origMeter=multilineVars.meter=this.setMeter(line.substring(2));break;case"P":multilineVars.is_in_header?tune.addMetaText("partOrder",tokenizer.translateString(tokenizer.stripComment(line.substring(2)))):multilineVars.partForNextLine=tokenizer.translateString(tokenizer.stripComment(line.substring(2)));break;case"Q":var tempo=this.setTempo(line,2,line.length);"delaySet"===tempo.type?multilineVars.tempo=tempo.tempo:"immediate"===tempo.type&&(tune.metaText.tempo=tempo.tempo);break;case"T":this.setTitle(line.substring(2));break;case"U":this.addUserDefinition(line,2,line.length);break;case"V":if(window.ABCJS.parse.parseKeyVoice.parseVoice(line,2,line.length),!multilineVars.is_in_header)return{newline:!0};break;case"s":return{symbols:!0};case"w":return{words:!0};case"X":break;case"E":case"m":warn("Ignored header",line,0);break;default:return nextLine.length&&(nextLine=""+nextLine),{regular:!0,str:line+nextLine}}return nextLine.length>0?{recurse:!0,str:nextLine}:{}}return{regular:!0,str:line}}},window.ABCJS||(window.ABCJS={}),window.ABCJS.parse||(window.ABCJS.parse={}),window.ABCJS.parse.parseKeyVoice={},function(){var tokenizer,warn,multilineVars,tune;window.ABCJS.parse.parseKeyVoice.initialize=function(tokenizer_,warn_,multilineVars_,tune_){tokenizer=tokenizer_,warn=warn_,multilineVars=multilineVars_,tune=tune_},window.ABCJS.parse.parseKeyVoice.standardKey=function(keyName){var key1sharp={acc:"sharp",note:"f"},key2sharp={acc:"sharp",note:"c"},key3sharp={acc:"sharp",note:"g"},key4sharp={acc:"sharp",note:"d"},key5sharp={acc:"sharp",note:"A"},key6sharp={acc:"sharp",note:"e"},key7sharp={acc:"sharp",note:"B"},key1flat={acc:"flat",note:"B"},key2flat={acc:"flat",note:"e"},key3flat={acc:"flat",note:"A"},key4flat={acc:"flat",note:"d"},key5flat={acc:"flat",note:"G"},key6flat={acc:"flat",note:"c"},key7flat={acc:"flat",note:"F"},keys={"C#":[key1sharp,key2sharp,key3sharp,key4sharp,key5sharp,key6sharp,key7sharp],"A#m":[key1sharp,key2sharp,key3sharp,key4sharp,key5sharp,key6sharp,key7sharp],"G#Mix":[key1sharp,key2sharp,key3sharp,key4sharp,key5sharp,key6sharp,key7sharp],"D#Dor":[key1sharp,key2sharp,key3sharp,key4sharp,key5sharp,key6sharp,key7sharp],"E#Phr":[key1sharp,key2sharp,key3sharp,key4sharp,key5sharp,key6sharp,key7sharp],"F#Lyd":[key1sharp,key2sharp,key3sharp,key4sharp,key5sharp,key6sharp,key7sharp],"B#Loc":[key1sharp,key2sharp,key3sharp,key4sharp,key5sharp,key6sharp,key7sharp],"F#":[key1sharp,key2sharp,key3sharp,key4sharp,key5sharp,key6sharp],"D#m":[key1sharp,key2sharp,key3sharp,key4sharp,key5sharp,key6sharp],"C#Mix":[key1sharp,key2sharp,key3sharp,key4sharp,key5sharp,key6sharp],"G#Dor":[key1sharp,key2sharp,key3sharp,key4sharp,key5sharp,key6sharp],"A#Phr":[key1sharp,key2sharp,key3sharp,key4sharp,key5sharp,key6sharp],BLyd:[key1sharp,key2sharp,key3sharp,key4sharp,key5sharp,key6sharp],"E#Loc":[key1sharp,key2sharp,key3sharp,key4sharp,key5sharp,key6sharp],B:[key1sharp,key2sharp,key3sharp,key4sharp,key5sharp],"G#m":[key1sharp,key2sharp,key3sharp,key4sharp,key5sharp],"F#Mix":[key1sharp,key2sharp,key3sharp,key4sharp,key5sharp],"C#Dor":[key1sharp,key2sharp,key3sharp,key4sharp,key5sharp],"D#Phr":[key1sharp,key2sharp,key3sharp,key4sharp,key5sharp],ELyd:[key1sharp,key2sharp,key3sharp,key4sharp,key5sharp],"A#Loc":[key1sharp,key2sharp,key3sharp,key4sharp,key5sharp],E:[key1sharp,key2sharp,key3sharp,key4sharp],"C#m":[key1sharp,key2sharp,key3sharp,key4sharp],BMix:[key1sharp,key2sharp,key3sharp,key4sharp],"F#Dor":[key1sharp,key2sharp,key3sharp,key4sharp],"G#Phr":[key1sharp,key2sharp,key3sharp,key4sharp],ALyd:[key1sharp,key2sharp,key3sharp,key4sharp],"D#Loc":[key1sharp,key2sharp,key3sharp,key4sharp],A:[key1sharp,key2sharp,key3sharp],"F#m":[key1sharp,key2sharp,key3sharp],EMix:[key1sharp,key2sharp,key3sharp],BDor:[key1sharp,key2sharp,key3sharp],"C#Phr":[key1sharp,key2sharp,key3sharp],DLyd:[key1sharp,key2sharp,key3sharp],"G#Loc":[key1sharp,key2sharp,key3sharp],D:[key1sharp,key2sharp],Bm:[key1sharp,key2sharp],AMix:[key1sharp,key2sharp],EDor:[key1sharp,key2sharp],"F#Phr":[key1sharp,key2sharp],GLyd:[key1sharp,key2sharp],"C#Loc":[key1sharp,key2sharp],G:[key1sharp],Em:[key1sharp],DMix:[key1sharp],ADor:[key1sharp],BPhr:[key1sharp],CLyd:[key1sharp],"F#Loc":[key1sharp],C:[],Am:[],GMix:[],DDor:[],EPhr:[],FLyd:[],BLoc:[],F:[key1flat],Dm:[key1flat],CMix:[key1flat],GDor:[key1flat],APhr:[key1flat],BbLyd:[key1flat],ELoc:[key1flat],Bb:[key1flat,key2flat],Gm:[key1flat,key2flat],FMix:[key1flat,key2flat],CDor:[key1flat,key2flat],DPhr:[key1flat,key2flat],EbLyd:[key1flat,key2flat],ALoc:[key1flat,key2flat],Eb:[key1flat,key2flat,key3flat],Cm:[key1flat,key2flat,key3flat],BbMix:[key1flat,key2flat,key3flat],FDor:[key1flat,key2flat,key3flat],GPhr:[key1flat,key2flat,key3flat],AbLyd:[key1flat,key2flat,key3flat],DLoc:[key1flat,key2flat,key3flat],Ab:[key1flat,key2flat,key3flat,key4flat],Fm:[key1flat,key2flat,key3flat,key4flat],EbMix:[key1flat,key2flat,key3flat,key4flat],BbDor:[key1flat,key2flat,key3flat,key4flat],CPhr:[key1flat,key2flat,key3flat,key4flat],DbLyd:[key1flat,key2flat,key3flat,key4flat],GLoc:[key1flat,key2flat,key3flat,key4flat],Db:[key1flat,key2flat,key3flat,key4flat,key5flat],Bbm:[key1flat,key2flat,key3flat,key4flat,key5flat],AbMix:[key1flat,key2flat,key3flat,key4flat,key5flat],EbDor:[key1flat,key2flat,key3flat,key4flat,key5flat],FPhr:[key1flat,key2flat,key3flat,key4flat,key5flat],GbLyd:[key1flat,key2flat,key3flat,key4flat,key5flat],CLoc:[key1flat,key2flat,key3flat,key4flat,key5flat],Gb:[key1flat,key2flat,key3flat,key4flat,key5flat,key6flat],Ebm:[key1flat,key2flat,key3flat,key4flat,key5flat,key6flat],DbMix:[key1flat,key2flat,key3flat,key4flat,key5flat,key6flat],AbDor:[key1flat,key2flat,key3flat,key4flat,key5flat,key6flat],BbPhr:[key1flat,key2flat,key3flat,key4flat,key5flat,key6flat],CbLyd:[key1flat,key2flat,key3flat,key4flat,key5flat,key6flat],FLoc:[key1flat,key2flat,key3flat,key4flat,key5flat,key6flat],Cb:[key1flat,key2flat,key3flat,key4flat,key5flat,key6flat,key7flat],Abm:[key1flat,key2flat,key3flat,key4flat,key5flat,key6flat,key7flat],GbMix:[key1flat,key2flat,key3flat,key4flat,key5flat,key6flat,key7flat],DbDor:[key1flat,key2flat,key3flat,key4flat,key5flat,key6flat,key7flat],EbPhr:[key1flat,key2flat,key3flat,key4flat,key5flat,key6flat,key7flat],FbLyd:[key1flat,key2flat,key3flat,key4flat,key5flat,key6flat,key7flat],BbLoc:[key1flat,key2flat,key3flat,key4flat,key5flat,key6flat,key7flat],"A#":[key1flat,key2flat],"B#":[],"D#":[key1flat,key2flat,key3flat],"E#":[key1flat],"G#":[key1flat,key2flat,key3flat,key4flat],Gbm:[key1sharp,key2sharp,key3sharp,key4sharp,key5sharp,key6sharp,key7sharp]};return keys[keyName]};var clefLines={treble:{clef:"treble",pitch:4,mid:0},"treble+8":{clef:"treble+8",pitch:4,mid:0},"treble-8":{clef:"treble-8",pitch:4,mid:0},treble1:{clef:"treble",pitch:2,mid:2},treble2:{clef:"treble",pitch:4,mid:0},treble3:{clef:"treble",pitch:6,mid:-2},treble4:{clef:"treble",pitch:8,mid:-4},treble5:{clef:"treble",pitch:10,mid:-6},perc:{clef:"perc",pitch:6,mid:0},none:{clef:"none",mid:0},bass:{clef:"bass",pitch:8,mid:-12},"bass+8":{clef:"bass+8",pitch:8,mid:-12},"bass-8":{clef:"bass-8",pitch:8,mid:-12},"bass+16":{clef:"bass",pitch:8,mid:-12},"bass-16":{clef:"bass",pitch:8,mid:-12},bass1:{clef:"bass",pitch:2,mid:-6},bass2:{clef:"bass",pitch:4,mid:-8},bass3:{clef:"bass",pitch:6,mid:-10},bass4:{clef:"bass",pitch:8,mid:-12},bass5:{clef:"bass",pitch:10,mid:-14},tenor:{clef:"alto",pitch:8,mid:-8},tenor1:{clef:"alto",pitch:2,mid:-2},tenor2:{clef:"alto",pitch:4,mid:-4},tenor3:{clef:"alto",pitch:6,mid:-6},tenor4:{clef:"alto",pitch:8,mid:-8},tenor5:{clef:"alto",pitch:10,mid:-10},alto:{clef:"alto",pitch:6,mid:-6},alto1:{clef:"alto",pitch:2,mid:-2},alto2:{clef:"alto",pitch:4,mid:-4},alto3:{clef:"alto",pitch:6,mid:-6},alto4:{clef:"alto",pitch:8,mid:-8},alto5:{clef:"alto",pitch:10,mid:-10},"alto+8":{clef:"alto+8",pitch:6,mid:-6},"alto-8":{clef:"alto-8",pitch:6,mid:-6}},calcMiddle=function(clef,oct){var value=clefLines[clef],mid=value?value.mid:0;return mid+oct};window.ABCJS.parse.parseKeyVoice.fixClef=function(clef){var value=clefLines[clef.type];value&&(clef.clefPos=value.pitch,clef.type=value.clef)},window.ABCJS.parse.parseKeyVoice.deepCopyKey=function(key){var ret={accidentals:[],root:key.root,acc:key.acc,mode:key.mode};return window.ABCJS.parse.each(key.accidentals,function(k){ret.accidentals.push(window.ABCJS.parse.clone(k))}),ret};var pitches={A:5,B:6,C:0,D:1,E:2,F:3,G:4,a:12,b:13,c:7,d:8,e:9,f:10,g:11};window.ABCJS.parse.parseKeyVoice.addPosToKey=function(clef,key){var mid=clef.verticalPos;window.ABCJS.parse.each(key.accidentals,function(acc){var pitch=pitches[acc.note];pitch-=mid,acc.verticalPos=pitch}),key.impliedNaturals&&window.ABCJS.parse.each(key.impliedNaturals,function(acc){var pitch=pitches[acc.note];pitch-=mid,acc.verticalPos=pitch}),mid<-10?(window.ABCJS.parse.each(key.accidentals,function(acc){acc.verticalPos-=7,(acc.verticalPos>=11||10===acc.verticalPos&&"flat"===acc.acc)&&(acc.verticalPos-=7),"A"===acc.note&&"sharp"===acc.acc&&(acc.verticalPos-=7),"G"!==acc.note&&"F"!==acc.note||"flat"!==acc.acc||(acc.verticalPos-=7)}),key.impliedNaturals&&window.ABCJS.parse.each(key.impliedNaturals,function(acc){acc.verticalPos-=7,(acc.verticalPos>=11||10===acc.verticalPos&&"flat"===acc.acc)&&(acc.verticalPos-=7),"A"===acc.note&&"sharp"===acc.acc&&(acc.verticalPos-=7),"G"!==acc.note&&"F"!==acc.note||"flat"!==acc.acc||(acc.verticalPos-=7)})):mid<-4?(window.ABCJS.parse.each(key.accidentals,function(acc){acc.verticalPos-=7,mid!==-8||"f"!==acc.note&&"g"!==acc.note||"sharp"!==acc.acc||(acc.verticalPos-=7)}),key.impliedNaturals&&window.ABCJS.parse.each(key.impliedNaturals,function(acc){acc.verticalPos-=7,mid!==-8||"f"!==acc.note&&"g"!==acc.note||"sharp"!==acc.acc||(acc.verticalPos-=7)})):mid>=7&&(window.ABCJS.parse.each(key.accidentals,function(acc){acc.verticalPos+=7}),key.impliedNaturals&&window.ABCJS.parse.each(key.impliedNaturals,function(acc){acc.verticalPos+=7}))},window.ABCJS.parse.parseKeyVoice.fixKey=function(clef,key){var fixedKey=window.ABCJS.parse.clone(key);return window.ABCJS.parse.parseKeyVoice.addPosToKey(clef,fixedKey),fixedKey};var parseMiddle=function(str){for(var mid=pitches[str.charAt(0)],i=1;i<str.length;i++)if(","===str.charAt(i))mid-=7;else{if(","!==str.charAt(i))break;mid+=7}return{mid:mid-6,str:str.substring(i)}},normalizeAccidentals=function(accs){for(var i=0;i<accs.length;i++)"b"===accs[i].note?accs[i].note="B":"a"===accs[i].note?accs[i].note="A":"F"===accs[i].note?accs[i].note="f":"E"===accs[i].note?accs[i].note="e":"D"===accs[i].note?accs[i].note="d":"C"===accs[i].note?accs[i].note="c":"G"===accs[i].note&&"sharp"===accs[i].acc?accs[i].note="g":"g"===accs[i].note&&"flat"===accs[i].acc&&(accs[i].note="G")};window.ABCJS.parse.parseKeyVoice.parseKey=function(str){0===str.length&&(str="none");var tokens=tokenizer.tokenize(str,0,str.length),ret={};switch(tokens[0].token){case"HP":window.ABCJS.parse.parseDirective.addDirective("bagpipes"),multilineVars.key={root:"HP",accidentals:[],acc:"",mode:""},ret.foundKey=!0,tokens.shift();break;case"Hp":window.ABCJS.parse.parseDirective.addDirective("bagpipes"),multilineVars.key={root:"Hp",accidentals:[{acc:"natural",note:"g"},{acc:"sharp",note:"f"},{acc:"sharp",note:"c"}],acc:"",mode:""},ret.foundKey=!0,tokens.shift();break;case"none":multilineVars.key={root:"none",accidentals:[],acc:"",mode:""},ret.foundKey=!0,tokens.shift();break;default:var retPitch=tokenizer.getKeyPitch(tokens[0].token);if(retPitch.len>0){ret.foundKey=!0;var acc="",mode="";tokens[0].token.length>1?tokens[0].token=tokens[0].token.substring(1):tokens.shift();var key=retPitch.token;if(tokens.length>0){var retAcc=tokenizer.getSharpFlat(tokens[0].token);if(retAcc.len>0&&(tokens[0].token.length>1?tokens[0].token=tokens[0].token.substring(1):tokens.shift(),key+=retAcc.token,acc=retAcc.token),tokens.length>0){var retMode=tokenizer.getMode(tokens[0].token);retMode.len>0&&(tokens.shift(),key+=retMode.token,mode=retMode.token)}if(void 0===window.ABCJS.parse.parseKeyVoice.standardKey(key))return warn("Unsupported key signature: "+key,str,0),ret}var oldKey=window.ABCJS.parse.parseKeyVoice.deepCopyKey(multilineVars.key);if(multilineVars.key=window.ABCJS.parse.parseKeyVoice.deepCopyKey({accidentals:window.ABCJS.parse.parseKeyVoice.standardKey(key)}),multilineVars.key.root=retPitch.token,multilineVars.key.acc=acc,multilineVars.key.mode=mode,oldKey){for(var kk,k=0;k<multilineVars.key.accidentals.length;k++)for(kk=0;kk<oldKey.accidentals.length;kk++)oldKey.accidentals[kk].note&&multilineVars.key.accidentals[k].note.toLowerCase()===oldKey.accidentals[kk].note.toLowerCase()&&(oldKey.accidentals[kk].note=null);for(kk=0;kk<oldKey.accidentals.length;kk++)oldKey.accidentals[kk].note&&(multilineVars.key.impliedNaturals||(multilineVars.key.impliedNaturals=[]),multilineVars.key.impliedNaturals.push({acc:"natural",note:oldKey.accidentals[kk].note}))}}}if(0===tokens.length)return ret;if("exp"===tokens[0].token&&tokens.shift(),0===tokens.length)return ret;if("oct"===tokens[0].token&&tokens.shift(),0===tokens.length)return ret;var accs=tokenizer.getKeyAccidentals2(tokens);if(accs.warn&&warn(accs.warn,str,0),accs.accs){ret.foundKey||(ret.foundKey=!0,multilineVars.key={root:"none",acc:"",mode:"",accidentals:[]}),normalizeAccidentals(accs.accs);for(var i=0;i<accs.accs.length;i++){for(var found=!1,j=0;j<multilineVars.key.accidentals.length&&!found;j++)multilineVars.key.accidentals[j].note===accs.accs[i].note&&(found=!0,multilineVars.key.accidentals[j].acc=accs.accs[i].acc);if(!found&&(multilineVars.key.accidentals.push(accs.accs[i]),multilineVars.key.impliedNaturals))for(var kkk=0;kkk<multilineVars.key.impliedNaturals.length;kkk++)multilineVars.key.impliedNaturals[kkk].note===accs.accs[i].note&&multilineVars.key.impliedNaturals.splice(kkk,1)}}for(var token;tokens.length>0;)switch(tokens[0].token){case"m":case"middle":if(tokens.shift(),0===tokens.length)return warn("Expected = after middle",str,0),ret;if(token=tokens.shift(),"="!==token.token){warn("Expected = after middle",str,token.start);break}if(0===tokens.length)return warn("Expected parameter after middle=",str,0),ret;var pitch=tokenizer.getPitchFromTokens(tokens);pitch.warn&&warn(pitch.warn,str,0),pitch.position&&(multilineVars.clef.verticalPos=pitch.position-6);break;case"transpose":if(tokens.shift(),0===tokens.length)return warn("Expected = after transpose",str,0),ret;if(token=tokens.shift(),"="!==token.token){warn("Expected = after transpose",str,token.start);break}if(0===tokens.length)return warn("Expected parameter after transpose=",str,0),ret;if("number"!==tokens[0].type){warn("Expected number after transpose",str,tokens[0].start);break}multilineVars.clef.transpose=tokens[0].intt,tokens.shift();break;case"stafflines":if(tokens.shift(),0===tokens.length)return warn("Expected = after stafflines",str,0),ret;if(token=tokens.shift(),"="!==token.token){warn("Expected = after stafflines",str,token.start);break}if(0===tokens.length)return warn("Expected parameter after stafflines=",str,0),ret;if("number"!==tokens[0].type){warn("Expected number after stafflines",str,tokens[0].start);break}multilineVars.clef.stafflines=tokens[0].intt,tokens.shift();break;case"staffscale":if(tokens.shift(),0===tokens.length)return warn("Expected = after staffscale",str,0),ret;if(token=tokens.shift(),"="!==token.token){warn("Expected = after staffscale",str,token.start);break}if(0===tokens.length)return warn("Expected parameter after staffscale=",str,0),ret;if("number"!==tokens[0].type){warn("Expected number after staffscale",str,tokens[0].start);break}multilineVars.clef.staffscale=tokens[0].floatt,tokens.shift();break;case"style":if(tokens.shift(),0===tokens.length)return warn("Expected = after style",str,0),ret;if(token=tokens.shift(),"="!==token.token){warn("Expected = after style",str,token.start);break}if(0===tokens.length)return warn("Expected parameter after style=",str,0),ret;switch(tokens[0].token){case"normal":case"harmonic":case"rhythm":case"x":multilineVars.style=tokens[0].token,tokens.shift();break;default:warn("error parsing style element: "+tokens[0].token,str,tokens[0].start)}break;case"clef":if(tokens.shift(),0===tokens.length)return warn("Expected = after clef",str,0),ret;if(token=tokens.shift(),"="!==token.token){warn("Expected = after clef",str,token.start);break}if(0===tokens.length)return warn("Expected parameter after clef=",str,0),ret;case"treble":case"bass":case"alto":case"tenor":case"perc":var clef=tokens.shift();switch(clef.token){case"treble":case"tenor":case"alto":case"bass":case"perc":case"none":break;case"C":clef.token="alto";break;case"F":clef.token="bass";break;case"G":clef.token="treble";break;case"c":clef.token="alto";break;case"f":clef.token="bass";break;case"g":clef.token="treble";break;default:warn("Expected clef name. Found "+clef.token,str,clef.start)}tokens.length>0&&"number"===tokens[0].type&&(clef.token+=tokens[0].token,tokens.shift()),tokens.length>1&&("-"===tokens[0].token||"+"===tokens[0].token)&&"8"===tokens[1].token&&(clef.token+=tokens[0].token+tokens[1].token,tokens.shift(),tokens.shift()),multilineVars.clef={type:clef.token,verticalPos:calcMiddle(clef.token,0)},multilineVars.currentVoice&&void 0!==multilineVars.currentVoice.transpose&&(multilineVars.clef.transpose=multilineVars.currentVoice.transpose),ret.foundClef=!0;break;default:warn("Unknown parameter: "+tokens[0].token,str,tokens[0].start),tokens.shift()}return ret};var setCurrentVoice=function(id){multilineVars.currentVoice=multilineVars.voices[id],tune.setCurrentVoice(multilineVars.currentVoice.staffNum,multilineVars.currentVoice.index)};window.ABCJS.parse.parseKeyVoice.parseVoice=function(line,i,e){var ret=tokenizer.getMeat(line,i,e),start=ret.start,end=ret.end,id=tokenizer.getToken(line,start,end);if(0===id.length)return void warn("Expected a voice id",line,start);var isNew=!1;void 0===multilineVars.voices[id]&&(multilineVars.voices[id]={},isNew=!0,multilineVars.score_is_present&&warn("Can't have an unknown V: id when the %score directive is present",line,start)),start+=id.length,start+=tokenizer.eatWhiteSpace(line,start);for(var staffInfo={startStaff:isNew},addNextTokenToStaffInfo=function(name){var attr=tokenizer.getVoiceToken(line,start,end);void 0!==attr.warn?warn("Expected value for "+name+" in voice: "+attr.warn,line,start):0===attr.token.length&&'"'!==line.charAt(start)?warn("Expected value for "+name+" in voice",line,start):staffInfo[name]=attr.token,start+=attr.len},addNextTokenToVoiceInfo=function(id,name,type){var attr=tokenizer.getVoiceToken(line,start,end);void 0!==attr.warn?warn("Expected value for "+name+" in voice: "+attr.warn,line,start):0===attr.token.length&&'"'!==line.charAt(start)?warn("Expected value for "+name+" in voice",line,start):("number"===type&&(attr.token=parseFloat(attr.token)),multilineVars.voices[id][name]=attr.token),start+=attr.len};start<end;){var token=tokenizer.getVoiceToken(line,start,end);if(start+=token.len,token.warn)warn("Error parsing voice: "+token.warn,line,start);else{var attr=null;switch(token.token){case"clef":case"cl":addNextTokenToStaffInfo("clef");var oct=0;void 0!==staffInfo.clef&&(staffInfo.clef=staffInfo.clef.replace(/[',]/g,""),staffInfo.clef.indexOf("+16")!==-1&&(oct+=14,staffInfo.clef=staffInfo.clef.replace("+16","")),staffInfo.verticalPos=calcMiddle(staffInfo.clef,oct));break;case"treble":case"bass":case"tenor":case"alto":case"none":case"treble'":case"bass'":case"tenor'":case"alto'":case"none'":case"treble''":case"bass''":case"tenor''":case"alto''":case"none''":case"treble,":case"bass,":case"tenor,":case"alto,":case"none,":case"treble,,":case"bass,,":case"tenor,,":case"alto,,":case"none,,":var oct2=0;staffInfo.clef=token.token.replace(/[',]/g,""),staffInfo.verticalPos=calcMiddle(staffInfo.clef,oct2);break;case"staves":case"stave":case"stv":addNextTokenToStaffInfo("staves");break;case"brace":case"brc":addNextTokenToStaffInfo("brace");break;case"bracket":case"brk":addNextTokenToStaffInfo("bracket");break;case"name":case"nm":addNextTokenToStaffInfo("name");break;case"subname":case"sname":case"snm":addNextTokenToStaffInfo("subname");break;case"merge":staffInfo.startStaff=!1;break;case"stems":attr=tokenizer.getVoiceToken(line,start,end),void 0!==attr.warn?warn("Expected value for stems in voice: "+attr.warn,line,start):"up"===attr.token||"down"===attr.token?multilineVars.voices[id].stem=attr.token:warn("Expected up or down for voice stem",line,start),start+=attr.len;break;case"up":case"down":multilineVars.voices[id].stem=token.token;break;case"middle":case"m":addNextTokenToStaffInfo("verticalPos"),staffInfo.verticalPos=parseMiddle(staffInfo.verticalPos).mid;break;case"gchords":case"gch":multilineVars.voices[id].suppressChords=!0;break;case"space":case"spc":addNextTokenToStaffInfo("spacing");break;case"scale":addNextTokenToVoiceInfo(id,"scale","number");break;case"transpose":addNextTokenToVoiceInfo(id,"transpose","number")}}start+=tokenizer.eatWhiteSpace(line,start)}if((staffInfo.startStaff||0===multilineVars.staves.length)&&(multilineVars.staves.push({index:multilineVars.staves.length,meter:multilineVars.origMeter}),multilineVars.score_is_present||(multilineVars.staves[multilineVars.staves.length-1].numVoices=0)),void 0===multilineVars.voices[id].staffNum){multilineVars.voices[id].staffNum=multilineVars.staves.length-1;var vi=0;for(var v in multilineVars.voices)multilineVars.voices.hasOwnProperty(v)&&multilineVars.voices[v].staffNum===multilineVars.voices[id].staffNum&&vi++;multilineVars.voices[id].index=vi-1}var s=multilineVars.staves[multilineVars.voices[id].staffNum];multilineVars.score_is_present||s.numVoices++,staffInfo.clef&&(s.clef={type:staffInfo.clef,verticalPos:staffInfo.verticalPos}),staffInfo.spacing&&(s.spacing_below_offset=staffInfo.spacing),staffInfo.verticalPos&&(s.verticalPos=staffInfo.verticalPos),staffInfo.name&&(s.name?s.name.push(staffInfo.name):s.name=[staffInfo.name]),staffInfo.subname&&(s.subname?s.subname.push(staffInfo.subname):s.subname=[staffInfo.subname]),setCurrentVoice(id)}}(),window.ABCJS||(window.ABCJS={}),window.ABCJS.parse||(window.ABCJS.parse={}),window.ABCJS.parse.tokenizer=function(){this.skipWhiteSpace=function(str){for(var i=0;i<str.length;i++)if(!this.isWhiteSpace(str.charAt(i)))return i;return str.length};var finished=function(str,i){return i>=str.length};this.eatWhiteSpace=function(line,index){for(var i=index;i<line.length;i++)if(!this.isWhiteSpace(line.charAt(i)))return i-index;return i-index},this.getKeyPitch=function(str){var i=this.skipWhiteSpace(str);if(finished(str,i))return{len:0};switch(str.charAt(i)){case"A":return{len:i+1,token:"A"};case"B":return{len:i+1,token:"B"};case"C":return{len:i+1,token:"C"};case"D":return{len:i+1,token:"D"};case"E":return{len:i+1,token:"E"};case"F":return{len:i+1,token:"F"};case"G":return{len:i+1,token:"G"}}return{len:0}},this.getSharpFlat=function(str){if("bass"===str)return{len:0};switch(str.charAt(0)){case"#":return{len:1,token:"#"};case"b":return{len:1,token:"b"}}return{len:0}},this.getMode=function(str){var skipAlpha=function(str,start){for(;start<str.length&&(str.charAt(start)>="a"&&str.charAt(start)<="z"||str.charAt(start)>="A"&&str.charAt(start)<="Z");)start++;return start},i=this.skipWhiteSpace(str);if(finished(str,i))return{len:0};var firstThree=str.substring(i,i+3).toLowerCase();switch((firstThree.length>1&&" "===firstThree.charAt(1)||"^"===firstThree.charAt(1)||"_"===firstThree.charAt(1)||"="===firstThree.charAt(1))&&(firstThree=firstThree.charAt(0)),firstThree){case"mix":return{len:skipAlpha(str,i),token:"Mix"};case"dor":return{len:skipAlpha(str,i),token:"Dor"};case"phr":return{len:skipAlpha(str,i),token:"Phr"};case"lyd":return{len:skipAlpha(str,i),token:"Lyd"};case"loc":return{len:skipAlpha(str,i),token:"Loc"};case"aeo":return{len:skipAlpha(str,i),token:"m"};case"maj":return{len:skipAlpha(str,i),token:""};case"ion":return{len:skipAlpha(str,i),token:""};case"min":return{len:skipAlpha(str,i),token:"m"};case"m":return{len:skipAlpha(str,i),token:"m"}}return{len:0}},this.getClef=function(str,bExplicitOnly){var strOrig=str,i=this.skipWhiteSpace(str);if(finished(str,i))return{len:0};var needsClef=!1,strClef=str.substring(i);if(window.ABCJS.parse.startsWith(strClef,"clef=")&&(needsClef=!0,strClef=strClef.substring(5),i+=5),0===strClef.length&&needsClef)return{len:i+5,warn:"No clef specified: "+strOrig};var j=this.skipWhiteSpace(strClef);if(finished(strClef,j))return{len:0};j>0&&(i+=j,strClef=strClef.substring(j));var name=null;if(window.ABCJS.parse.startsWith(strClef,"treble"))name="treble";else if(window.ABCJS.parse.startsWith(strClef,"bass3"))name="bass3";else if(window.ABCJS.parse.startsWith(strClef,"bass"))name="bass";else if(window.ABCJS.parse.startsWith(strClef,"tenor"))name="tenor";else if(window.ABCJS.parse.startsWith(strClef,"alto2"))name="alto2";else if(window.ABCJS.parse.startsWith(strClef,"alto1"))name="alto1";else if(window.ABCJS.parse.startsWith(strClef,"alto"))name="alto";else if(!bExplicitOnly&&needsClef&&window.ABCJS.parse.startsWith(strClef,"none"))name="none";else if(window.ABCJS.parse.startsWith(strClef,"perc"))name="perc";else if(!bExplicitOnly&&needsClef&&window.ABCJS.parse.startsWith(strClef,"C"))name="tenor";else if(!bExplicitOnly&&needsClef&&window.ABCJS.parse.startsWith(strClef,"F"))name="bass";else{if(bExplicitOnly||!needsClef||!window.ABCJS.parse.startsWith(strClef,"G"))return{len:i+5,warn:"Unknown clef specified: "+strOrig};name="treble"}return strClef=strClef.substring(name.length),j=this.isMatch(strClef,"+8"),j>0?name+="+8":(j=this.isMatch(strClef,"-8"),j>0&&(name+="-8")),{len:i+name.length,token:name,explicit:needsClef}},this.getBarLine=function(line,i){switch(line.charAt(i)){case"]":switch(++i,line.charAt(i)){case"|":return{len:2,token:"bar_thick_thin"};case"[":return++i,line.charAt(i)>="1"&&line.charAt(i)<="9"||'"'===line.charAt(i)?{len:2,token:"bar_invisible"}:{len:1,warn:"Unknown bar symbol"};default:return{len:1,token:"bar_invisible"}}break;case":":switch(++i,line.charAt(i)){case":":return{len:2,token:"bar_dbl_repeat"};case"|":switch(++i,line.charAt(i)){case"]":switch(++i,line.charAt(i)){case"|":return++i,":"===line.charAt(i)?{len:5,token:"bar_dbl_repeat"}:{len:3,token:"bar_right_repeat"};default:return{len:3,token:"bar_right_repeat"}}break;case"|":return++i,":"===line.charAt(i)?{len:4,token:"bar_dbl_repeat"}:{len:3,token:"bar_right_repeat"};default:return{len:2,token:"bar_right_repeat"}}break;default:return{len:1,warn:"Unknown bar symbol"}}break;case"[":if(++i,"|"!==line.charAt(i))return line.charAt(i)>="1"&&line.charAt(i)<="9"||'"'===line.charAt(i)?{len:1,token:"bar_invisible"}:{len:0};switch(++i,line.charAt(i)){case":":return{len:3,token:"bar_left_repeat"};case"]":return{len:3,token:"bar_invisible"};default:return{len:2,token:"bar_thick_thin"}}break;case"|":switch(++i,line.charAt(i)){case"]":return{len:2,token:"bar_thin_thick"};case"|":return++i,":"===line.charAt(i)?{len:3,token:"bar_left_repeat"}:{len:2,token:"bar_thin_thin"};case":":for(var colons=0;":"===line.charAt(i+colons);)colons++;return{len:1+colons,token:"bar_left_repeat"};default:return{len:1,token:"bar_thin"}}}return{len:0}},this.getTokenOf=function(str,legalChars){for(var i=0;i<str.length;i++)if(legalChars.indexOf(str.charAt(i))<0)return{len:i,token:str.substring(0,i)};return{len:i,token:str}},this.getToken=function(str,start,end){for(var i=start;i<end&&!this.isWhiteSpace(str.charAt(i));)i++;return str.substring(start,i)},this.isMatch=function(str,match){var i=this.skipWhiteSpace(str);return finished(str,i)?0:window.ABCJS.parse.startsWith(str.substring(i),match)?i+match.length:0; },this.getPitchFromTokens=function(tokens){var ret={},pitches={A:5,B:6,C:0,D:1,E:2,F:3,G:4,a:12,b:13,c:7,d:8,e:9,f:10,g:11};if(ret.position=pitches[tokens[0].token],void 0===ret.position)return{warn:"Pitch expected. Found: "+tokens[0].token};for(tokens.shift();tokens.length;)switch(tokens[0].token){case",":ret.position-=7,tokens.shift();break;case"'":ret.position+=7,tokens.shift();break;default:return ret}return ret},this.getKeyAccidentals2=function(tokens){for(var accs;tokens.length>0;){var acc;if("^"===tokens[0].token){if(acc="sharp",tokens.shift(),0===tokens.length)return{accs:accs,warn:"Expected note name after "+acc};switch(tokens[0].token){case"^":acc="dblsharp",tokens.shift();break;case"/":acc="quartersharp",tokens.shift()}}else if("="===tokens[0].token)acc="natural",tokens.shift();else{if("_"!==tokens[0].token)return{accs:accs};if(acc="flat",tokens.shift(),0===tokens.length)return{accs:accs,warn:"Expected note name after "+acc};switch(tokens[0].token){case"_":acc="dblflat",tokens.shift();break;case"/":acc="quarterflat",tokens.shift()}}if(0===tokens.length)return{accs:accs,warn:"Expected note name after "+acc};switch(tokens[0].token.charAt(0)){case"a":case"b":case"c":case"d":case"e":case"f":case"g":case"A":case"B":case"C":case"D":case"E":case"F":case"G":void 0===accs&&(accs=[]),accs.push({acc:acc,note:tokens[0].token.charAt(0)}),1===tokens[0].token.length?tokens.shift():tokens[0].token=tokens[0].token.substring(1);break;default:return{accs:accs,warn:"Expected note name after "+acc+" Found: "+tokens[0].token}}}return{accs:accs}},this.getKeyAccidental=function(str){var accTranslation={"^":"sharp","^^":"dblsharp","=":"natural",_:"flat",__:"dblflat","_/":"quarterflat","^/":"quartersharp"},i=this.skipWhiteSpace(str);if(finished(str,i))return{len:0};var acc=null;switch(str.charAt(i)){case"^":case"_":case"=":acc=str.charAt(i);break;default:return{len:0}}if(i++,finished(str,i))return{len:1,warn:"Expected note name after accidental"};switch(str.charAt(i)){case"a":case"b":case"c":case"d":case"e":case"f":case"g":case"A":case"B":case"C":case"D":case"E":case"F":case"G":return{len:i+1,token:{acc:accTranslation[acc],note:str.charAt(i)}};case"^":case"_":case"/":if(acc+=str.charAt(i),i++,finished(str,i))return{len:2,warn:"Expected note name after accidental"};switch(str.charAt(i)){case"a":case"b":case"c":case"d":case"e":case"f":case"g":case"A":case"B":case"C":case"D":case"E":case"F":case"G":return{len:i+1,token:{acc:accTranslation[acc],note:str.charAt(i)}};default:return{len:2,warn:"Expected note name after accidental"}}break;default:return{len:1,warn:"Expected note name after accidental"}}},this.isWhiteSpace=function(ch){return" "===ch||"\t"===ch||""===ch},this.getMeat=function(line,start,end){var comment=line.indexOf("%",start);for(comment>=0&&comment<end&&(end=comment);start<end&&(" "===line.charAt(start)||"\t"===line.charAt(start)||""===line.charAt(start));)start++;for(;start<end&&(" "===line.charAt(end-1)||"\t"===line.charAt(end-1)||""===line.charAt(end-1));)end--;return{start:start,end:end}};var isLetter=function(ch){return ch>="A"&&ch<="Z"||ch>="a"&&ch<="z"},isNumber=function(ch){return ch>="0"&&ch<="9"};this.tokenize=function(line,start,end,alphaUntilWhiteSpace){var ret=this.getMeat(line,start,end);start=ret.start,end=ret.end;for(var i,tokens=[];start<end;){if('"'===line.charAt(start)){for(i=start+1;i<end&&'"'!==line.charAt(i);)i++;tokens.push({type:"quote",token:line.substring(start+1,i),start:start+1,end:i}),i++}else if(isLetter(line.charAt(start))){if(i=start+1,alphaUntilWhiteSpace)for(;i<end&&!this.isWhiteSpace(line.charAt(i));)i++;else for(;i<end&&isLetter(line.charAt(i));)i++;tokens.push({type:"alpha",token:line.substring(start,i),continueId:isNumber(line.charAt(i)),start:start,end:i}),start=i+1}else if("."===line.charAt(start)&&isNumber(line.charAt(i+1))){i=start+1;for(var int2=null,float2=null;i<end&&isNumber(line.charAt(i));)i++;float2=parseFloat(line.substring(start,i)),tokens.push({type:"number",token:line.substring(start,i),intt:int2,floatt:float2,continueId:isLetter(line.charAt(i)),start:start,end:i}),start=i+1}else if(isNumber(line.charAt(start))||"-"===line.charAt(start)&&isNumber(line.charAt(i+1))){i=start+1;for(var intt=null,floatt=null;i<end&&isNumber(line.charAt(i));)i++;if("."===line.charAt(i)&&isNumber(line.charAt(i+1)))for(i++;i<end&&isNumber(line.charAt(i));)i++;else intt=parseInt(line.substring(start,i));floatt=parseFloat(line.substring(start,i)),tokens.push({type:"number",token:line.substring(start,i),intt:intt,floatt:floatt,continueId:isLetter(line.charAt(i)),start:start,end:i}),start=i+1}else" "===line.charAt(start)||"\t"===line.charAt(start)?i=start+1:(tokens.push({type:"punct",token:line.charAt(start),start:start,end:start+1}),i=start+1);start=i}return tokens},this.getVoiceToken=function(line,start,end){for(var i=start;i<end&&this.isWhiteSpace(line.charAt(i))||"="===line.charAt(i);)i++;if('"'===line.charAt(i)){var close=line.indexOf('"',i+1);return close===-1||close>=end?{len:1,err:"Missing close quote"}:{len:close-start+1,token:this.translateString(line.substring(i+1,close))}}for(var ii=i;ii<end&&!this.isWhiteSpace(line.charAt(ii))&&"="!==line.charAt(ii);)ii++;return{len:ii-start+1,token:line.substring(i,ii)}};var charMap={"`a":"à","'a":"á","^a":"â","~a":"ã",'"a':"ä",oa:"å","=a":"ā",ua:"ă",";a":"ą","`e":"è","'e":"é","^e":"ê",'"e':"ë","=e":"ē",ue:"ĕ",";e":"ę",".e":"ė","`i":"ì","'i":"í","^i":"î",'"i':"ï","=i":"ī",ui:"ĭ",";i":"į","`o":"ò","'o":"ó","^o":"ô","~o":"õ",'"o':"ö","=o":"ō",uo:"ŏ","/o":"ø","`u":"ù","'u":"ú","^u":"û","~u":"ũ",'"u':"ü",ou:"ů","=u":"ū",uu:"ŭ",";u":"ų","`A":"À","'A":"Á","^A":"Â","~A":"Ã",'"A':"Ä",oA:"Å","=A":"Ā",uA:"Ă",";A":"Ą","`E":"È","'E":"É","^E":"Ê",'"E':"Ë","=E":"Ē",uE:"Ĕ",";E":"Ę",".E":"Ė","`I":"Ì","'I":"Í","^I":"Î","~I":"Ĩ",'"I':"Ï","=I":"Ī",uI:"Ĭ",";I":"Į",".I":"İ","`O":"Ò","'O":"Ó","^O":"Ô","~O":"Õ",'"O':"Ö","=O":"Ō",uO:"Ŏ","/O":"Ø","`U":"Ù","'U":"Ú","^U":"Û","~U":"Ũ",'"U':"Ü",oU:"Ů","=U":"Ū",uU:"Ŭ",";U":"Ų",ae:"æ",AE:"Æ",oe:"œ",OE:"Œ",ss:"ß","'c":"ć","^c":"ĉ",uc:"č",cc:"ç",".c":"ċ",cC:"Ç","'C":"Ć","^C":"Ĉ",uC:"Č",".C":"Ċ","~n":"ñ","=s":"š",vs:"š",vz:"ž"},charMap1={"#":"♯",b:"♭","=":"♮"},charMap2={201:"♯",202:"♭",203:"♮",241:"¡",242:"¢",252:"a",262:"2",272:"o",302:"Â",312:"Ê",322:"Ò",332:"Ú",342:"â",352:"ê",362:"ò",372:"ú",243:"£",253:"«",263:"3",273:"»",303:"Ã",313:"Ë",323:"Ó",333:"Û",343:"ã",353:"ë",363:"ó",373:"û",244:"¤",254:"¬",264:" ́",274:"1⁄4",304:"Ä",314:"Ì",324:"Ô",334:"Ü",344:"ä",354:"ì",364:"ô",374:"ü",245:"¥",255:"-",265:"μ",275:"1⁄2",305:"Å",315:"Í",325:"Õ",335:"Ý",345:"å",355:"í",365:"õ",375:"ý",246:"¦",256:"®",266:"¶",276:"3⁄4",306:"Æ",316:"Î",326:"Ö",336:"Þ",346:"æ",356:"î",366:"ö",376:"þ",247:"§",257:" ̄",267:"·",277:"¿",307:"Ç",317:"Ï",327:"×",337:"ß",347:"ç",357:"ï",367:"÷",377:"ÿ",250:" ̈",260:"°",270:" ̧",300:"À",310:"È",320:"Ð",330:"Ø",340:"à",350:"è",360:"ð",370:"ø",251:"©",261:"±",271:"1",301:"Á",311:"É",321:"Ñ",331:"Ù",341:"á",351:"é",361:"ñ",371:"ù"};this.translateString=function(str){var arr=str.split("\\");if(1===arr.length)return str;var out=null;return window.ABCJS.parse.each(arr,function(s){if(null===out)out=s;else{var c=charMap[s.substring(0,2)];void 0!==c?out+=c+s.substring(2):(c=charMap2[s.substring(0,3)],void 0!==c?out+=c+s.substring(3):(c=charMap1[s.substring(0,1)],out+=void 0!==c?c+s.substring(1):"\\"+s))}}),out},this.getNumber=function(line,index){for(var num=0;index<line.length;)switch(line.charAt(index)){case"0":num*=10,index++;break;case"1":num=10*num+1,index++;break;case"2":num=10*num+2,index++;break;case"3":num=10*num+3,index++;break;case"4":num=10*num+4,index++;break;case"5":num=10*num+5,index++;break;case"6":num=10*num+6,index++;break;case"7":num=10*num+7,index++;break;case"8":num=10*num+8,index++;break;case"9":num=10*num+9,index++;break;default:return{num:num,index:index}}return{num:num,index:index}},this.getFraction=function(line,index){var num=1,den=1;if("/"!==line.charAt(index)){var ret=this.getNumber(line,index);num=ret.num,index=ret.index}if("/"===line.charAt(index)){if(index++,"/"===line.charAt(index)){for(var div=.5;"/"===line.charAt(index++);)div/=2;return{value:num*div,index:index-1}}var iSave=index,ret2=this.getNumber(line,index);0===ret2.num&&iSave===index&&(ret2.num=2),0!==ret2.num&&(den=ret2.num),index=ret2.index}return{value:num/den,index:index}},this.theReverser=function(str){return window.ABCJS.parse.endsWith(str,", The")?"The "+str.substring(0,str.length-5):window.ABCJS.parse.endsWith(str,", A")?"A "+str.substring(0,str.length-3):str},this.stripComment=function(str){var i=str.indexOf("%");return i>=0?window.ABCJS.parse.strip(str.substring(0,i)):window.ABCJS.parse.strip(str)},this.getInt=function(str){var x=parseInt(str);if(isNaN(x))return{digits:0};var s=""+x,i=str.indexOf(s);return{value:x,digits:i+s.length}},this.getFloat=function(str){var x=parseFloat(str);if(isNaN(x))return{digits:0};var s=""+x,i=str.indexOf(s);return{value:x,digits:i+s.length}},this.getMeasurement=function(tokens){if(0===tokens.length)return{used:0};var used=1,num="";if("-"===tokens[0].token)tokens.shift(),num="-",used++;else if("number"!==tokens[0].type)return{used:0};if(num+=tokens.shift().token,0===tokens.length)return{used:1,value:parseInt(num)};var x=tokens.shift();if("."===x.token){if(used++,0===tokens.length)return{used:used,value:parseInt(num)};if("number"===tokens[0].type&&(x=tokens.shift(),num=num+"."+x.token,used++,0===tokens.length))return{used:used,value:parseFloat(num)};x=tokens.shift()}switch(x.token){case"pt":return{used:used+1,value:parseFloat(num)};case"cm":return{used:used+1,value:parseFloat(num)/2.54*72};case"in":return{used:used+1,value:72*parseFloat(num)};default:return tokens.unshift(x),{used:used,value:parseFloat(num)}}return{used:0}};var substInChord=function(str){for(;str.indexOf("\\n")!==-1;)str=str.replace("\\n","\n");return str};this.getBrackettedSubstring=function(line,i,maxErrorChars,_matchChar){for(var matchChar=_matchChar||line.charAt(i),pos=i+1;pos<line.length&&line.charAt(pos)!==matchChar;)++pos;return line.charAt(pos)===matchChar?[pos-i+1,substInChord(line.substring(i+1,pos)),!0]:(pos=i+maxErrorChars,pos>line.length-1&&(pos=line.length-1),[pos-i+1,substInChord(line.substring(i+1,pos)),!1])}},window.ABCJS||(window.ABCJS={}),window.ABCJS.write||(window.ABCJS.write={}),ABCJS.write.AbsoluteElement=function(abcelem,duration,minspacing,type,tuneNumber){this.tuneNumber=tuneNumber,this.abcelem=abcelem,this.duration=duration,this.minspacing=minspacing||0,this.x=0,this.children=[],this.heads=[],this.extra=[],this.extraw=0,this.w=0,this.right=[],this.invisible=!1,this.bottom=void 0,this.top=void 0,this.type=type,this.specialY={tempoHeightAbove:0,partHeightAbove:0,volumeHeightAbove:0,dynamicHeightAbove:0,endingHeightAbove:0,chordHeightAbove:0,lyricHeightAbove:0,lyricHeightBelow:0,chordHeightBelow:0,volumeHeightBelow:0,dynamicHeightBelow:0}},ABCJS.write.AbsoluteElement.prototype.setUpperAndLowerElements=function(specialYResolved){for(var i=0;i<this.children.length;i++){var child=this.children[i];for(var key in this.specialY)this.specialY.hasOwnProperty(key)&&child[key]&&(child.pitch=specialYResolved[key])}},ABCJS.write.AbsoluteElement.prototype.getMinWidth=function(){return this.w},ABCJS.write.AbsoluteElement.prototype.getExtraWidth=function(){return-this.extraw},ABCJS.write.AbsoluteElement.prototype.addExtra=function(extra){extra.dx<this.extraw&&(this.extraw=extra.dx),this.extra[this.extra.length]=extra,this.addChild(extra)},ABCJS.write.AbsoluteElement.prototype.addHead=function(head){head.dx<this.extraw&&(this.extraw=head.dx),this.heads[this.heads.length]=head,this.addRight(head)},ABCJS.write.AbsoluteElement.prototype.addRight=function(right){right.dx+right.w>this.w&&(this.w=right.dx+right.w),this.right[this.right.length]=right,this.addChild(right)},ABCJS.write.AbsoluteElement.prototype.addCentered=function(elem){var half=elem.w/2;-half<this.extraw&&(this.extraw=-half),this.extra[this.extra.length]=elem,elem.dx+half>this.w&&(this.w=elem.dx+half),this.right[this.right.length]=elem,this.addChild(elem)},ABCJS.write.AbsoluteElement.prototype.setLimit=function(member,child){child[member]&&(this.specialY[member]?this.specialY[member]=Math.max(this.specialY[member],child[member]):this.specialY[member]=child[member])},ABCJS.write.AbsoluteElement.prototype.addChild=function(child){child.parent=this,this.children[this.children.length]=child,this.pushTop(child.top),this.pushBottom(child.bottom),this.setLimit("tempoHeightAbove",child),this.setLimit("partHeightAbove",child),this.setLimit("volumeHeightAbove",child),this.setLimit("dynamicHeightAbove",child),this.setLimit("endingHeightAbove",child),this.setLimit("chordHeightAbove",child),this.setLimit("lyricHeightAbove",child),this.setLimit("lyricHeightBelow",child),this.setLimit("chordHeightBelow",child),this.setLimit("volumeHeightBelow",child),this.setLimit("dynamicHeightBelow",child)},ABCJS.write.AbsoluteElement.prototype.pushTop=function(top){void 0!==top&&(void 0===this.top?this.top=top:this.top=Math.max(top,this.top))},ABCJS.write.AbsoluteElement.prototype.pushBottom=function(bottom){void 0!==bottom&&(void 0===this.bottom?this.bottom=bottom:this.bottom=Math.min(bottom,this.bottom))},ABCJS.write.AbsoluteElement.prototype.setX=function(x){this.x=x;for(var i=0;i<this.children.length;i++)this.children[i].setX(x)},ABCJS.write.AbsoluteElement.prototype.setHint=function(){this.hint=!0},ABCJS.write.AbsoluteElement.prototype.draw=function(renderer,bartop){if(this.elemset=renderer.paper.set(),!this.invisible){renderer.beginGroup();for(var i=0;i<this.children.length;i++)ABCJS.write.debugPlacement&&"ornament"===this.children[i].klass&&renderer.printShadedBox(this.x,renderer.calcY(this.children[i].top),this.w,renderer.calcY(this.children[i].bottom)-renderer.calcY(this.children[i].top),"rgba(0,0,200,0.3)"),this.elemset.push(this.children[i].draw(renderer,bartop));this.elemset.push(renderer.endGroup(this.type)),this.klass&&this.setClass("mark","","#00ff00"),this.hint&&this.setClass("abcjs-hint","",null);var color=ABCJS.write.debugPlacement?"rgba(0,0,0,0.3)":"rgba(0,0,0,0)",target=renderer.printShadedBox(this.x,renderer.calcY(this.top),this.w,renderer.calcY(this.bottom)-renderer.calcY(this.top),color),self=this,controller=renderer.controller;target.mouseup(function(){controller.notifySelect(self,self.tuneNumber)}),this.abcelem.abselem=this;var spacing=ABCJS.write.spacing.STEP,start=function(){this.dy=0},move=function(dx,dy){dy=Math.round(dy/spacing)*spacing,this.translate(0,-this.dy),this.dy=dy,this.translate(0,this.dy)},up=function(){if(self.abcelem.pitches){var delta=-Math.round(this.dy/spacing);self.abcelem.pitches[0].pitch+=delta,self.abcelem.pitches[0].verticalPos+=delta,controller.notifyChange()}};"note"===this.abcelem.el_type&&controller.editable&&this.elemset.drag(move,start,up)}},ABCJS.write.AbsoluteElement.prototype.isIE=!1,ABCJS.write.AbsoluteElement.prototype.setClass=function(addClass,removeClass,color){if(null!==color&&this.elemset.attr({fill:color}),!this.isIE)for(var i=0;i<this.elemset.length;i++)if(this.elemset[i][0].setAttribute){var kls=this.elemset[i][0].getAttribute("class");kls||(kls=""),kls=kls.replace(removeClass,""),kls=kls.replace(addClass,""),addClass.length>0&&(kls.length>0&&" "!==kls.charAt(kls.length-1)&&(kls+=" "),kls+=addClass),this.elemset[i][0].setAttribute("class",kls)}},ABCJS.write.AbsoluteElement.prototype.highlight=function(klass,color){void 0===klass&&(klass="note_selected"),void 0===color&&(color="#ff0000"),this.setClass(klass,"",color)},ABCJS.write.AbsoluteElement.prototype.unhighlight=function(klass,color){void 0===klass&&(klass="note_selected"),void 0===color&&(color="#000000"),this.setClass("",klass,color)},window.ABCJS||(window.ABCJS={}),window.ABCJS.write||(window.ABCJS.write={}),function(){"use strict";ABCJS.write.getDuration=function(elem){var d=0;return elem.duration&&(d=elem.duration),d},ABCJS.write.getDurlog=function(duration){return void 0===duration?0:Math.floor(Math.log(duration)/Math.log(2))},ABCJS.write.AbstractEngraver=function(bagpipes,renderer,tuneNumber){this.decoration=new ABCJS.write.Decoration,this.renderer=renderer,this.tuneNumber=tuneNumber,this.isBagpipes=bagpipes,this.chartable={rest:{0:"rests.whole",1:"rests.half",2:"rests.quarter",3:"rests.8th",4:"rests.16th",5:"rests.32nd",6:"rests.64th",7:"rests.128th"},note:{"-1":"noteheads.dbl",0:"noteheads.whole",1:"noteheads.half",2:"noteheads.quarter",3:"noteheads.quarter",4:"noteheads.quarter",5:"noteheads.quarter",6:"noteheads.quarter",7:"noteheads.quarter",nostem:"noteheads.quarter"},rhythm:{"-1":"noteheads.slash.whole",0:"noteheads.slash.whole",1:"noteheads.slash.whole",2:"noteheads.slash.quarter",3:"noteheads.slash.quarter",4:"noteheads.slash.quarter",5:"noteheads.slash.quarter",6:"noteheads.slash.quarter",7:"noteheads.slash.quarter",nostem:"noteheads.slash.nostem"},x:{"-1":"noteheads.indeterminate",0:"noteheads.indeterminate",1:"noteheads.indeterminate",2:"noteheads.indeterminate",3:"noteheads.indeterminate",4:"noteheads.indeterminate",5:"noteheads.indeterminate",6:"noteheads.indeterminate",7:"noteheads.indeterminate",nostem:"noteheads.indeterminate"},harmonic:{"-1":"noteheads.harmonic.quarter",0:"noteheads.harmonic.quarter",1:"noteheads.harmonic.quarter",2:"noteheads.harmonic.quarter",3:"noteheads.harmonic.quarter",4:"noteheads.harmonic.quarter",5:"noteheads.harmonic.quarter",6:"noteheads.harmonic.quarter",7:"noteheads.harmonic.quarter",nostem:"noteheads.harmonic.quarter"},uflags:{3:"flags.u8th",4:"flags.u16th",5:"flags.u32nd",6:"flags.u64th"},dflags:{3:"flags.d8th",4:"flags.d16th",5:"flags.d32nd",6:"flags.d64th"}},this.reset()},ABCJS.write.AbstractEngraver.prototype.reset=function(){this.slurs={},this.ties=[],this.slursbyvoice={},this.tiesbyvoice={},this.endingsbyvoice={},this.s=0,this.v=0,this.tripletmultiplier=1,this.abcline=void 0,this.accidentalSlot=void 0,this.accidentalshiftx=void 0,this.dotshiftx=void 0,this.hasVocals=!1,this.minY=void 0,this.partstartelem=void 0,this.pos=void 0,this.roomtaken=void 0,this.roomtakenright=void 0,this.staffgroup=void 0,this.startlimitelem=void 0,this.stemdir=void 0,this.voice=void 0},ABCJS.write.AbstractEngraver.prototype.setStemHeight=function(heightInPixels){this.stemHeight=heightInPixels/ABCJS.write.spacing.STEP},ABCJS.write.AbstractEngraver.prototype.getCurrentVoiceId=function(){return"s"+this.s+"v"+this.v},ABCJS.write.AbstractEngraver.prototype.pushCrossLineElems=function(){this.slursbyvoice[this.getCurrentVoiceId()]=this.slurs,this.tiesbyvoice[this.getCurrentVoiceId()]=this.ties,this.endingsbyvoice[this.getCurrentVoiceId()]=this.partstartelem},ABCJS.write.AbstractEngraver.prototype.popCrossLineElems=function(){this.slurs=this.slursbyvoice[this.getCurrentVoiceId()]||{},this.ties=this.tiesbyvoice[this.getCurrentVoiceId()]||[],this.partstartelem=this.endingsbyvoice[this.getCurrentVoiceId()]},ABCJS.write.AbstractEngraver.prototype.getElem=function(){return this.abcline.length<=this.pos?null:this.abcline[this.pos]},ABCJS.write.AbstractEngraver.prototype.getNextElem=function(){return this.abcline.length<=this.pos+1?null:this.abcline[this.pos+1]},ABCJS.write.AbstractEngraver.prototype.containsLyrics=function(staves){for(var i=0;i<staves.length;i++)for(var j=0;j<staves[i].voices.length;j++)for(var k=0;k<staves[i].voices[j].length;k++){var el=staves[i].voices[j][k];if(el.lyric)return void(el.positioning&&"below"!==el.positioning.vocalPosition||(this.hasVocals=!0))}},ABCJS.write.AbstractEngraver.prototype.createABCLine=function(staffs,tempo){for(this.minY=2,this.containsLyrics(staffs),this.staffgroup=new ABCJS.write.StaffGroupElement,this.tempoSet=!1,this.s=0;this.s<staffs.length;this.s++)ABCJS.write.hint&&this.restoreState(),ABCJS.write.hint=!1,this.createABCStaff(staffs[this.s],tempo);return this.staffgroup},ABCJS.write.AbstractEngraver.prototype.createABCStaff=function(abcstaff,tempo){for(this.v=0;this.v<abcstaff.voices.length;this.v++){this.voice=new ABCJS.write.VoiceElement(this.v,abcstaff.voices.length),0===this.v?(this.voice.barfrom="start"===abcstaff.connectBarLines||"continue"===abcstaff.connectBarLines,this.voice.barto="continue"===abcstaff.connectBarLines||"end"===abcstaff.connectBarLines):this.voice.duplicate=!0,abcstaff.title&&abcstaff.title[this.v]&&(this.voice.header=abcstaff.title[this.v]);var clef=ABCJS.write.createClef(abcstaff.clef,this.tuneNumber);clef&&(0===this.v&&abcstaff.barNumber&&this.addMeasureNumber(abcstaff.barNumber,clef),this.voice.addChild(clef));var keySig=ABCJS.write.createKeySignature(abcstaff.key,this.tuneNumber);if(keySig&&(this.voice.addChild(keySig),this.startlimitelem=keySig),abcstaff.meter){var ts=ABCJS.write.createTimeSignature(abcstaff.meter,this.tuneNumber);this.voice.addChild(ts),this.startlimitelem=ts}this.voice.duplicate&&(this.voice.children=[]);var staffLines=abcstaff.clef.stafflines||0===abcstaff.clef.stafflines?abcstaff.clef.stafflines:5;this.staffgroup.addVoice(this.voice,this.s,staffLines),this.createABCVoice(abcstaff.voices[this.v],tempo),this.staffgroup.setStaffLimits(this.voice),"start"===abcstaff.brace?this.staffgroup.brace=new ABCJS.write.BraceElem(1,!0):"end"===abcstaff.brace&&this.staffgroup.brace?this.staffgroup.brace.increaseStavesIncluded():"continue"===abcstaff.brace&&this.staffgroup.brace&&this.staffgroup.brace.increaseStavesIncluded()}},ABCJS.write.AbstractEngraver.prototype.createABCVoice=function(abcline,tempo){this.popCrossLineElems(),this.stemdir=this.isBagpipes?"down":null,this.abcline=abcline,this.partstartelem&&(this.partstartelem=new ABCJS.write.EndingElem("",null,null),this.voice.addOther(this.partstartelem));for(var slur in this.slurs)this.slurs.hasOwnProperty(slur)&&(this.slurs[slur]=new ABCJS.write.TieElem(null,null,this.slurs[slur].above,this.slurs[slur].force,!1),ABCJS.write.hint&&this.slurs[slur].setHint(),this.voice.addOther(this.slurs[slur]));for(var i=0;i<this.ties.length;i++)this.ties[i]=new ABCJS.write.TieElem(null,null,this.ties[i].above,this.ties[i].force,!0),ABCJS.write.hint&&this.ties[i].setHint(),this.voice.addOther(this.ties[i]);for(this.pos=0;this.pos<this.abcline.length;this.pos++){var abselems=this.createABCElement();if(abselems)for(i=0;i<abselems.length;i++)this.tempoSet||!tempo||tempo.suppress||(this.tempoSet=!0,abselems[i].addChild(new ABCJS.write.TempoElement(tempo,this.tuneNumber))),this.voice.addChild(abselems[i])}this.pushCrossLineElems()},ABCJS.write.AbstractEngraver.prototype.saveState=function(){this.tiesSave=ABCJS.parse.cloneArray(this.ties),this.slursSave=ABCJS.parse.cloneHashOfHash(this.slurs),this.slursbyvoiceSave=ABCJS.parse.cloneHashOfHash(this.slursbyvoice),this.tiesbyvoiceSave=ABCJS.parse.cloneHashOfArrayOfHash(this.tiesbyvoice)},ABCJS.write.AbstractEngraver.prototype.restoreState=function(){this.ties=ABCJS.parse.cloneArray(this.tiesSave),this.slurs=ABCJS.parse.cloneHashOfHash(this.slursSave),this.slursbyvoice=ABCJS.parse.cloneHashOfHash(this.slursbyvoiceSave),this.tiesbyvoice=ABCJS.parse.cloneHashOfArrayOfHash(this.tiesbyvoiceSave)},ABCJS.write.AbstractEngraver.prototype.createABCElement=function(){var elemset=[],elem=this.getElem();switch(elem.el_type){case"note":elemset=this.createBeam();break;case"bar":elemset[0]=this.createBarLine(elem),this.voice.duplicate&&(elemset[0].invisible=!0);break;case"meter":elemset[0]=ABCJS.write.createTimeSignature(elem,this.tuneNumber),this.startlimitelem=elemset[0],this.voice.duplicate&&(elemset[0].invisible=!0);break;case"clef":if(elemset[0]=ABCJS.write.createClef(elem,this.tuneNumber),!elemset[0])return null;this.voice.duplicate&&(elemset[0].invisible=!0);break;case"key":var absKey=ABCJS.write.createKeySignature(elem,this.tuneNumber);absKey&&(elemset[0]=absKey,this.startlimitelem=elemset[0]),this.voice.duplicate&&(elemset[0].invisible=!0);break;case"stem":this.stemdir=elem.direction;break;case"part":var abselem=new ABCJS.write.AbsoluteElement(elem,0,0,"part",this.tuneNumber),dim=this.renderer.getTextSize(elem.title,"partsfont","part");abselem.addChild(new ABCJS.write.RelativeElement(elem.title,0,0,void 0,{type:"part",height:dim.height/ABCJS.write.spacing.STEP})),elemset[0]=abselem;break;case"tempo":var abselem3=new ABCJS.write.AbsoluteElement(elem,0,0,"tempo",this.tuneNumber);abselem3.addChild(new ABCJS.write.TempoElement(elem,this.tuneNumber)),elemset[0]=abselem3;break;case"style":"normal"===elem.head?delete this.style:this.style=elem.head;break;case"hint":ABCJS.write.hint=!0,this.saveState();break;case"midi":break;default:var abselem2=new ABCJS.write.AbsoluteElement(elem,0,0,"unsupported",this.tuneNumber);abselem2.addChild(new ABCJS.write.RelativeElement("element type "+elem.el_type,0,0,void 0,{type:"debug"})),elemset[0]=abselem2}return elemset},ABCJS.write.AbstractEngraver.prototype.calcBeamDir=function(){if(this.stemdir)return this.stemdir;for(var abselem,beamelem=new ABCJS.write.BeamElem(this.stemHeight,this.stemdir),oldPos=this.pos;this.getElem()&&(abselem=this.createNote(this.getElem(),!0,!0),beamelem.add(abselem),!this.getElem().endBeam);)this.pos++;var dir=beamelem.calcDir();return this.pos=oldPos,dir?"up":"down"},ABCJS.write.AbstractEngraver.prototype.createBeam=function(){var abselemset=[];if(this.getElem().startBeam&&!this.getElem().endBeam){var dir=this.calcBeamDir(),beamelem=new ABCJS.write.BeamElem(this.stemHeight,dir);ABCJS.write.hint&&beamelem.setHint();var oldDir=this.stemdir;for(this.stemdir=dir;this.getElem();){var abselem=this.createNote(this.getElem(),!0);if(abselemset.push(abselem),beamelem.add(abselem),this.triplet&&this.triplet.isClosed()&&(this.voice.addOther(this.triplet),this.triplet=null,this.tripletmultiplier=1),this.getElem().endBeam)break;this.pos++}this.stemdir=oldDir,this.voice.addBeam(beamelem)}else abselemset[0]=this.createNote(this.getElem()),this.triplet&&this.triplet.isClosed()&&(this.voice.addOther(this.triplet),this.triplet=null,this.tripletmultiplier=1);return abselemset},ABCJS.write.sortPitch=function(elem){var sorted;do{sorted=!0;for(var p=0;p<elem.pitches.length-1;p++)if(elem.pitches[p].pitch>elem.pitches[p+1].pitch){sorted=!1;var tmp=elem.pitches[p];elem.pitches[p]=elem.pitches[p+1],elem.pitches[p+1]=tmp}}while(!sorted)},ABCJS.write.ledgerLines=function(abselem,minPitch,maxPitch,isRest,c,additionalLedgers,dir,dx,scale){for(var i=maxPitch;i>11;i--)i%2!==0||isRest||abselem.addChild(new ABCJS.write.RelativeElement(null,dx,(ABCJS.write.glyphs.getSymbolWidth(c)+4)*scale,i,{type:"ledger"}));for(i=minPitch;i<1;i++)i%2!==0||isRest||abselem.addChild(new ABCJS.write.RelativeElement(null,dx,(ABCJS.write.glyphs.getSymbolWidth(c)+4)*scale,i,{type:"ledger"}));for(i=0;i<additionalLedgers.length;i++){var ofs=ABCJS.write.glyphs.getSymbolWidth(c);"down"===dir&&(ofs=-ofs),abselem.addChild(new ABCJS.write.RelativeElement(null,ofs+dx,(ABCJS.write.glyphs.getSymbolWidth(c)+4)*scale,additionalLedgers[i],{type:"ledger"}))}},ABCJS.write.AbstractEngraver.prototype.createNote=function(elem,nostem,dontDraw){var notehead=null,grace=null;this.roomtaken=0,this.roomtakenright=0;var p,i,pp,width,p1,p2,dx,dotshiftx=0,c="",flag=null,additionalLedgers=[],duration=ABCJS.write.getDuration(elem),zeroDuration=!1;0===duration&&(zeroDuration=!0,duration=.25,nostem=!0);for(var durlog=Math.floor(Math.log(duration)/Math.log(2)),dot=0,tot=Math.pow(2,durlog),inc=tot/2;tot<duration;dot++,tot+=inc,inc/=2);elem.startTriplet&&(2===elem.startTriplet?this.tripletmultiplier=1.5:this.tripletmultiplier=(elem.startTriplet-1)/elem.startTriplet);var abselem=new ABCJS.write.AbsoluteElement(elem,duration*this.tripletmultiplier,1,"note",this.tuneNumber);if(ABCJS.write.hint&&abselem.setHint(),elem.rest){var restpitch=7;"down"===this.stemdir&&(restpitch=3),"up"===this.stemdir&&(restpitch=11);var numLines=this.staffgroup.staffs[this.staffgroup.staffs.length-1].lines;switch(1===numLines&&(restpitch=duration<.5?7:duration<1?6.8:4.8),elem.rest.type){case"whole":c=this.chartable.rest[0],elem.averagepitch=restpitch,elem.minpitch=restpitch,elem.maxpitch=restpitch,dot=0;break;case"rest":c=this.chartable.rest[-durlog],elem.averagepitch=restpitch,elem.minpitch=restpitch,elem.maxpitch=restpitch;break;case"invisible":case"spacer":c="",elem.averagepitch=restpitch,elem.minpitch=restpitch,elem.maxpitch=restpitch}dontDraw||(notehead=this.createNoteHead(abselem,c,{verticalPos:restpitch},null,0,-this.roomtaken,null,dot,0,1)),notehead&&abselem.addHead(notehead),this.roomtaken+=this.accidentalshiftx,this.roomtakenright=Math.max(this.roomtakenright,this.dotshiftx)}else{ABCJS.write.sortPitch(elem);var sum=0;for(p=0,pp=elem.pitches.length;p<pp;p++)sum+=elem.pitches[p].verticalPos;elem.averagepitch=sum/elem.pitches.length,elem.minpitch=elem.pitches[0].verticalPos,this.minY=Math.min(elem.minpitch,this.minY),elem.maxpitch=elem.pitches[elem.pitches.length-1].verticalPos;var dir=elem.averagepitch>=6?"down":"up";this.stemdir&&(dir=this.stemdir);var style=elem.style?elem.style:this.style;style&&"normal"!==style||(style="note");var noteSymbol;for(noteSymbol=zeroDuration?this.chartable[style].nostem:this.chartable[style][-durlog],noteSymbol||console.log("noteSymbol:",style,durlog,zeroDuration),p="down"===dir?elem.pitches.length-2:1;"down"===dir?p>=0:p<elem.pitches.length;p="down"===dir?p-1:p+1){var prev=elem.pitches["down"===dir?p+1:p-1],curr=elem.pitches[p],delta="down"===dir?prev.pitch-curr.pitch:curr.pitch-prev.pitch;delta<=1&&!prev.printer_shift&&(curr.printer_shift=delta?"different":"same",(curr.verticalPos>11||curr.verticalPos<1)&&additionalLedgers.push(curr.verticalPos-curr.verticalPos%2),"down"===dir?this.roomtaken=ABCJS.write.glyphs.getSymbolWidth(noteSymbol)+2:dotshiftx=ABCJS.write.glyphs.getSymbolWidth(noteSymbol)+2)}for(this.accidentalSlot=[],p=0;p<elem.pitches.length;p++){nostem||(flag="down"===dir&&0!==p||"up"===dir&&p!==pp-1?null:this.chartable["down"===dir?"dflags":"uflags"][-durlog]),c=noteSymbol,elem.pitches[p].highestVert=elem.pitches[p].verticalPos;var isTopWhenStemIsDown=("up"===this.stemdir||"up"===dir)&&0===p,isBottomWhenStemIsUp=("down"===this.stemdir||"down"===dir)&&p===pp-1;if(!dontDraw&&(isTopWhenStemIsDown||isBottomWhenStemIsUp)){if((elem.startSlur||1===pp)&&(elem.pitches[p].highestVert=elem.pitches[pp-1].verticalPos,"up"!==this.stemdir&&"up"!==dir||(elem.pitches[p].highestVert+=6)),elem.startSlur)for(elem.pitches[p].startSlur||(elem.pitches[p].startSlur=[]),i=0;i<elem.startSlur.length;i++)elem.pitches[p].startSlur.push(elem.startSlur[i]);if(!dontDraw&&elem.endSlur)for(elem.pitches[p].highestVert=elem.pitches[pp-1].verticalPos,"up"!==this.stemdir&&"up"!==dir||(elem.pitches[p].highestVert+=6),elem.pitches[p].endSlur||(elem.pitches[p].endSlur=[]),i=0;i<elem.endSlur.length;i++)elem.pitches[p].endSlur.push(elem.endSlur[i])}var hasStem=!nostem&&durlog<=-1;dontDraw||(notehead=this.createNoteHead(abselem,c,elem.pitches[p],hasStem?dir:null,0,-this.roomtaken,flag,dot,dotshiftx,1)),notehead&&abselem.addHead(notehead),this.roomtaken+=this.accidentalshiftx,this.roomtakenright=Math.max(this.roomtakenright,this.dotshiftx)}hasStem&&(p1="down"===dir?elem.minpitch-7:elem.minpitch+1/3,p1>6&&!this.stemdir&&(p1=6),p2="down"===dir?elem.maxpitch-1/3:elem.maxpitch+7,p2<6&&!this.stemdir&&(p2=6),dx="down"===dir||0===abselem.heads.length?0:abselem.heads[0].w,width="down"===dir?1:-1,"noteheads.slash.quarter"===notehead.c&&("down"===dir?p2-=1:p1+=1),abselem.addExtra(new ABCJS.write.RelativeElement(null,dx,0,p1,{type:"stem",pitch2:p2,linewidth:width})),this.minY=Math.min(p1,this.minY),this.minY=Math.min(p2,this.minY))}if(void 0!==elem.lyric){var lyricStr="";window.ABCJS.parse.each(elem.lyric,function(ly){lyricStr+=ly.syllable+ly.divider+"\n"});var lyricDim=this.renderer.getTextSize(lyricStr,"vocalfont","abc-lyric"),position=elem.positioning?elem.positioning.vocalPosition:"below";abselem.addCentered(new ABCJS.write.RelativeElement(lyricStr,0,lyricDim.width,void 0,{type:"lyric",position:position,height:lyricDim.height/ABCJS.write.spacing.STEP}))}if(!dontDraw&&void 0!==elem.gracenotes){var gracescale=.6,graceScaleStem=.7,gracebeam=null;elem.gracenotes.length>1&&(gracebeam=new ABCJS.write.BeamElem(this.stemHeight*graceScaleStem,"grace",this.isBagpipes), ABCJS.write.hint&&gracebeam.setHint(),gracebeam.mainNote=abselem);var graceoffsets=[];for(i=elem.gracenotes.length-1;i>=0;i--)this.roomtaken+=10,graceoffsets[i]=this.roomtaken,elem.gracenotes[i].accidental&&(this.roomtaken+=7);for(i=0;i<elem.gracenotes.length;i++){var gracepitch=elem.gracenotes[i].verticalPos;if(flag=gracebeam?null:this.chartable.uflags[this.isBagpipes?5:3],grace=this.createNoteHead(abselem,"noteheads.quarter",elem.gracenotes[i],"up",-graceoffsets[i],-graceoffsets[i],flag,0,0,gracescale),abselem.addExtra(grace),elem.gracenotes[i].acciaccatura){var pos=elem.gracenotes[i].verticalPos+7*gracescale,dAcciaccatura=gracebeam?5:6;abselem.addRight(new ABCJS.write.RelativeElement("flags.ugrace",-graceoffsets[i]+dAcciaccatura,0,pos,{scalex:gracescale,scaley:gracescale}))}if(gracebeam){var graceDuration=elem.gracenotes[i].duration/2;this.isBagpipes&&(graceDuration/=2);var pseudoabselem={heads:[grace],abcelem:{averagepitch:gracepitch,minpitch:gracepitch,maxpitch:gracepitch,duration:graceDuration}};gracebeam.add(pseudoabselem)}else p1=gracepitch+1/3*gracescale,p2=gracepitch+7*gracescale,dx=grace.dx+grace.w,width=-.6,abselem.addExtra(new ABCJS.write.RelativeElement(null,dx,0,p1,{type:"stem",pitch2:p2,linewidth:width}));ABCJS.write.ledgerLines(abselem,gracepitch,gracepitch,!1,"noteheads.quarter",[],!0,grace.dx-1,.6),0!==i||this.isBagpipes||elem.rest&&("spacer"===elem.rest.type||"invisible"===elem.rest.type)||this.voice.addOther(new ABCJS.write.TieElem(grace,notehead,!1,!0,!1))}gracebeam&&this.voice.addBeam(gracebeam)}!dontDraw&&elem.decoration&&this.decoration.createDecoration(this.voice,elem.decoration,abselem.top,notehead?notehead.w:0,abselem,this.roomtaken,dir,abselem.bottom,elem.positioning,this.hasVocals),elem.barNumber&&abselem.addChild(new ABCJS.write.RelativeElement(elem.barNumber,-10,0,0,{type:"barNumber"})),ABCJS.write.ledgerLines(abselem,elem.minpitch,elem.maxpitch,elem.rest,c,additionalLedgers,dir,-2,1);var chordMargin=8;if(void 0!==elem.chord)for(i=0;i<elem.chord.length;i++){var y,x=0,dim=this.renderer.getTextSize(elem.chord[i].name,"annotationfont","annotation"),chordWidth=dim.width,chordHeight=dim.height/ABCJS.write.spacing.STEP;switch(elem.chord[i].position){case"left":this.roomtaken+=chordWidth+7,x=-this.roomtaken,y=elem.averagepitch,abselem.addExtra(new ABCJS.write.RelativeElement(elem.chord[i].name,x,chordWidth+4,y,{type:"text",height:chordHeight}));break;case"right":this.roomtakenright+=4,x=this.roomtakenright,y=elem.averagepitch,abselem.addRight(new ABCJS.write.RelativeElement(elem.chord[i].name,x,chordWidth+4,y,{type:"text",height:chordHeight}));break;case"below":for(var eachLine=elem.chord[i].name.split("\n"),ii=0;ii<eachLine.length;ii++)abselem.addRight(new ABCJS.write.RelativeElement(eachLine[ii],x,chordWidth+chordMargin,void 0,{type:"text",position:"below",height:chordHeight}));break;case"above":abselem.addRight(new ABCJS.write.RelativeElement(elem.chord[i].name,0,chordWidth+chordMargin,void 0,{type:"text",height:chordHeight}));break;default:if(elem.chord[i].rel_position){var relPositionY=elem.chord[i].rel_position.y+3*ABCJS.write.spacing.STEP;abselem.addChild(new ABCJS.write.RelativeElement(elem.chord[i].name,x+elem.chord[i].rel_position.x,0,elem.minpitch+relPositionY/ABCJS.write.spacing.STEP,{type:"text",height:chordHeight}))}else{var pos2="above";elem.positioning&&elem.positioning.chordPosition&&(pos2=elem.positioning.chordPosition),dim=this.renderer.getTextSize(elem.chord[i].name,"gchordfont","chord"),chordHeight=dim.height/ABCJS.write.spacing.STEP,chordWidth=dim.width,abselem.addCentered(new ABCJS.write.RelativeElement(elem.chord[i].name,x,chordWidth,void 0,{type:"chord",position:pos2,height:chordHeight}))}}}return elem.startTriplet&&!dontDraw&&(this.triplet=new ABCJS.write.TripletElem(elem.startTriplet,notehead)),elem.endTriplet&&this.triplet&&!dontDraw&&this.triplet.setCloseAnchor(notehead),abselem},ABCJS.write.AbstractEngraver.prototype.createNoteHead=function(abselem,c,pitchelem,dir,headx,extrax,flag,dot,dotshiftx,scale){var notehead,i,pitch=pitchelem.verticalPos;if(this.accidentalshiftx=0,this.dotshiftx=0,void 0===c)abselem.addChild(new ABCJS.write.RelativeElement("pitch is undefined",0,0,0,{type:"debug"}));else if(""===c)notehead=new ABCJS.write.RelativeElement(null,0,0,pitch);else{var shiftheadx=headx;if(pitchelem.printer_shift){var adjust="same"===pitchelem.printer_shift?1:0;shiftheadx="down"===dir?-ABCJS.write.glyphs.getSymbolWidth(c)*scale+adjust:ABCJS.write.glyphs.getSymbolWidth(c)*scale-adjust}var opts={scalex:scale,scaley:scale,thickness:ABCJS.write.glyphs.symbolHeightInPitches(c)*scale};if(notehead=new ABCJS.write.RelativeElement(c,shiftheadx,ABCJS.write.glyphs.getSymbolWidth(c)*scale,pitch,opts),flag){var pos=pitch+("down"===dir?-7:7)*scale;(1===scale&&"down"===dir?pos>6:pos<6)&&(pos=6);var xdelta="down"===dir?headx:headx+notehead.w-.6;abselem.addRight(new ABCJS.write.RelativeElement(flag,xdelta,ABCJS.write.glyphs.getSymbolWidth(flag)*scale,pos,{scalex:scale,scaley:scale}))}for(this.dotshiftx=notehead.w+dotshiftx-2+5*dot;dot>0;dot--){var dotadjusty=1-Math.abs(pitch)%2;abselem.addRight(new ABCJS.write.RelativeElement("dots.dot",notehead.w+dotshiftx-2+5*dot,ABCJS.write.glyphs.getSymbolWidth("dots.dot"),pitch+dotadjusty))}}if(notehead&&(notehead.highestVert=pitchelem.highestVert),pitchelem.accidental){var symb;switch(pitchelem.accidental){case"quartersharp":symb="accidentals.halfsharp";break;case"dblsharp":symb="accidentals.dblsharp";break;case"sharp":symb="accidentals.sharp";break;case"quarterflat":symb="accidentals.halfflat";break;case"flat":symb="accidentals.flat";break;case"dblflat":symb="accidentals.dblflat";break;case"natural":symb="accidentals.nat"}for(var accSlotFound=!1,accPlace=extrax,j=0;j<this.accidentalSlot.length;j++)if(pitch-this.accidentalSlot[j][0]>=6){this.accidentalSlot[j][0]=pitch,accPlace=this.accidentalSlot[j][1],accSlotFound=!0;break}accSlotFound===!1&&(accPlace-=ABCJS.write.glyphs.getSymbolWidth(symb)*scale+2,this.accidentalSlot.push([pitch,accPlace]),this.accidentalshiftx=ABCJS.write.glyphs.getSymbolWidth(symb)*scale+2),abselem.addExtra(new ABCJS.write.RelativeElement(symb,accPlace,ABCJS.write.glyphs.getSymbolWidth(symb),pitch,{scalex:scale,scaley:scale}))}if(pitchelem.endTie&&this.ties[0]&&(this.ties[0].setEndAnchor(notehead),this.ties=this.ties.slice(1,this.ties.length)),pitchelem.startTie){var tie=new ABCJS.write.TieElem(notehead,null,("down"===this.stemdir||"down"===dir)&&"up"!==this.stemdir,"down"===this.stemdir||"up"===this.stemdir,!0);ABCJS.write.hint&&tie.setHint(),this.ties[this.ties.length]=tie,this.voice.addOther(tie),abselem.startTie=!0}if(pitchelem.endSlur)for(i=0;i<pitchelem.endSlur.length;i++){var slur,slurid=pitchelem.endSlur[i];this.slurs[slurid]?(slur=this.slurs[slurid],slur.setEndAnchor(notehead),delete this.slurs[slurid]):(slur=new ABCJS.write.TieElem(null,notehead,"down"===dir,("up"===this.stemdir||"down"===dir)&&"down"!==this.stemdir,!1),ABCJS.write.hint&&slur.setHint(),this.voice.addOther(slur)),this.startlimitelem&&slur.setStartX(this.startlimitelem)}if(pitchelem.startSlur)for(i=0;i<pitchelem.startSlur.length;i++){var slurid=pitchelem.startSlur[i].label,slur=new ABCJS.write.TieElem(notehead,null,("down"===this.stemdir||"down"===dir)&&"up"!==this.stemdir,!1,!1);ABCJS.write.hint&&slur.setHint(),this.slurs[slurid]=slur,this.voice.addOther(slur)}return notehead},ABCJS.write.AbstractEngraver.prototype.addMeasureNumber=function(number,abselem){var measureNumHeight=this.renderer.getTextSize(number,"measurefont","bar-number");abselem.addChild(new ABCJS.write.RelativeElement(number,0,0,11+measureNumHeight.height/ABCJS.write.spacing.STEP,{type:"barNumber"}))},ABCJS.write.AbstractEngraver.prototype.createBarLine=function(elem){var abselem=new ABCJS.write.AbsoluteElement(elem,0,10,"bar",this.tuneNumber),anchor=null,dx=0;elem.barNumber&&this.addMeasureNumber(elem.barNumber,abselem);var firstdots="bar_right_repeat"===elem.type||"bar_dbl_repeat"===elem.type,firstthin="bar_left_repeat"!==elem.type&&"bar_thick_thin"!==elem.type&&"bar_invisible"!==elem.type,thick="bar_right_repeat"===elem.type||"bar_dbl_repeat"===elem.type||"bar_left_repeat"===elem.type||"bar_thin_thick"===elem.type||"bar_thick_thin"===elem.type,secondthin="bar_left_repeat"===elem.type||"bar_thick_thin"===elem.type||"bar_thin_thin"===elem.type||"bar_dbl_repeat"===elem.type,seconddots="bar_left_repeat"===elem.type||"bar_dbl_repeat"===elem.type;if(firstdots||seconddots){for(var slur in this.slurs)this.slurs.hasOwnProperty(slur)&&this.slurs[slur].setEndX(abselem);this.startlimitelem=abselem}if(firstdots&&(abselem.addRight(new ABCJS.write.RelativeElement("dots.dot",dx,1,7)),abselem.addRight(new ABCJS.write.RelativeElement("dots.dot",dx,1,5)),dx+=6),firstthin&&(anchor=new ABCJS.write.RelativeElement(null,dx,1,2,{type:"bar",pitch2:10,linewidth:.6}),abselem.addRight(anchor)),"bar_invisible"===elem.type&&(anchor=new ABCJS.write.RelativeElement(null,dx,1,2,{type:"none",pitch2:10,linewidth:.6}),abselem.addRight(anchor)),elem.decoration&&this.decoration.createDecoration(this.voice,elem.decoration,12,thick?3:1,abselem,0,"down",2,elem.positioning,this.hasVocals),thick&&(dx+=4,anchor=new ABCJS.write.RelativeElement(null,dx,4,2,{type:"bar",pitch2:10,linewidth:4}),abselem.addRight(anchor),dx+=5),this.partstartelem&&elem.endEnding&&(this.partstartelem.anchor2=anchor,this.partstartelem=null),secondthin&&(dx+=3,anchor=new ABCJS.write.RelativeElement(null,dx,1,2,{type:"bar",pitch2:10,linewidth:.6}),abselem.addRight(anchor)),seconddots&&(dx+=3,abselem.addRight(new ABCJS.write.RelativeElement("dots.dot",dx,1,7)),abselem.addRight(new ABCJS.write.RelativeElement("dots.dot",dx,1,5))),elem.startEnding){var textWidth=this.renderer.getTextSize(elem.startEnding,"repeatfont","").width;abselem.minspacing+=textWidth+10,this.partstartelem=new ABCJS.write.EndingElem(elem.startEnding,anchor,null),this.voice.addOther(this.partstartelem)}return abselem}}(),window.ABCJS||(window.ABCJS={}),window.ABCJS.write||(window.ABCJS.write={}),function(){"use strict";function minStem(element,stemsUp,referencePitch,minStemHeight){if(!element.children)return minStemHeight;for(var i=0;i<element.children.length;i++){var elem=element.children[i];stemsUp&&void 0!==elem.top&&"flags.ugrace"===elem.c?minStemHeight=Math.max(minStemHeight,elem.top-referencePitch):stemsUp||void 0===elem.bottom||"flags.ugrace"!==elem.c||(minStemHeight=Math.max(minStemHeight,referencePitch-elem.bottom+7))}return minStemHeight}function calcSlant(leftAveragePitch,rightAveragePitch,numStems,isFlat){if(isFlat)return 0;var slant=leftAveragePitch-rightAveragePitch,maxSlant=numStems/2;return slant>maxSlant&&(slant=maxSlant),slant<-maxSlant&&(slant=-maxSlant),slant}function calcAverage(total,numElements){return numElements?total/numElements:0}function getBarYAt(startx,starty,endx,endy,x){return starty+(endy-starty)/(endx-startx)*(x-startx)}function calcDy(asc,isGrace){var dy=asc?ABCJS.write.spacing.STEP:-ABCJS.write.spacing.STEP;return isGrace&&(dy*=.4),dy}function drawBeam(renderer,startX,startY,endX,endY,dy,isHint){var klass="beam-elem";isHint&&(klass+=" abcjs-hint"),startY=renderer.calcY(startY),endY=renderer.calcY(endY);var pathString="M"+startX+" "+startY+" L"+endX+" "+endY+"L"+endX+" "+(endY+dy)+" L"+startX+" "+(startY+dy)+"z";renderer.printPath({path:pathString,stroke:"none",fill:"#000000",class:renderer.addClasses(klass)})}function calcXPos(asc,firstElement,lastElement){var starthead=firstElement.heads[asc?0:firstElement.heads.length-1],endhead=lastElement.heads[asc?0:lastElement.heads.length-1],startX=starthead.x;asc&&(startX+=starthead.w-.6);var endX=endhead.x;return asc&&(endX+=endhead.w),[startX,endX]}function calcYPos(total,numElements,stemHeight,asc,firstAveragePitch,lastAveragePitch,isFlat,minPitch,maxPitch,isGrace){var average=calcAverage(total,numElements),barpos=stemHeight-2,barminpos=stemHeight-2,pos=Math.round(asc?Math.max(average+barpos,maxPitch+barminpos):Math.min(average-barpos,minPitch-barminpos)),slant=calcSlant(firstAveragePitch,lastAveragePitch,numElements,isFlat),startY=pos+Math.floor(slant/2),endY=pos+Math.floor(-slant/2);return isGrace||(asc&&pos<6?(startY=6,endY=6):!asc&&pos>6&&(startY=6,endY=6)),[startY,endY]}function createStems(elems,asc,beam,dy,mainNote){for(var i=0;i<elems.length;i++){var elem=elems[i];if(!elem.abcelem.rest){var isGrace=!elem.addExtra,parent=isGrace?mainNote:elem,furthestHead=elem.heads[asc?0:elem.heads.length-1],ovalDelta=.2,pitch=furthestHead.pitch+(asc?ovalDelta:-ovalDelta),dx=asc?furthestHead.w:0,x=furthestHead.x+dx,bary=getBarYAt(beam.startX,beam.startY,beam.endX,beam.endY,x),lineWidth=asc?-.6:.6;asc||(bary-=dy/2/ABCJS.write.spacing.STEP),isGrace&&(dx+=elem.heads[0].dx),"noteheads.slash.quarter"===furthestHead.c&&(asc?pitch+=1:pitch-=1);var stem=new ABCJS.write.RelativeElement(null,dx,0,pitch,{type:"stem",pitch2:bary,linewidth:lineWidth});stem.setX(parent.x),parent.addExtra(stem)}}}function createAdditionalBeams(elems,asc,beam,isGrace,dy){for(var beams=[],auxBeams=[],i=0;i<elems.length;i++){var elem=elems[i];if(!elem.abcelem.rest){var furthestHead=elem.heads[asc?0:elem.heads.length-1],x=furthestHead.x+(asc?furthestHead.w:0),bary=getBarYAt(beam.startX,beam.startY,beam.endX,beam.endY,x),sy=asc?-1.5:1.5;isGrace&&(sy=2*sy/3);var duration=elem.abcelem.duration;0===duration&&(duration=.25);for(var durlog=ABCJS.write.getDurlog(duration);durlog<-3;durlog++)auxBeams[-4-durlog]?auxBeams[-4-durlog].single=!1:auxBeams[-4-durlog]={x:x+(asc?-.6:0),y:bary+sy*(-4-durlog+1),durlog:durlog,single:!0};for(var j=auxBeams.length-1;j>=0;j--)if(i===elems.length-1||ABCJS.write.getDurlog(elems[i+1].abcelem.duration)>-j-4){var auxBeamEndX=x,auxBeamEndY=bary+sy*(j+1);auxBeams[j].single&&(auxBeamEndX=0===i?x+5:x-5,auxBeamEndY=getBarYAt(beam.startX,beam.startY,beam.endX,beam.endY,auxBeamEndX)+sy*(j+1)),beams.push({startX:auxBeams[j].x,endX:auxBeamEndX,startY:auxBeams[j].y,endY:auxBeamEndY,dy:dy}),auxBeams=auxBeams.slice(0,j)}}}return beams}ABCJS.write.BeamElem=function(stemHeight,type,flat){this.isflat=flat,this.isgrace=type&&"grace"===type,this.forceup=this.isgrace||type&&"up"===type,this.forcedown=type&&"down"===type,this.elems=[],this.total=0,this.allrests=!0,this.stemHeight=stemHeight,this.beams=[]},ABCJS.write.BeamElem.prototype.setHint=function(){this.hint=!0},ABCJS.write.BeamElem.prototype.add=function(abselem){var pitch=abselem.abcelem.averagepitch;void 0!==pitch&&(this.allrests=this.allrests&&abselem.abcelem.rest,abselem.beam=this,this.elems.push(abselem),this.total+=pitch,(!this.min||abselem.abcelem.minpitch<this.min)&&(this.min=abselem.abcelem.minpitch),(!this.max||abselem.abcelem.maxpitch>this.max)&&(this.max=abselem.abcelem.maxpitch))};var middleLine=6;ABCJS.write.BeamElem.prototype.calcDir=function(){if(this.forceup)return!0;if(this.forcedown)return!1;var average=calcAverage(this.total,this.elems.length);return average<middleLine},ABCJS.write.BeamElem.prototype.layout=function(){if(0!==this.elems.length&&!this.allrests){this.stemsUp=this.calcDir();var dy=calcDy(this.stemsUp,this.isgrace),firstElement=this.elems[0],lastElement=this.elems[this.elems.length-1],minStemHeight=0,referencePitch=this.stemsUp?firstElement.abcelem.maxpitch:firstElement.abcelem.minpitch;minStemHeight=minStem(firstElement,this.stemsUp,referencePitch,minStemHeight),minStemHeight=minStem(lastElement,this.stemsUp,referencePitch,minStemHeight),minStemHeight=Math.max(this.stemHeight,minStemHeight+3);var yPos=calcYPos(this.total,this.elems.length,minStemHeight,this.stemsUp,firstElement.abcelem.averagepitch,lastElement.abcelem.averagepitch,this.isflat,this.min,this.max,this.isgrace),xPos=calcXPos(this.stemsUp,firstElement,lastElement);this.beams.push({startX:xPos[0],endX:xPos[1],startY:yPos[0],endY:yPos[1],dy:dy});for(var beams=createAdditionalBeams(this.elems,this.stemsUp,this.beams[0],this.isgrace,dy),i=0;i<beams.length;i++)this.beams.push(beams[i]);createStems(this.elems,this.stemsUp,this.beams[0],dy,this.mainNote)}},ABCJS.write.BeamElem.prototype.isAbove=function(){return this.stemsUp},ABCJS.write.BeamElem.prototype.heightAtMidpoint=function(startX,endX){if(0===this.beams.length)return 0;var beam=this.beams[0],midPoint=startX+(endX-startX)/2;return getBarYAt(beam.startX,beam.startY,beam.endX,beam.endY,midPoint)},ABCJS.write.BeamElem.prototype.yAtNote=function(element){var beam=this.beams[0];return getBarYAt(beam.startX,beam.startY,beam.endX,beam.endY,element.x)},ABCJS.write.BeamElem.prototype.xAtMidpoint=function(startX,endX){return startX+(endX-startX)/2},ABCJS.write.BeamElem.prototype.draw=function(renderer){if(0!==this.beams.length){renderer.beginGroup();for(var i=0;i<this.beams.length;i++){var beam=this.beams[i];drawBeam(renderer,beam.startX,beam.startY,beam.endX,beam.endY,beam.dy,this.hint)}renderer.endGroup("beam-elem")}}}(),window.ABCJS||(window.ABCJS={}),window.ABCJS.write||(window.ABCJS.write={}),ABCJS.write.BraceElem=function(){this.length=1},ABCJS.write.BraceElem.prototype.increaseStavesIncluded=function(){this.length++},ABCJS.write.BraceElem.prototype.setLocation=function(x){this.x=x},ABCJS.write.BraceElem.prototype.getWidth=function(){return 10},ABCJS.write.BraceElem.prototype.layout=function(renderer,top,bottom){this.startY=top,this.endY=bottom},ABCJS.write.BraceElem.prototype.draw=function(renderer,top,bottom){this.layout(renderer,top,bottom),renderer.drawBrace(this.x,this.startY,this.endY)},window.ABCJS||(window.ABCJS={}),window.ABCJS.write||(window.ABCJS.write={}),function(){"use strict";ABCJS.write.createClef=function(elem,tuneNumber){var clef,octave=0,abselem=new ABCJS.write.AbsoluteElement(elem,0,10,"staff-extra",tuneNumber);switch(elem.type){case"treble":clef="clefs.G";break;case"tenor":clef="clefs.C";break;case"alto":clef="clefs.C";break;case"bass":clef="clefs.F";break;case"treble+8":clef="clefs.G",octave=1;break;case"tenor+8":clef="clefs.C",octave=1;break;case"bass+8":clef="clefs.F",octave=1;break;case"alto+8":clef="clefs.C",octave=1;break;case"treble-8":clef="clefs.G",octave=-1;break;case"tenor-8":clef="clefs.C",octave=-1;break;case"bass-8":clef="clefs.F",octave=-1;break;case"alto-8":clef="clefs.C",octave=-1;break;case"none":return null;case"perc":clef="clefs.perc";break;default:abselem.addChild(new ABCJS.write.RelativeElement("clef="+elem.type,0,0,void 0,{type:"debug"}))}var dx=5;if(clef&&(abselem.addRight(new ABCJS.write.RelativeElement(clef,dx,ABCJS.write.glyphs.getSymbolWidth(clef),elem.clefPos)),"clefs.G"===clef?(abselem.top=13,abselem.bottom=-1):(abselem.top=10,abselem.bottom=2),0!==octave)){var scale=2/3,adjustspacing=(ABCJS.write.glyphs.getSymbolWidth(clef)-ABCJS.write.glyphs.getSymbolWidth("8")*scale)/2;abselem.addRight(new ABCJS.write.RelativeElement("8",dx+adjustspacing,ABCJS.write.glyphs.getSymbolWidth("8")*scale,octave>0?abselem.top+3:abselem.bottom-1,{scalex:scale,scaley:scale})),abselem.top+=2}return abselem}}(),window.ABCJS||(window.ABCJS={}),window.ABCJS.write||(window.ABCJS.write={}),function(){"use strict";ABCJS.write.createKeySignature=function(elem,tuneNumber){if(!elem.accidentals||0===elem.accidentals.length)return null;var abselem=new ABCJS.write.AbsoluteElement(elem,0,10,"staff-extra",tuneNumber),dx=0;return window.ABCJS.parse.each(elem.accidentals,function(acc){var symbol="sharp"===acc.acc?"accidentals.sharp":"natural"===acc.acc?"accidentals.nat":"accidentals.flat";abselem.addRight(new ABCJS.write.RelativeElement(symbol,dx,ABCJS.write.glyphs.getSymbolWidth(symbol),acc.verticalPos,{thickness:ABCJS.write.glyphs.symbolHeightInPitches(symbol)})),dx+=ABCJS.write.glyphs.getSymbolWidth(symbol)+2},this),abselem}}(),window.ABCJS||(window.ABCJS={}),window.ABCJS.write||(window.ABCJS.write={}),function(){"use strict";ABCJS.write.createTimeSignature=function(elem,tuneNumber){var abselem=new ABCJS.write.AbsoluteElement(elem,0,10,"staff-extra",tuneNumber);if("specified"===elem.type)for(var i=0;i<elem.value.length;i++)0!==i&&abselem.addRight(new ABCJS.write.RelativeElement("+",20*i-9,ABCJS.write.glyphs.getSymbolWidth("+"),6,{thickness:ABCJS.write.glyphs.symbolHeightInPitches("+")})),elem.value[i].den?(abselem.addRight(new ABCJS.write.RelativeElement(elem.value[i].num,20*i,ABCJS.write.glyphs.getSymbolWidth(elem.value[i].num.charAt(0))*elem.value[i].num.length,8,{thickness:ABCJS.write.glyphs.symbolHeightInPitches(elem.value[i].num.charAt(0))})),abselem.addRight(new ABCJS.write.RelativeElement(elem.value[i].den,20*i,ABCJS.write.glyphs.getSymbolWidth(elem.value[i].den.charAt(0))*elem.value[i].den.length,4,{thickness:ABCJS.write.glyphs.symbolHeightInPitches(elem.value[i].den.charAt(0))}))):abselem.addRight(new ABCJS.write.RelativeElement(elem.value[i].num,20*i,ABCJS.write.glyphs.getSymbolWidth(elem.value[i].num.charAt(0))*elem.value[i].num.length,6,{thickness:ABCJS.write.glyphs.symbolHeightInPitches(elem.value[i].num.charAt(0))}));else"common_time"===elem.type?abselem.addRight(new ABCJS.write.RelativeElement("timesig.common",0,ABCJS.write.glyphs.getSymbolWidth("timesig.common"),6,{thickness:ABCJS.write.glyphs.symbolHeightInPitches("timesig.common")})):"cut_time"===elem.type&&abselem.addRight(new ABCJS.write.RelativeElement("timesig.cut",0,ABCJS.write.glyphs.getSymbolWidth("timesig.cut"),6,{thickness:ABCJS.write.glyphs.symbolHeightInPitches("timesig.cut")}));return abselem}}(),window.ABCJS||(window.ABCJS={}),window.ABCJS.write||(window.ABCJS.write={}),ABCJS.write.CrescendoElem=function(anchor1,anchor2,dir,positioning){this.anchor1=anchor1,this.anchor2=anchor2,this.dir=dir,"above"===positioning?this.dynamicHeightAbove=4:this.dynamicHeightBelow=4,this.pitch=void 0},ABCJS.write.CrescendoElem.prototype.setUpperAndLowerElements=function(positionY){this.dynamicHeightAbove?this.pitch=positionY.dynamicHeightAbove:this.pitch=positionY.dynamicHeightBelow},ABCJS.write.CrescendoElem.prototype.draw=function(renderer){void 0===this.pitch&&window.console.error("Crescendo Element y-coordinate not set.");var y=renderer.calcY(this.pitch)+4,height=8;"<"===this.dir?(this.drawLine(renderer,y+height/2,y),this.drawLine(renderer,y+height/2,y+height)):(this.drawLine(renderer,y,y+height/2),this.drawLine(renderer,y+height,y+height/2))},ABCJS.write.CrescendoElem.prototype.drawLine=function(renderer,y1,y2){var left=this.anchor1?this.anchor1.x:0,right=this.anchor2?this.anchor2.x:800,pathString=ABCJS.write.sprintf("M %f %f L %f %f",left,y1,right,y2);renderer.printPath({path:pathString,stroke:"#000000",class:renderer.addClasses("decoration")})},window.ABCJS||(window.ABCJS={}),window.ABCJS.write||(window.ABCJS.write={}),function(){"use strict";ABCJS.write.Decoration=function(){this.startDiminuendoX=void 0,this.startCrescendoX=void 0,this.minTop=12,this.minBottom=0};var closeDecoration=function(voice,decoration,pitch,width,abselem,roomtaken,dir,minPitch){for(var yPos,i=0;i<decoration.length;i++){if("staccato"===decoration[i]||"tenuto"===decoration[i]||"accent"===decoration[i]){var symbol="scripts."+decoration[i];if("accent"===decoration[i]&&(symbol="scripts.sforzato"),yPos=void 0===yPos?"down"===dir?pitch+2:minPitch-2:"down"===dir?yPos+2:yPos-2,"accent"===decoration[i])"up"===dir?yPos--:yPos++;else switch(yPos){case 2:case 4:case 6:case 8:case 10:"up"===dir?yPos--:yPos++}pitch>9&&yPos++;var deltaX=width/2;"center"!==ABCJS.write.glyphs.getSymbolAlign(symbol)&&(deltaX-=ABCJS.write.glyphs.getSymbolWidth(symbol)/2),abselem.addChild(new ABCJS.write.RelativeElement(symbol,deltaX,ABCJS.write.glyphs.getSymbolWidth(symbol),yPos))}if("slide"===decoration[i]&&abselem.heads[0]){var yPos2=abselem.heads[0].pitch;yPos2-=2;var blank1=new ABCJS.write.RelativeElement("",-roomtaken-15,0,yPos2-1),blank2=new ABCJS.write.RelativeElement("",-roomtaken-5,0,yPos2+1);abselem.addChild(blank1),abselem.addChild(blank2),voice.addOther(new ABCJS.write.TieElem(blank1,blank2,!1,!1,!1))}}return void 0===yPos&&(yPos=pitch),{above:yPos,below:abselem.bottom}},volumeDecoration=function(voice,decoration,abselem,positioning){for(var i=0;i<decoration.length;i++)switch(decoration[i]){case"p":case"mp":case"pp":case"ppp":case"pppp":case"f":case"ff":case"fff":case"ffff":case"sfz":case"mf":var elem=new ABCJS.write.DynamicDecoration(abselem,decoration[i],positioning);voice.addOther(elem)}},compoundDecoration=function(decoration,pitch,width,abselem,dir){function highestPitch(){if(0===abselem.heads.length)return 10;for(var pitch=abselem.heads[0].pitch,i=1;i<abselem.heads.length;i++)pitch=Math.max(pitch,abselem.heads[i].pitch);return pitch}function lowestPitch(){if(0===abselem.heads.length)return 2;for(var pitch=abselem.heads[0].pitch,i=1;i<abselem.heads.length;i++)pitch=Math.min(pitch,abselem.heads[i].pitch);return pitch}function compoundDecoration(symbol,count){var placement="down"===dir?lowestPitch()+1:highestPitch()+9;"down"!==dir&&1===count&&placement--;var deltaX=width/2;deltaX+="down"===dir?-5:3;for(var i=0;i<count;i++)placement-=1,abselem.addChild(new ABCJS.write.RelativeElement(symbol,deltaX,ABCJS.write.glyphs.getSymbolWidth(symbol),placement))}for(var i=0;i<decoration.length;i++)switch(decoration[i]){case"/":compoundDecoration("flags.ugrace",1);break;case"//":compoundDecoration("flags.ugrace",2);break;case"///":compoundDecoration("flags.ugrace",3);break;case"////":compoundDecoration("flags.ugrace",4)}},stackedDecoration=function(decoration,width,abselem,yPos,positioning,minTop,minBottom){function incrementPlacement(placement,height){"above"===placement?yPos.above+=height:yPos.below-=height}function getPlacement(placement){var y;return"above"===placement?(y=yPos.above,y<minTop&&(y=minTop)):(y=yPos.below,y>minBottom&&(y=minBottom)),y}function textDecoration(text,placement){var y=getPlacement(placement),textFudge=2,textHeight=5;abselem.addChild(new ABCJS.write.RelativeElement(text,width/2,0,y+textFudge,{type:"decoration",klass:"ornament",thickness:3})),incrementPlacement(placement,textHeight)}function symbolDecoration(symbol,placement){var deltaX=width/2;"center"!==ABCJS.write.glyphs.getSymbolAlign(symbol)&&(deltaX-=ABCJS.write.glyphs.getSymbolWidth(symbol)/2);var height=ABCJS.write.glyphs.symbolHeightInPitches(symbol)+1,y=getPlacement(placement);y="above"===placement?y+height/2:y-height/2,abselem.addChild(new ABCJS.write.RelativeElement(symbol,deltaX,ABCJS.write.glyphs.getSymbolWidth(symbol),y,{klass:"ornament",thickness:ABCJS.write.glyphs.symbolHeightInPitches(symbol)})),incrementPlacement(placement,height)}for(var symbolList={"+":"scripts.stopped",open:"scripts.open",snap:"scripts.snap",wedge:"scripts.wedge",thumb:"scripts.thumb",shortphrase:"scripts.shortphrase",mediumphrase:"scripts.mediumphrase",longphrase:"scripts.longphrase",trill:"scripts.trill",roll:"scripts.roll",irishroll:"scripts.roll",marcato:"scripts.umarcato",dmarcato:"scripts.dmarcato",umarcato:"scripts.umarcato",turn:"scripts.turn",uppermordent:"scripts.prall",pralltriller:"scripts.prall",mordent:"scripts.mordent",lowermordent:"scripts.mordent",downbow:"scripts.downbow",upbow:"scripts.upbow",fermata:"scripts.ufermata",invertedfermata:"scripts.dfermata",breath:",",coda:"scripts.coda",segno:"scripts.segno"},hasOne=!1,i=0;i<decoration.length;i++)switch(decoration[i]){case"0":case"1":case"2":case"3":case"4":case"5":case"D.C.":case"D.S.":textDecoration(decoration[i],positioning),hasOne=!0;break;case"fine":textDecoration("FINE",positioning),hasOne=!0;break;case"+":case"open":case"snap":case"wedge":case"thumb":case"shortphrase":case"mediumphrase":case"longphrase":case"trill":case"roll":case"irishroll":case"marcato":case"dmarcato":case"turn":case"uppermordent":case"pralltriller":case"mordent":case"lowermordent":case"downbow":case"upbow":case"fermata":case"breath":case"umarcato":case"coda":case"segno":symbolDecoration(symbolList[decoration[i]],positioning),hasOne=!0;break;case"invertedfermata":symbolDecoration(symbolList[decoration[i]],"below"),hasOne=!0;break;case"mark":abselem.klass="mark"}return hasOne};ABCJS.write.Decoration.prototype.dynamicDecoration=function(voice,decoration,abselem,positioning){for(var diminuendo,crescendo,i=0;i<decoration.length;i++)switch(decoration[i]){case"diminuendo(":this.startDiminuendoX=abselem,diminuendo=void 0;break;case"diminuendo)":diminuendo={start:this.startDiminuendoX,stop:abselem},this.startDiminuendoX=void 0;break;case"crescendo(":this.startCrescendoX=abselem,crescendo=void 0;break;case"crescendo)":crescendo={start:this.startCrescendoX,stop:abselem},this.startCrescendoX=void 0}diminuendo&&voice.addOther(new ABCJS.write.CrescendoElem(diminuendo.start,diminuendo.stop,">",positioning)),crescendo&&voice.addOther(new ABCJS.write.CrescendoElem(crescendo.start,crescendo.stop,"<",positioning))},ABCJS.write.Decoration.prototype.createDecoration=function(voice,decoration,pitch,width,abselem,roomtaken,dir,minPitch,positioning,hasVocals){positioning||(positioning={ornamentPosition:"above",volumePosition:hasVocals?"above":"below",dynamicPosition:hasVocals?"above":"below"}),volumeDecoration(voice,decoration,abselem,positioning.volumePosition),this.dynamicDecoration(voice,decoration,abselem,positioning.dynamicPosition),compoundDecoration(decoration,pitch,width,abselem,dir);var yPos=closeDecoration(voice,decoration,pitch,width,abselem,roomtaken,dir,minPitch);yPos.above=Math.max(yPos.above,this.minTop);stackedDecoration(decoration,width,abselem,yPos,positioning.ornamentPosition,this.minTop,this.minBottom)}}(),window.ABCJS||(window.ABCJS={}),window.ABCJS.write||(window.ABCJS.write={}),ABCJS.write.DynamicDecoration=function(anchor,dec,position){this.anchor=anchor,this.dec=dec,"below"===position?this.volumeHeightBelow=5:this.volumeHeightAbove=5,this.pitch=void 0},ABCJS.write.DynamicDecoration.prototype.setUpperAndLowerElements=function(positionY){this.volumeHeightAbove?this.pitch=positionY.volumeHeightAbove:this.pitch=positionY.volumeHeightBelow},ABCJS.write.DynamicDecoration.prototype.draw=function(renderer,linestartx,lineendx){void 0===this.pitch&&window.console.error("Dynamic Element y-coordinate not set.");var scalex=1,scaley=1;renderer.printSymbol(this.anchor.x,this.pitch,this.dec,scalex,scaley,renderer.addClasses("decoration"))},window.ABCJS||(window.ABCJS={}),window.ABCJS.write||(window.ABCJS.write={}),ABCJS.write.EndingElem=function(text,anchor1,anchor2){this.text=text,this.anchor1=anchor1,this.anchor2=anchor2,this.endingHeightAbove=5,this.pitch=void 0},ABCJS.write.EndingElem.prototype.setUpperAndLowerElements=function(positionY){this.pitch=positionY.endingHeightAbove},ABCJS.write.EndingElem.prototype.draw=function(renderer,linestartx,lineendx){void 0===this.pitch&&window.console.error("Ending Element y-coordinate not set.");var pathString,y=renderer.calcY(this.pitch),height=20;this.anchor1&&(linestartx=this.anchor1.x+this.anchor1.w,pathString=ABCJS.write.sprintf("M %f %f L %f %f",linestartx,y,linestartx,y+height),renderer.printPath({path:pathString,stroke:"#000000",fill:"#000000",class:renderer.addClasses("ending")}),renderer.renderText(linestartx+5,renderer.calcY(this.pitch-.5),this.text,"repeatfont","ending","start")),this.anchor2&&(lineendx=this.anchor2.x,pathString=ABCJS.write.sprintf("M %f %f L %f %f",lineendx,y,lineendx,y+height),renderer.printPath({path:pathString,stroke:"#000000",fill:"#000000",class:renderer.addClasses("ending")})),pathString=ABCJS.write.sprintf("M %f %f L %f %f",linestartx,y,lineendx,y),renderer.printPath({path:pathString,stroke:"#000000",fill:"#000000",class:renderer.addClasses("ending")})},window.ABCJS||(window.ABCJS={}),window.ABCJS.write||(window.ABCJS.write={}),ABCJS.write.spacing=function(){},ABCJS.write.spacing.FONTEM=360,ABCJS.write.spacing.FONTSIZE=30,ABCJS.write.spacing.STEP=93*ABCJS.write.spacing.FONTSIZE/720,ABCJS.write.spacing.SPACE=10,ABCJS.write.spacing.TOPNOTE=15,ABCJS.write.spacing.STAVEHEIGHT=100,ABCJS.write.spacing.INDENT=50,ABCJS.write.debugPlacement=!1,ABCJS.write.EngraverController=function(paper,params){params=params||{},this.space=3*ABCJS.write.spacing.SPACE,this.scale=params.scale||void 0,params.staffwidth?(this.staffwidthScreen=params.staffwidth,this.staffwidthPrint=params.staffwidth):(this.staffwidthScreen=740,this.staffwidthPrint=680), this.editable=params.editable||!1,this.listeners=[],params.listener&&this.addSelectListener(params.listener),this.usingSvg=!(!window.SVGAngle&&!document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1")),this.usingSvg&&params.add_classes&&(Raphael._availableAttrs.class=""),Raphael._availableAttrs["text-decoration"]="",Raphael._availableAttrs["data-vertical"]="",this.renderer=new ABCJS.write.Renderer(paper,params.regression),this.renderer.setPaddingOverride(params),this.renderer.controller=this,this.reset()},ABCJS.write.EngraverController.prototype.reset=function(){this.selected=[],this.ingroup=!1,this.staffgroups=[],this.lastStaffGroupIndex=-1,this.engraver&&this.engraver.reset(),this.engraver=null,this.renderer.reset()},ABCJS.write.EngraverController.prototype.engraveABC=function(abctunes){void 0===abctunes[0]&&(abctunes=[abctunes]),this.reset();for(var i=0;i<abctunes.length;i++)this.engraveTune(abctunes[i],i);if(this.renderer.doRegression)return this.renderer.regressionLines.join("\n")},ABCJS.write.EngraverController.prototype.adjustNonScaledItems=function(scale){this.width/=scale,this.renderer.adjustNonScaledItems(scale)},ABCJS.write.EngraverController.prototype.engraveTune=function(abctune,tuneNumber){this.renderer.lineNumber=null,abctune.formatting.tripletfont={face:"Times",size:11,weight:"normal",style:"italic",decoration:"none"},this.renderer.abctune=abctune,this.renderer.setVerticalSpace(abctune.formatting),this.renderer.measureNumber=null,this.renderer.setPrintMode("print"===abctune.media);var scale=abctune.formatting.scale?abctune.formatting.scale:this.scale;void 0===scale&&(scale=this.renderer.isPrint?.75:1),this.renderer.setPadding(abctune),this.engraver=new ABCJS.write.AbstractEngraver(abctune.formatting.bagpipes,this.renderer,tuneNumber),this.engraver.setStemHeight(this.renderer.spacing.stemHeight),this.renderer.engraver=this.engraver,abctune.formatting.staffwidth?this.width=1.33*abctune.formatting.staffwidth:this.width=this.renderer.isPrint?this.staffwidthPrint:this.staffwidthScreen,this.adjustNonScaledItems(scale);var i,abcLine,hasPrintedTempo=!1;for(i=0;i<abctune.lines.length;i++)abcLine=abctune.lines[i],abcLine.staff&&(abcLine.staffGroup=this.engraver.createABCLine(abcLine.staff,hasPrintedTempo?null:abctune.metaText.tempo),hasPrintedTempo=!0);var maxWidth=this.width;for(i=0;i<abctune.lines.length;i++)abcLine=abctune.lines[i],abcLine.staff&&(this.setXSpacing(abcLine.staffGroup,abctune.formatting,i===abctune.lines.length-1),abcLine.staffGroup.w>maxWidth&&(maxWidth=abcLine.staffGroup.w));for(i=0;i<abctune.lines.length;i++)if(abcLine=abctune.lines[i],abcLine.staffGroup&&abcLine.staffGroup.voices){for(var j=0;j<abcLine.staffGroup.voices.length;j++)abcLine.staffGroup.voices[j].layoutBeams();abcLine.staffGroup.setUpperAndLowerElements(this.renderer)}for(i=0;i<abctune.lines.length;i++)abcLine=abctune.lines[i],abcLine.staffGroup&&(abcLine.staffGroup.height=abcLine.staffGroup.calcHeight());this.renderer.topMargin(abctune),this.renderer.engraveTopText(this.width,abctune),this.renderer.addMusicPadding(),this.staffgroups=[],this.lastStaffGroupIndex=-1;for(var line=0;line<abctune.lines.length;line++)this.renderer.lineNumber=line,abcLine=abctune.lines[line],abcLine.staff?this.engraveStaffLine(abcLine.staffGroup):abcLine.subtitle&&0!==line?this.renderer.outputSubtitle(this.width,abcLine.subtitle):void 0!==abcLine.text&&this.renderer.outputFreeText(abcLine.text);this.renderer.moveY(24),this.renderer.engraveExtraText(this.width,abctune),this.renderer.setPaperSize(maxWidth,scale)},ABCJS.write.EngraverController.prototype.setXSpacing=function(staffGroup,formatting,isLastLine){for(var newspace=this.space,it=0;it<3;it++){staffGroup.layout(newspace,this.renderer,!1);var stretchLast=!!formatting.stretchlast&&formatting.stretchlast;if(newspace=calcHorizontalSpacing(isLastLine,stretchLast,this.width+this.renderer.padding.left,staffGroup.w,newspace,staffGroup.spacingunits,staffGroup.minspace),null===newspace)break}centerWholeRests(staffGroup.voices)},ABCJS.write.EngraverController.prototype.engraveStaffLine=function(staffGroup){this.lastStaffGroupIndex>-1&&this.renderer.addStaffPadding(this.staffgroups[this.lastStaffGroupIndex],staffGroup),this.renderer.voiceNumber=null,staffGroup.draw(this.renderer);var height=staffGroup.height*ABCJS.write.spacing.STEP;this.staffgroups[this.staffgroups.length]=staffGroup,this.lastStaffGroupIndex=this.staffgroups.length-1,this.renderer.y+=height},ABCJS.write.EngraverController.prototype.notifySelect=function(abselem,tuneNumber){this.clearSelection(),abselem.highlight&&(this.selected=[abselem],abselem.highlight());for(var abcelem=abselem.abcelem||{},i=0;i<this.listeners.length;i++)this.listeners[i].highlight&&this.listeners[i].highlight(abcelem,tuneNumber)},ABCJS.write.EngraverController.prototype.notifyChange=function(){for(var i=0;i<this.listeners.length;i++)this.listeners[i].modelChanged&&this.listeners[i].modelChanged()},ABCJS.write.EngraverController.prototype.clearSelection=function(){for(var i=0;i<this.selected.length;i++)this.selected[i].unhighlight();this.selected=[]},ABCJS.write.EngraverController.prototype.addSelectListener=function(listener){this.listeners[this.listeners.length]=listener},ABCJS.write.EngraverController.prototype.rangeHighlight=function(start,end){this.clearSelection();for(var line=0;line<this.staffgroups.length;line++)for(var voices=this.staffgroups[line].voices,voice=0;voice<voices.length;voice++)for(var elems=voices[voice].children,elem=0;elem<elems.length;elem++){var elStart=elems[elem].abcelem.startChar,elEnd=elems[elem].abcelem.endChar;(end>elStart&&start<elEnd||end===start&&end===elEnd)&&(this.selected[this.selected.length]=elems[elem],elems[elem].highlight())}},window.ABCJS||(window.ABCJS={}),window.ABCJS.write||(window.ABCJS.write={}),ABCJS.write.Glyphs=function(){"use strict";var glyphs={0:{d:[["M",4.83,-14.97],["c",.33,-.03,1.11,0,1.47,.06],["c",1.68,.36,2.97,1.59,3.78,3.6],["c",1.2,2.97,.81,6.96,-.9,9.27],["c",-.78,1.08,-1.71,1.71,-2.91,1.95],["c",-.45,.09,-1.32,.09,-1.77,0],["c",-.81,-.18,-1.47,-.51,-2.07,-1.02],["c",-2.34,-2.07,-3.15,-6.72,-1.74,-10.2],["c",.87,-2.16,2.28,-3.42,4.14,-3.66],["z"],["m",1.11,.87],["c",-.21,-.06,-.69,-.09,-.87,-.06],["c",-.54,.12,-.87,.42,-1.17,.99],["c",-.36,.66,-.51,1.56,-.6,3],["c",-.03,.75,-.03,4.59,0,5.31],["c",.09,1.5,.27,2.4,.6,3.06],["c",.24,.48,.57,.78,.96,.9],["c",.27,.09,.78,.09,1.05,0],["c",.39,-.12,.72,-.42,.96,-.9],["c",.33,-.66,.51,-1.56,.6,-3.06],["c",.03,-.72,.03,-4.56,0,-5.31],["c",-.09,-1.47,-.27,-2.37,-.6,-3.03],["c",-.24,-.48,-.54,-.78,-.93,-.9],["z"]],w:10.78,h:14.959},1:{d:[["M",3.3,-15.06],["c",.06,-.06,.21,-.03,.66,.15],["c",.81,.39,1.08,.39,1.83,.03],["c",.21,-.09,.39,-.15,.42,-.15],["c",.12,0,.21,.09,.27,.21],["c",.06,.12,.06,.33,.06,5.94],["c",0,3.93,0,5.85,.03,6.03],["c",.06,.36,.15,.69,.27,.96],["c",.36,.75,.93,1.17,1.68,1.26],["c",.3,.03,.39,.09,.39,.3],["c",0,.15,-.03,.18,-.09,.24],["c",-.06,.06,-.09,.06,-.48,.06],["c",-.42,0,-.69,-.03,-2.1,-.24],["c",-.9,-.15,-1.77,-.15,-2.67,0],["c",-1.41,.21,-1.68,.24,-2.1,.24],["c",-.39,0,-.42,0,-.48,-.06],["c",-.06,-.06,-.06,-.09,-.06,-.24],["c",0,-.21,.06,-.27,.36,-.3],["c",.75,-.09,1.32,-.51,1.68,-1.26],["c",.12,-.27,.21,-.6,.27,-.96],["c",.03,-.18,.03,-1.59,.03,-4.29],["c",0,-3.87,0,-4.05,-.06,-4.14],["c",-.09,-.15,-.18,-.24,-.39,-.24],["c",-.12,0,-.15,.03,-.21,.06],["c",-.03,.06,-.45,.99,-.96,2.13],["c",-.48,1.14,-.9,2.1,-.93,2.16],["c",-.06,.15,-.21,.24,-.33,.24],["c",-.24,0,-.42,-.18,-.42,-.39],["c",0,-.06,3.27,-7.62,3.33,-7.74],["z"]],w:8.94,h:15.058},2:{d:[["M",4.23,-14.97],["c",.57,-.06,1.68,0,2.34,.18],["c",.69,.18,1.5,.54,2.01,.9],["c",1.35,.96,1.95,2.25,1.77,3.81],["c",-.15,1.35,-.66,2.34,-1.68,3.15],["c",-.6,.48,-1.44,.93,-3.12,1.65],["c",-1.32,.57,-1.8,.81,-2.37,1.14],["c",-.57,.33,-.57,.33,-.24,.27],["c",.39,-.09,1.26,-.09,1.68,0],["c",.72,.15,1.41,.45,2.1,.9],["c",.99,.63,1.86,.87,2.55,.75],["c",.24,-.06,.42,-.15,.57,-.3],["c",.12,-.09,.3,-.42,.3,-.51],["c",0,-.09,.12,-.21,.24,-.24],["c",.18,-.03,.39,.12,.39,.3],["c",0,.12,-.15,.57,-.3,.87],["c",-.54,1.02,-1.56,1.74,-2.79,2.01],["c",-.42,.09,-1.23,.09,-1.62,.03],["c",-.81,-.18,-1.32,-.45,-2.01,-1.11],["c",-.45,-.45,-.63,-.57,-.96,-.69],["c",-.84,-.27,-1.89,.12,-2.25,.9],["c",-.12,.21,-.21,.54,-.21,.72],["c",0,.12,-.12,.21,-.27,.24],["c",-.15,0,-.27,-.03,-.33,-.15],["c",-.09,-.21,.09,-1.08,.33,-1.71],["c",.24,-.66,.66,-1.26,1.29,-1.89],["c",.45,-.45,.9,-.81,1.92,-1.56],["c",1.29,-.93,1.89,-1.44,2.34,-1.98],["c",.87,-1.05,1.26,-2.19,1.2,-3.63],["c",-.06,-1.29,-.39,-2.31,-.96,-2.91],["c",-.36,-.33,-.72,-.51,-1.17,-.54],["c",-.84,-.03,-1.53,.42,-1.59,1.05],["c",-.03,.33,.12,.6,.57,1.14],["c",.45,.54,.54,.87,.42,1.41],["c",-.15,.63,-.54,1.11,-1.08,1.38],["c",-.63,.33,-1.2,.33,-1.83,0],["c",-.24,-.12,-.33,-.18,-.54,-.39],["c",-.18,-.18,-.27,-.3,-.36,-.51],["c",-.24,-.45,-.27,-.84,-.21,-1.38],["c",.12,-.75,.45,-1.41,1.02,-1.98],["c",.72,-.72,1.74,-1.17,2.85,-1.32],["z"]],w:10.764,h:14.97},3:{d:[["M",3.78,-14.97],["c",.3,-.03,1.41,0,1.83,.06],["c",2.22,.3,3.51,1.32,3.72,2.91],["c",.03,.33,.03,1.26,-.03,1.65],["c",-.12,.84,-.48,1.47,-1.05,1.77],["c",-.27,.15,-.36,.24,-.45,.39],["c",-.09,.21,-.09,.36,0,.57],["c",.09,.15,.18,.24,.51,.39],["c",.75,.42,1.23,1.14,1.41,2.13],["c",.06,.42,.06,1.35,0,1.71],["c",-.18,.81,-.48,1.38,-1.02,1.95],["c",-.75,.72,-1.8,1.2,-3.18,1.38],["c",-.42,.06,-1.56,.06,-1.95,0],["c",-1.89,-.33,-3.18,-1.29,-3.51,-2.64],["c",-.03,-.12,-.03,-.33,-.03,-.6],["c",0,-.36,0,-.42,.06,-.63],["c",.12,-.3,.27,-.51,.51,-.75],["c",.24,-.24,.45,-.39,.75,-.51],["c",.21,-.06,.27,-.06,.6,-.06],["c",.33,0,.39,0,.6,.06],["c",.3,.12,.51,.27,.75,.51],["c",.36,.33,.57,.75,.6,1.2],["c",0,.21,0,.27,-.06,.42],["c",-.09,.18,-.12,.24,-.54,.54],["c",-.51,.36,-.63,.54,-.6,.87],["c",.06,.54,.54,.9,1.38,.99],["c",.36,.06,.72,.03,.96,-.06],["c",.81,-.27,1.29,-1.23,1.44,-2.79],["c",.03,-.45,.03,-1.95,-.03,-2.37],["c",-.09,-.75,-.33,-1.23,-.75,-1.44],["c",-.33,-.18,-.45,-.18,-1.98,-.18],["c",-1.35,0,-1.41,0,-1.5,-.06],["c",-.18,-.12,-.24,-.39,-.12,-.6],["c",.12,-.15,.15,-.15,1.68,-.15],["c",1.5,0,1.62,0,1.89,-.15],["c",.18,-.09,.42,-.36,.54,-.57],["c",.18,-.42,.27,-.9,.3,-1.95],["c",.03,-1.2,-.06,-1.8,-.36,-2.37],["c",-.24,-.48,-.63,-.81,-1.14,-.96],["c",-.3,-.06,-1.08,-.06,-1.38,.03],["c",-.6,.15,-.9,.42,-.96,.84],["c",-.03,.3,.06,.45,.63,.84],["c",.33,.24,.42,.39,.45,.63],["c",.03,.72,-.57,1.5,-1.32,1.65],["c",-1.05,.27,-2.1,-.57,-2.1,-1.65],["c",0,-.45,.15,-.96,.39,-1.38],["c",.12,-.21,.54,-.63,.81,-.81],["c",.57,-.42,1.38,-.69,2.25,-.81],["z"]],w:9.735,h:14.967},4:{d:[["M",8.64,-14.94],["c",.27,-.09,.42,-.12,.54,-.03],["c",.09,.06,.15,.21,.15,.3],["c",-.03,.06,-1.92,2.31,-4.23,5.04],["c",-2.31,2.73,-4.23,4.98,-4.26,5.01],["c",-.03,.06,.12,.06,2.55,.06],["l",2.61,0],["l",0,-2.37],["c",0,-2.19,.03,-2.37,.06,-2.46],["c",.03,-.06,.21,-.18,.57,-.42],["c",1.08,-.72,1.38,-1.08,1.86,-2.16],["c",.12,-.3,.24,-.54,.27,-.57],["c",.12,-.12,.39,-.06,.45,.12],["c",.06,.09,.06,.57,.06,3.96],["l",0,3.9],["l",1.08,0],["c",1.05,0,1.11,0,1.2,.06],["c",.24,.15,.24,.54,0,.69],["c",-.09,.06,-.15,.06,-1.2,.06],["l",-1.08,0],["l",0,.33],["c",0,.57,.09,1.11,.3,1.53],["c",.36,.75,.93,1.17,1.68,1.26],["c",.3,.03,.39,.09,.39,.3],["c",0,.15,-.03,.18,-.09,.24],["c",-.06,.06,-.09,.06,-.48,.06],["c",-.42,0,-.69,-.03,-2.1,-.24],["c",-.9,-.15,-1.77,-.15,-2.67,0],["c",-1.41,.21,-1.68,.24,-2.1,.24],["c",-.39,0,-.42,0,-.48,-.06],["c",-.06,-.06,-.06,-.09,-.06,-.24],["c",0,-.21,.06,-.27,.36,-.3],["c",.75,-.09,1.32,-.51,1.68,-1.26],["c",.21,-.42,.3,-.96,.3,-1.53],["l",0,-.33],["l",-2.7,0],["c",-2.91,0,-2.85,0,-3.09,-.15],["c",-.18,-.12,-.3,-.39,-.27,-.54],["c",.03,-.06,.18,-.24,.33,-.45],["c",.75,-.9,1.59,-2.07,2.13,-3.03],["c",.33,-.54,.84,-1.62,1.05,-2.16],["c",.57,-1.41,.84,-2.64,.9,-4.05],["c",.03,-.63,.06,-.72,.24,-.81],["l",.12,-.06],["l",.45,.12],["c",.66,.18,1.02,.24,1.47,.27],["c",.6,.03,1.23,-.09,2.01,-.33],["z"]],w:11.795,h:14.994},5:{d:[["M",1.02,-14.94],["c",.12,-.09,.03,-.09,1.08,.06],["c",2.49,.36,4.35,.36,6.96,-.06],["c",.57,-.09,.66,-.06,.81,.06],["c",.15,.18,.12,.24,-.15,.51],["c",-1.29,1.26,-3.24,2.04,-5.58,2.31],["c",-.6,.09,-1.2,.12,-1.71,.12],["c",-.39,0,-.45,0,-.57,.06],["c",-.09,.06,-.15,.12,-.21,.21],["l",-.06,.12],["l",0,1.65],["l",0,1.65],["l",.21,-.21],["c",.66,-.57,1.41,-.96,2.19,-1.14],["c",.33,-.06,1.41,-.06,1.95,0],["c",2.61,.36,4.02,1.74,4.26,4.14],["c",.03,.45,.03,1.08,-.03,1.44],["c",-.18,1.02,-.78,2.01,-1.59,2.7],["c",-.72,.57,-1.62,1.02,-2.49,1.2],["c",-1.38,.27,-3.03,.06,-4.2,-.54],["c",-1.08,-.54,-1.71,-1.32,-1.86,-2.28],["c",-.09,-.69,.09,-1.29,.57,-1.74],["c",.24,-.24,.45,-.39,.75,-.51],["c",.21,-.06,.27,-.06,.6,-.06],["c",.33,0,.39,0,.6,.06],["c",.3,.12,.51,.27,.75,.51],["c",.36,.33,.57,.75,.6,1.2],["c",0,.21,0,.27,-.06,.42],["c",-.09,.18,-.12,.24,-.54,.54],["c",-.18,.12,-.36,.3,-.42,.33],["c",-.36,.42,-.18,.99,.36,1.26],["c",.51,.27,1.47,.36,2.01,.27],["c",.93,-.21,1.47,-1.17,1.65,-2.91],["c",.06,-.45,.06,-1.89,0,-2.31],["c",-.15,-1.2,-.51,-2.1,-1.05,-2.55],["c",-.21,-.18,-.54,-.36,-.81,-.39],["c",-.3,-.06,-.84,-.03,-1.26,.06],["c",-.93,.18,-1.65,.6,-2.16,1.2],["c",-.15,.21,-.27,.3,-.39,.3],["c",-.15,0,-.3,-.09,-.36,-.18],["c",-.06,-.09,-.06,-.15,-.06,-3.66],["c",0,-3.39,0,-3.57,.06,-3.66],["c",.03,-.06,.09,-.15,.15,-.18],["z"]],w:10.212,h:14.997},6:{d:[["M",4.98,-14.97],["c",.36,-.03,1.2,0,1.59,.06],["c",.9,.15,1.68,.51,2.25,1.05],["c",.57,.51,.87,1.23,.84,1.98],["c",-.03,.51,-.21,.9,-.6,1.26],["c",-.24,.24,-.45,.39,-.75,.51],["c",-.21,.06,-.27,.06,-.6,.06],["c",-.33,0,-.39,0,-.6,-.06],["c",-.3,-.12,-.51,-.27,-.75,-.51],["c",-.39,-.36,-.57,-.78,-.57,-1.26],["c",0,-.27,0,-.3,.09,-.42],["c",.03,-.09,.18,-.21,.3,-.3],["c",.12,-.09,.3,-.21,.39,-.27],["c",.09,-.06,.21,-.18,.27,-.24],["c",.06,-.12,.09,-.15,.09,-.33],["c",0,-.18,-.03,-.24,-.09,-.36],["c",-.24,-.39,-.75,-.6,-1.38,-.57],["c",-.54,.03,-.9,.18,-1.23,.48],["c",-.81,.72,-1.08,2.16,-.96,5.37],["l",0,.63],["l",.3,-.12],["c",.78,-.27,1.29,-.33,2.1,-.27],["c",1.47,.12,2.49,.54,3.27,1.29],["c",.48,.51,.81,1.11,.96,1.89],["c",.06,.27,.06,.42,.06,.93],["c",0,.54,0,.69,-.06,.96],["c",-.15,.78,-.48,1.38,-.96,1.89],["c",-.54,.51,-1.17,.87,-1.98,1.08],["c",-1.14,.3,-2.4,.33,-3.24,.03],["c",-1.5,-.48,-2.64,-1.89,-3.27,-4.02],["c",-.36,-1.23,-.51,-2.82,-.42,-4.08],["c",.3,-3.66,2.28,-6.3,4.95,-6.66],["z"],["m",.66,7.41],["c",-.27,-.09,-.81,-.12,-1.08,-.06],["c",-.72,.18,-1.08,.69,-1.23,1.71],["c",-.06,.54,-.06,3,0,3.54],["c",.18,1.26,.72,1.77,1.8,1.74],["c",.39,-.03,.63,-.09,.9,-.27],["c",.66,-.42,.9,-1.32,.9,-3.24],["c",0,-2.22,-.36,-3.12,-1.29,-3.42],["z"]],w:9.956,h:14.982},7:{d:[["M",.21,-14.97],["c",.21,-.06,.45,0,.54,.15],["c",.06,.09,.06,.15,.06,.39],["c",0,.24,0,.33,.06,.42],["c",.06,.12,.21,.24,.27,.24],["c",.03,0,.12,-.12,.24,-.21],["c",.96,-1.2,2.58,-1.35,3.99,-.42],["c",.15,.12,.42,.3,.54,.45],["c",.48,.39,.81,.57,1.29,.6],["c",.69,.03,1.5,-.3,2.13,-.87],["c",.09,-.09,.27,-.3,.39,-.45],["c",.12,-.15,.24,-.27,.3,-.3],["c",.18,-.06,.39,.03,.51,.21],["c",.06,.18,.06,.24,-.27,.72],["c",-.18,.24,-.54,.78,-.78,1.17],["c",-2.37,3.54,-3.54,6.27,-3.87,9],["c",-.03,.33,-.03,.66,-.03,1.26],["c",0,.9,0,1.08,.15,1.89],["c",.06,.45,.06,.48,.03,.6],["c",-.06,.09,-.21,.21,-.3,.21],["c",-.03,0,-.27,-.06,-.54,-.15],["c",-.84,-.27,-1.11,-.3,-1.65,-.3],["c",-.57,0,-.84,.03,-1.56,.27],["c",-.6,.18,-.69,.21,-.81,.15],["c",-.12,-.06,-.21,-.18,-.21,-.3],["c",0,-.15,.6,-1.44,1.2,-2.61],["c",1.14,-2.22,2.73,-4.68,5.1,-8.01],["c",.21,-.27,.36,-.48,.33,-.48],["c",0,0,-.12,.06,-.27,.12],["c",-.54,.3,-.99,.39,-1.56,.39],["c",-.75,.03,-1.2,-.18,-1.83,-.75],["c",-.99,-.9,-1.83,-1.17,-2.31,-.72],["c",-.18,.15,-.36,.51,-.45,.84],["c",-.06,.24,-.06,.33,-.09,1.98],["c",0,1.62,-.03,1.74,-.06,1.8],["c",-.15,.24,-.54,.24,-.69,0],["c",-.06,-.09,-.06,-.15,-.06,-3.57],["c",0,-3.42,0,-3.48,.06,-3.57],["c",.03,-.06,.09,-.12,.15,-.15],["z"]],w:10.561,h:15.093},8:{d:[["M",4.98,-14.97],["c",.33,-.03,1.02,-.03,1.32,0],["c",1.32,.12,2.49,.6,3.21,1.32],["c",.39,.39,.66,.81,.78,1.29],["c",.09,.36,.09,1.08,0,1.44],["c",-.21,.84,-.66,1.59,-1.59,2.55],["l",-.3,.3],["l",.27,.18],["c",1.47,.93,2.31,2.31,2.25,3.75],["c",-.03,.75,-.24,1.35,-.63,1.95],["c",-.45,.66,-1.02,1.14,-1.83,1.53],["c",-1.8,.87,-4.2,.87,-6,.03],["c",-1.62,-.78,-2.52,-2.16,-2.46,-3.66],["c",.06,-.99,.54,-1.77,1.8,-2.97],["c",.54,-.51,.54,-.54,.48,-.57],["c",-.39,-.27,-.96,-.78,-1.2,-1.14],["c",-.75,-1.11,-.87,-2.4,-.3,-3.6],["c",.69,-1.35,2.25,-2.25,4.2,-2.4],["z"],["m",1.53,.69],["c",-.42,-.09,-1.11,-.12,-1.38,-.06],["c",-.3,.06,-.6,.18,-.81,.3],["c",-.21,.12,-.6,.51,-.72,.72],["c",-.51,.87,-.42,1.89,.21,2.52],["c",.21,.21,.36,.3,1.95,1.23],["c",.96,.54,1.74,.99,1.77,1.02],["c",.09,0,.63,-.6,.99,-1.11],["c",.21,-.36,.48,-.87,.57,-1.23],["c",.06,-.24,.06,-.36,.06,-.72],["c",0,-.45,-.03,-.66,-.15,-.99],["c",-.39,-.81,-1.29,-1.44,-2.49,-1.68],["z"],["m",-1.44,8.07],["l",-1.89,-1.08],["c",-.03,0,-.18,.15,-.39,.33],["c",-1.2,1.08,-1.65,1.95,-1.59,3],["c",.09,1.59,1.35,2.85,3.21,3.24],["c",.33,.06,.45,.06,.93,.06],["c",.63,0,.81,-.03,1.29,-.27],["c",.9,-.42,1.47,-1.41,1.41,-2.4],["c",-.06,-.66,-.39,-1.29,-.9,-1.65],["c",-.12,-.09,-1.05,-.63,-2.07,-1.23],["z"]],w:10.926,h:14.989},9:{d:[["M",4.23,-14.97],["c",.42,-.03,1.29,0,1.62,.06],["c",.51,.12,.93,.3,1.38,.57],["c",1.53,1.02,2.52,3.24,2.73,5.94],["c",.18,2.55,-.48,4.98,-1.83,6.57],["c",-1.05,1.26,-2.4,1.89,-3.93,1.83],["c",-1.23,-.06,-2.31,-.45,-3.03,-1.14],["c",-.57,-.51,-.87,-1.23,-.84,-1.98],["c",.03,-.51,.21,-.9,.6,-1.26],["c",.24,-.24,.45,-.39,.75,-.51],["c",.21,-.06,.27,-.06,.6,-.06],["c",.33,0,.39,0,.6,.06],["c",.3,.12,.51,.27,.75,.51],["c",.39,.36,.57,.78,.57,1.26],["c",0,.27,0,.3,-.09,.42],["c",-.03,.09,-.18,.21,-.3,.3],["c",-.12,.09,-.3,.21,-.39,.27],["c",-.09,.06,-.21,.18,-.27,.24],["c",-.06,.12,-.06,.15,-.06,.33],["c",0,.18,0,.24,.06,.36],["c",.24,.39,.75,.6,1.38,.57],["c",.54,-.03,.9,-.18,1.23,-.48],["c",.81,-.72,1.08,-2.16,.96,-5.37],["l",0,-.63],["l",-.3,.12],["c",-.78,.27,-1.29,.33,-2.1,.27],["c",-1.47,-.12,-2.49,-.54,-3.27,-1.29],["c",-.48,-.51,-.81,-1.11,-.96,-1.89],["c",-.06,-.27,-.06,-.42,-.06,-.96],["c",0,-.51,0,-.66,.06,-.93],["c",.15,-.78,.48,-1.38,.96,-1.89],["c",.15,-.12,.33,-.27,.42,-.36],["c",.69,-.51,1.62,-.81,2.76,-.93],["z"],["m",1.17,.66],["c",-.21,-.06,-.57,-.06,-.81,-.03],["c",-.78,.12,-1.26,.69,-1.41,1.74],["c",-.12,.63,-.15,1.95,-.09,2.79],["c",.12,1.71,.63,2.4,1.77,2.46],["c",1.08,.03,1.62,-.48,1.8,-1.74],["c",.06,-.54,.06,-3,0,-3.54],["c",-.15,-1.05,-.51,-1.53,-1.26,-1.68],["z"]],w:9.959,h:14.986},"rests.whole":{d:[["M",.06,.03],["l",.09,-.06],["l",5.46,0],["l",5.49,0],["l",.09,.06],["l",.06,.09],["l",0,2.19],["l",0,2.19],["l",-.06,.09],["l",-.09,.06],["l",-5.49,0],["l",-5.46,0],["l",-.09,-.06],["l",-.06,-.09],["l",0,-2.19],["l",0,-2.19],["z"]],w:11.25,h:4.68},"rests.half":{d:[["M",.06,-4.62],["l",.09,-.06],["l",5.46,0],["l",5.49,0],["l",.09,.06],["l",.06,.09],["l",0,2.19],["l",0,2.19],["l",-.06,.09],["l",-.09,.06],["l",-5.49,0],["l",-5.46,0],["l",-.09,-.06],["l",-.06,-.09],["l",0,-2.19],["l",0,-2.19],["z"]],w:11.25,h:4.68},"rests.quarter":{d:[["M",1.89,-11.82],["c",.12,-.06,.24,-.06,.36,-.03],["c",.09,.06,4.74,5.58,4.86,5.82],["c",.21,.39,.15,.78,-.15,1.26],["c",-.24,.33,-.72,.81,-1.62,1.56],["c",-.45,.36,-.87,.75,-.96,.84],["c",-.93,.99,-1.14,2.49,-.6,3.63],["c",.18,.39,.27,.48,1.32,1.68],["c",1.92,2.25,1.83,2.16,1.83,2.34],["c",0,.18,-.18,.36,-.36,.39],["c",-.15,0,-.27,-.06,-.48,-.27],["c",-.75,-.75,-2.46,-1.29,-3.39,-1.08],["c",-.45,.09,-.69,.27,-.9,.69],["c",-.12,.3,-.21,.66,-.24,1.14],["c",-.03,.66,.09,1.35,.3,2.01],["c",.15,.42,.24,.66,.45,.96],["c",.18,.24,.18,.33,.03,.42],["c",-.12,.06,-.18,.03,-.45,-.3],["c",-1.08,-1.38,-2.07,-3.36,-2.4,-4.83],["c",-.27,-1.05,-.15,-1.77,.27,-2.07],["c",.21,-.12,.42,-.15,.87,-.15],["c",.87,.06,2.1,.39,3.3,.9],["l",.39,.18],["l",-1.65,-1.95],["c",-2.52,-2.97,-2.61,-3.09,-2.7,-3.27],["c",-.09,-.24,-.12,-.48,-.03,-.75],["c",.15,-.48,.57,-.96,1.83,-2.01],["c",.45,-.36,.84,-.72,.93,-.78],["c",.69,-.75,1.02,-1.8,.9,-2.79],["c",-.06,-.33,-.21,-.84,-.39,-1.11],["c",-.09,-.15,-.45,-.6,-.81,-1.05],["c",-.36,-.42,-.69,-.81,-.72,-.87],["c",-.09,-.18,0,-.42,.21,-.51],["z"]],w:7.888,h:21.435},"rests.8th":{d:[["M",1.68,-6.12],["c",.66,-.09,1.23,.09,1.68,.51],["c",.27,.3,.39,.54,.57,1.26],["c",.09,.33,.18,.66,.21,.72],["c",.12,.27,.33,.45,.6,.48],["c",.12,0,.18,0,.33,-.09],["c",.39,-.18,1.32,-1.29,1.68,-1.98],["c",.09,-.21,.24,-.3,.39,-.3],["c",.12,0,.27,.09,.33,.18],["c",.03,.06,-.27,1.11,-1.86,6.42],["c",-1.02,3.48,-1.89,6.39,-1.92,6.42],["c",0,.03,-.12,.12,-.24,.15],["c",-.18,.09,-.21,.09,-.45,.09],["c",-.24,0,-.3,0,-.48,-.06],["c",-.09,-.06,-.21,-.12,-.21,-.15],["c",-.06,-.03,.15,-.57,1.68,-4.92],["c",.96,-2.67,1.74,-4.89,1.71,-4.89],["l",-.51,.15],["c",-1.08,.36,-1.74,.48,-2.55,.48],["c",-.66,0,-.84,-.03,-1.32,-.27],["c",-1.32,-.63,-1.77,-2.16,-1.02,-3.3],["c",.33,-.45,.84,-.81,1.38,-.9],["z"]],w:7.534,h:13.883},"rests.16th":{d:[["M",3.33,-6.12],["c",.66,-.09,1.23,.09,1.68,.51],["c",.27,.3,.39,.54,.57,1.26],["c",.09,.33,.18,.66,.21,.72],["c",.15,.39,.57,.57,.87,.42],["c",.39,-.18,1.2,-1.23,1.62,-2.07],["c",.06,-.15,.24,-.24,.36,-.24],["c",.12,0,.27,.09,.33,.18],["c",.03,.06,-.45,1.86,-2.67,10.17],["c",-1.5,5.55,-2.73,10.14,-2.76,10.17],["c",-.03,.03,-.12,.12,-.24,.15],["c",-.18,.09,-.21,.09,-.45,.09],["c",-.24,0,-.3,0,-.48,-.06],["c",-.09,-.06,-.21,-.12,-.21,-.15],["c",-.06,-.03,.12,-.57,1.44,-4.92],["c",.81,-2.67,1.47,-4.86,1.47,-4.89],["c",-.03,0,-.27,.06,-.54,.15],["c",-1.08,.36,-1.77,.48,-2.58,.48],["c",-.66,0,-.84,-.03,-1.32,-.27],["c",-1.32,-.63,-1.77,-2.16,-1.02,-3.3],["c",.72,-1.05,2.22,-1.23,3.06,-.42],["c",.3,.33,.42,.6,.6,1.38],["c",.09,.45,.21,.78,.33,.9],["c",.09,.09,.27,.18,.45,.21],["c",.12,0,.18,0,.33,-.09],["c",.33,-.15,1.02,-.93,1.41,-1.59],["c",.12,-.21,.18,-.39,.39,-1.08],["c",.66,-2.1,1.17,-3.84,1.17,-3.87],["c",0,0,-.21,.06,-.42,.15],["c",-.51,.15,-1.2,.33,-1.68,.42],["c",-.33,.06,-.51,.06,-.96,.06],["c",-.66,0,-.84,-.03,-1.32,-.27],["c",-1.32,-.63,-1.77,-2.16,-1.02,-3.3],["c",.33,-.45,.84,-.81,1.38,-.9],["z"]],w:9.724,h:21.383},"rests.32nd":{d:[["M",4.23,-13.62],["c",.66,-.09,1.23,.09,1.68,.51],["c",.27,.3,.39,.54,.57,1.26],["c",.09,.33,.18,.66,.21,.72],["c",.12,.27,.33,.45,.6,.48],["c",.12,0,.18,0,.27,-.06],["c",.33,-.21,.99,-1.11,1.44,-1.98],["c",.09,-.24,.21,-.33,.39,-.33],["c",.12,0,.27,.09,.33,.18],["c",.03,.06,-.57,2.67,-3.21,13.89],["c",-1.8,7.62,-3.3,13.89,-3.3,13.92],["c",-.03,.06,-.12,.12,-.24,.18],["c",-.21,.09,-.24,.09,-.48,.09],["c",-.24,0,-.3,0,-.48,-.06],["c",-.09,-.06,-.21,-.12,-.21,-.15],["c",-.06,-.03,.09,-.57,1.23,-4.92],["c",.69,-2.67,1.26,-4.86,1.29,-4.89],["c",0,-.03,-.12,-.03,-.48,.12],["c",-1.17,.39,-2.22,.57,-3,.54],["c",-.42,-.03,-.75,-.12,-1.11,-.3],["c",-1.32,-.63,-1.77,-2.16,-1.02,-3.3],["c",.72,-1.05,2.22,-1.23,3.06,-.42],["c",.3,.33,.42,.6,.6,1.38],["c",.09,.45,.21,.78,.33,.9],["c",.12,.09,.3,.18,.48,.21],["c",.12,0,.18,0,.3,-.09],["c",.42,-.21,1.29,-1.29,1.56,-1.89],["c",.03,-.12,1.23,-4.59,1.23,-4.65],["c",0,-.03,-.18,.03,-.39,.12],["c",-.63,.18,-1.2,.36,-1.74,.45],["c",-.39,.06,-.54,.06,-1.02,.06],["c",-.66,0,-.84,-.03,-1.32,-.27],["c",-1.32,-.63,-1.77,-2.16,-1.02,-3.3],["c",.72,-1.05,2.22,-1.23,3.06,-.42],["c",.3,.33,.42,.6,.6,1.38],["c",.09,.45,.21,.78,.33,.9],["c",.18,.18,.51,.27,.72,.15],["c",.3,-.12,.69,-.57,1.08,-1.17],["c",.42,-.6,.39,-.51,1.05,-3.03],["c",.33,-1.26,.6,-2.31,.6,-2.34],["c",0,0,-.21,.03,-.45,.12],["c",-.57,.18,-1.14,.33,-1.62,.42],["c",-.33,.06,-.51,.06,-.96,.06],["c",-.66,0,-.84,-.03,-1.32,-.27],["c",-1.32,-.63,-1.77,-2.16,-1.02,-3.3],["c",.33,-.45,.84,-.81,1.38,-.9],["z"]],w:11.373,h:28.883},"rests.64th":{d:[["M",5.13,-13.62],["c",.66,-.09,1.23,.09,1.68,.51],["c",.27,.3,.39,.54,.57,1.26],["c",.15,.63,.21,.81,.33,.96],["c",.18,.21,.54,.3,.75,.18],["c",.24,-.12,.63,-.66,1.08,-1.56],["c",.33,-.66,.39,-.72,.6,-.72],["c",.12,0,.27,.09,.33,.18],["c",.03,.06,-.69,3.66,-3.54,17.64],["c",-1.95,9.66,-3.57,17.61,-3.57,17.64],["c",-.03,.06,-.12,.12,-.24,.18],["c",-.21,.09,-.24,.09,-.48,.09],["c",-.24,0,-.3,0,-.48,-.06],["c",-.09,-.06,-.21,-.12,-.21,-.15],["c",-.06,-.03,.06,-.57,1.05,-4.95],["c",.6,-2.7,1.08,-4.89,1.08,-4.92],["c",0,0,-.24,.06,-.51,.15],["c",-.66,.24,-1.2,.36,-1.77,.48],["c",-.42,.06,-.57,.06,-1.05,.06],["c",-.69,0,-.87,-.03,-1.35,-.27],["c",-1.32,-.63,-1.77,-2.16,-1.02,-3.3],["c",.72,-1.05,2.22,-1.23,3.06,-.42],["c",.3,.33,.42,.6,.6,1.38],["c",.09,.45,.21,.78,.33,.9],["c",.09,.09,.27,.18,.45,.21],["c",.21,.03,.39,-.09,.72,-.42],["c",.45,-.45,1.02,-1.26,1.17,-1.65],["c",.03,-.09,.27,-1.14,.54,-2.34],["c",.27,-1.2,.48,-2.19,.51,-2.22],["c",0,-.03,-.09,-.03,-.48,.12],["c",-1.17,.39,-2.22,.57,-3,.54],["c",-.42,-.03,-.75,-.12,-1.11,-.3],["c",-1.32,-.63,-1.77,-2.16,-1.02,-3.3],["c",.36,-.54,.96,-.87,1.65,-.93],["c",.54,-.03,1.02,.15,1.41,.54],["c",.27,.3,.39,.54,.57,1.26],["c",.09,.33,.18,.66,.21,.72],["c",.15,.39,.57,.57,.9,.42],["c",.36,-.18,1.2,-1.26,1.47,-1.89],["c",.03,-.09,.3,-1.2,.57,-2.43],["l",.51,-2.28],["l",-.54,.18],["c",-1.11,.36,-1.8,.48,-2.61,.48],["c",-.66,0,-.84,-.03,-1.32,-.27],["c",-1.32,-.63,-1.77,-2.16,-1.02,-3.3],["c",.36,-.54,.96,-.87,1.65,-.93],["c",.54,-.03,1.02,.15,1.41,.54],["c",.27,.3,.39,.54,.57,1.26],["c",.15,.63,.21,.81,.33,.96],["c",.21,.21,.54,.3,.75,.18],["c",.36,-.18,.93,-.93,1.29,-1.68],["c",.12,-.24,.18,-.48,.63,-2.55],["l",.51,-2.31],["c",0,-.03,-.18,.03,-.39,.12],["c",-1.14,.36,-2.1,.54,-2.82,.51],["c",-.42,-.03,-.75,-.12,-1.11,-.3],["c",-1.32,-.63,-1.77,-2.16,-1.02,-3.3],["c",.33,-.45,.84,-.81,1.38,-.9],["z"]],w:12.453,h:36.383},"rests.128th":{d:[["M",6.03,-21.12],["c",.66,-.09,1.23,.09,1.68,.51],["c",.27,.3,.39,.54,.57,1.26],["c",.09,.33,.18,.66,.21,.72],["c",.12,.27,.33,.45,.6,.48],["c",.21,0,.33,-.06,.54,-.36],["c",.15,-.21,.54,-.93,.78,-1.47],["c",.15,-.33,.18,-.39,.3,-.48],["c",.18,-.09,.45,0,.51,.15],["c",.03,.09,-7.11,42.75,-7.17,42.84],["c",-.03,.03,-.15,.09,-.24,.15],["c",-.18,.06,-.24,.06,-.45,.06],["c",-.24,0,-.3,0,-.48,-.06],["c",-.09,-.06,-.21,-.12,-.21,-.15],["c",-.06,-.03,.03,-.57,.84,-4.98],["c",.51,-2.7,.93,-4.92,.9,-4.92],["c",0,0,-.15,.06,-.36,.12],["c",-.78,.27,-1.62,.48,-2.31,.57],["c",-.15,.03,-.54,.03,-.81,.03],["c",-.66,0,-.84,-.03,-1.32,-.27],["c",-1.32,-.63,-1.77,-2.16,-1.02,-3.3],["c",.36,-.54,.96,-.87,1.65,-.93],["c",.54,-.03,1.02,.15,1.41,.54],["c",.27,.3,.39,.54,.57,1.26],["c",.09,.33,.18,.66,.21,.72],["c",.12,.27,.33,.45,.63,.48],["c",.12,0,.18,0,.3,-.09],["c",.42,-.21,1.14,-1.11,1.5,-1.83],["c",.12,-.27,.12,-.27,.54,-2.52],["c",.24,-1.23,.42,-2.25,.39,-2.25],["c",0,0,-.24,.06,-.51,.18],["c",-1.26,.39,-2.25,.57,-3.06,.54],["c",-.42,-.03,-.75,-.12,-1.11,-.3],["c",-1.32,-.63,-1.77,-2.16,-1.02,-3.3],["c",.36,-.54,.96,-.87,1.65,-.93],["c",.54,-.03,1.02,.15,1.41,.54],["c",.27,.3,.39,.54,.57,1.26],["c",.15,.63,.21,.81,.33,.96],["c",.18,.21,.51,.3,.75,.18],["c",.36,-.15,1.05,-.99,1.41,-1.77],["l",.15,-.3],["l",.42,-2.25],["c",.21,-1.26,.42,-2.28,.39,-2.28],["l",-.51,.15],["c",-1.11,.39,-1.89,.51,-2.7,.51],["c",-.66,0,-.84,-.03,-1.32,-.27],["c",-1.32,-.63,-1.77,-2.16,-1.02,-3.3],["c",.36,-.54,.96,-.87,1.65,-.93],["c",.54,-.03,1.02,.15,1.41,.54],["c",.27,.3,.39,.54,.57,1.26],["c",.15,.63,.21,.81,.33,.96],["c",.18,.18,.48,.27,.72,.21],["c",.33,-.12,1.14,-1.26,1.41,-1.95],["c",0,-.09,.21,-1.11,.45,-2.34],["c",.21,-1.2,.39,-2.22,.39,-2.28],["c",.03,-.03,0,-.03,-.45,.12],["c",-.57,.18,-1.2,.33,-1.71,.42],["c",-.3,.06,-.51,.06,-.93,.06],["c",-.66,0,-.84,-.03,-1.32,-.27],["c",-1.32,-.63,-1.77,-2.16,-1.02,-3.3],["c",.36,-.54,.96,-.87,1.65,-.93],["c",.54,-.03,1.02,.15,1.41,.54],["c",.27,.3,.39,.54,.57,1.26],["c",.09,.33,.18,.66,.21,.72],["c",.12,.27,.33,.45,.6,.48],["c",.18,0,.36,-.09,.57,-.33],["c",.33,-.36,.78,-1.14,.93,-1.56],["c",.03,-.12,.24,-1.2,.45,-2.4],["c",.24,-1.2,.42,-2.22,.42,-2.28],["c",.03,-.03,0,-.03,-.39,.09],["c",-1.05,.36,-1.8,.48,-2.58,.48],["c",-.63,0,-.84,-.03,-1.29,-.27],["c",-1.32,-.63,-1.77,-2.16,-1.02,-3.3],["c",.33,-.45,.84,-.81,1.38,-.9],["z"]],w:12.992,h:43.883},"accidentals.sharp":{d:[["M",5.73,-11.19],["c",.21,-.12,.54,-.03,.66,.24],["c",.06,.12,.06,.21,.06,2.31],["c",0,1.23,0,2.22,.03,2.22],["c",0,0,.27,-.12,.6,-.24],["c",.69,-.27,.78,-.3,.96,-.15],["c",.21,.15,.21,.18,.21,1.38],["c",0,1.02,0,1.11,-.06,1.2],["c",-.03,.06,-.09,.12,-.12,.15],["c",-.06,.03,-.42,.21,-.84,.36],["l",-.75,.33],["l",-.03,2.43],["c",0,1.32,0,2.43,.03,2.43],["c",0,0,.27,-.12,.6,-.24],["c",.69,-.27,.78,-.3,.96,-.15],["c",.21,.15,.21,.18,.21,1.38],["c",0,1.02,0,1.11,-.06,1.2],["c",-.03,.06,-.09,.12,-.12,.15],["c",-.06,.03,-.42,.21,-.84,.36],["l",-.75,.33],["l",-.03,2.52],["c",0,2.28,-.03,2.55,-.06,2.64],["c",-.21,.36,-.72,.36,-.93,0],["c",-.03,-.09,-.06,-.33,-.06,-2.43],["l",0,-2.31],["l",-1.29,.51],["l",-1.26,.51],["l",0,2.43],["c",0,2.58,0,2.52,-.15,2.67],["c",-.06,.09,-.27,.18,-.36,.18],["c",-.12,0,-.33,-.09,-.39,-.18],["c",-.15,-.15,-.15,-.09,-.15,-2.43],["c",0,-1.23,0,-2.22,-.03,-2.22],["c",0,0,-.27,.12,-.6,.24],["c",-.69,.27,-.78,.3,-.96,.15],["c",-.21,-.15,-.21,-.18,-.21,-1.38],["c",0,-1.02,0,-1.11,.06,-1.2],["c",.03,-.06,.09,-.12,.12,-.15],["c",.06,-.03,.42,-.21,.84,-.36],["l",.78,-.33],["l",0,-2.43],["c",0,-1.32,0,-2.43,-.03,-2.43],["c",0,0,-.27,.12,-.6,.24],["c",-.69,.27,-.78,.3,-.96,.15],["c",-.21,-.15,-.21,-.18,-.21,-1.38],["c",0,-1.02,0,-1.11,.06,-1.2],["c",.03,-.06,.09,-.12,.12,-.15],["c",.06,-.03,.42,-.21,.84,-.36],["l",.78,-.33],["l",0,-2.52],["c",0,-2.28,.03,-2.55,.06,-2.64],["c",.21,-.36,.72,-.36,.93,0],["c",.03,.09,.06,.33,.06,2.43],["l",.03,2.31],["l",1.26,-.51],["l",1.26,-.51],["l",0,-2.43],["c",0,-2.28,0,-2.43,.06,-2.55],["c",.06,-.12,.12,-.18,.27,-.24],["z"],["m",-.33,10.65],["l",0,-2.43],["l",-1.29,.51],["l",-1.26,.51],["l",0,2.46],["l",0,2.43],["l",.09,-.03],["c",.06,-.03,.63,-.27,1.29,-.51],["l",1.17,-.48],["l",0,-2.46],["z"]],w:8.25,h:22.462},"accidentals.halfsharp":{d:[["M",2.43,-10.05],["c",.21,-.12,.54,-.03,.66,.24],["c",.06,.12,.06,.21,.06,2.01],["c",0,1.05,0,1.89,.03,1.89],["l",.72,-.48],["c",.69,-.48,.69,-.51,.87,-.51],["c",.15,0,.18,.03,.27,.09],["c",.21,.15,.21,.18,.21,1.41],["c",0,1.11,-.03,1.14,-.09,1.23],["c",-.03,.03,-.48,.39,-1.02,.75],["l",-.99,.66],["l",0,2.37],["c",0,1.32,0,2.37,.03,2.37],["l",.72,-.48],["c",.69,-.48,.69,-.51,.87,-.51],["c",.15,0,.18,.03,.27,.09],["c",.21,.15,.21,.18,.21,1.41],["c",0,1.11,-.03,1.14,-.09,1.23],["c",-.03,.03,-.48,.39,-1.02,.75],["l",-.99,.66],["l",0,2.25],["c",0,1.95,0,2.28,-.06,2.37],["c",-.06,.12,-.12,.21,-.24,.27],["c",-.27,.12,-.54,.03,-.69,-.24],["c",-.06,-.12,-.06,-.21,-.06,-2.01],["c",0,-1.05,0,-1.89,-.03,-1.89],["l",-.72,.48],["c",-.69,.48,-.69,.48,-.87,.48],["c",-.15,0,-.18,0,-.27,-.06],["c",-.21,-.15,-.21,-.18,-.21,-1.41],["c",0,-1.11,.03,-1.14,.09,-1.23],["c",.03,-.03,.48,-.39,1.02,-.75],["l",.99,-.66],["l",0,-2.37],["c",0,-1.32,0,-2.37,-.03,-2.37],["l",-.72,.48],["c",-.69,.48,-.69,.48,-.87,.48],["c",-.15,0,-.18,0,-.27,-.06],["c",-.21,-.15,-.21,-.18,-.21,-1.41],["c",0,-1.11,.03,-1.14,.09,-1.23],["c",.03,-.03,.48,-.39,1.02,-.75],["l",.99,-.66],["l",0,-2.25],["c",0,-2.13,0,-2.28,.06,-2.4],["c",.06,-.12,.12,-.18,.27,-.24],["z"]],w:5.25,h:20.174},"accidentals.nat":{d:[["M",.21,-11.4],["c",.24,-.06,.78,0,.99,.15],["c",.03,.03,.03,.48,0,2.61],["c",-.03,1.44,-.03,2.61,-.03,2.61],["c",0,.03,.75,-.09,1.68,-.24],["c",.96,-.18,1.71,-.27,1.74,-.27],["c",.15,.03,.27,.15,.36,.3],["l",.06,.12],["l",.09,8.67],["c",.09,6.96,.12,8.67,.09,8.67],["c",-.03,.03,-.12,.06,-.21,.09],["c",-.24,.09,-.72,.09,-.96,0],["c",-.09,-.03,-.18,-.06,-.21,-.09],["c",-.03,-.03,-.03,-.48,0,-2.61],["c",.03,-1.44,.03,-2.61,.03,-2.61],["c",0,-.03,-.75,.09,-1.68,.24],["c",-.96,.18,-1.71,.27,-1.74,.27],["c",-.15,-.03,-.27,-.15,-.36,-.3],["l",-.06,-.15],["l",-.09,-7.53],["c",-.06,-4.14,-.09,-8.04,-.12,-8.67],["l",0,-1.11],["l",.15,-.06],["c",.09,-.03,.21,-.06,.27,-.09],["z"],["m",3.75,8.4],["c",0,-.33,0,-.42,-.03,-.42],["c",-.12,0,-2.79,.45,-2.79,.48],["c",-.03,0,-.09,6.3,-.09,6.33],["c",.03,0,2.79,-.45,2.82,-.48],["c",0,0,.09,-4.53,.09,-5.91],["z"]],w:5.4,h:22.8},"accidentals.flat":{ d:[["M",-.36,-14.07],["c",.33,-.06,.87,0,1.08,.15],["c",.06,.03,.06,.36,-.03,5.25],["c",-.06,2.85,-.09,5.19,-.09,5.19],["c",0,.03,.12,-.03,.24,-.12],["c",.63,-.42,1.41,-.66,2.19,-.72],["c",.81,-.03,1.47,.21,2.04,.78],["c",.57,.54,.87,1.26,.93,2.04],["c",.03,.57,-.09,1.08,-.36,1.62],["c",-.42,.81,-1.02,1.38,-2.82,2.61],["c",-1.14,.78,-1.44,1.02,-1.8,1.44],["c",-.18,.18,-.39,.39,-.45,.42],["c",-.27,.18,-.57,.15,-.81,-.06],["c",-.06,-.09,-.12,-.18,-.15,-.27],["c",-.03,-.06,-.09,-3.27,-.18,-8.34],["c",-.09,-4.53,-.15,-8.58,-.18,-9.03],["l",0,-.78],["l",.12,-.06],["c",.06,-.03,.18,-.09,.27,-.12],["z"],["m",3.18,11.01],["c",-.21,-.12,-.54,-.15,-.81,-.06],["c",-.54,.15,-.99,.63,-1.17,1.26],["c",-.06,.3,-.12,2.88,-.06,3.87],["c",.03,.42,.03,.81,.06,.9],["l",.03,.12],["l",.45,-.39],["c",.63,-.54,1.26,-1.17,1.56,-1.59],["c",.3,-.42,.6,-.99,.72,-1.41],["c",.18,-.69,.09,-1.47,-.18,-2.07],["c",-.15,-.3,-.33,-.51,-.6,-.63],["z"]],w:6.75,h:18.801},"accidentals.halfflat":{d:[["M",4.83,-14.07],["c",.33,-.06,.87,0,1.08,.15],["c",.06,.03,.06,.6,-.12,9.06],["c",-.09,5.55,-.15,9.06,-.18,9.12],["c",-.03,.09,-.09,.18,-.15,.27],["c",-.24,.21,-.54,.24,-.81,.06],["c",-.06,-.03,-.27,-.24,-.45,-.42],["c",-.36,-.42,-.66,-.66,-1.8,-1.44],["c",-1.23,-.84,-1.83,-1.32,-2.25,-1.77],["c",-.66,-.78,-.96,-1.56,-.93,-2.46],["c",.09,-1.41,1.11,-2.58,2.4,-2.79],["c",.3,-.06,.84,-.03,1.23,.06],["c",.54,.12,1.08,.33,1.53,.63],["c",.12,.09,.24,.15,.24,.12],["c",0,0,-.12,-8.37,-.18,-9.75],["l",0,-.66],["l",.12,-.06],["c",.06,-.03,.18,-.09,.27,-.12],["z"],["m",-1.65,10.95],["c",-.6,-.18,-1.08,.09,-1.38,.69],["c",-.27,.6,-.36,1.38,-.18,2.07],["c",.12,.42,.42,.99,.72,1.41],["c",.3,.42,.93,1.05,1.56,1.59],["l",.48,.39],["l",0,-.12],["c",.03,-.09,.03,-.48,.06,-.9],["c",.03,-.57,.03,-1.08,0,-2.22],["c",-.03,-1.62,-.03,-1.62,-.24,-2.07],["c",-.21,-.42,-.6,-.75,-1.02,-.84],["z"]],w:6.728,h:18.801},"accidentals.dblflat":{d:[["M",-.36,-14.07],["c",.33,-.06,.87,0,1.08,.15],["c",.06,.03,.06,.33,-.03,4.89],["c",-.06,2.67,-.09,5.01,-.09,5.22],["l",0,.36],["l",.15,-.15],["c",.36,-.3,.75,-.51,1.2,-.63],["c",.33,-.09,.96,-.09,1.26,-.03],["c",.27,.09,.63,.27,.87,.45],["l",.21,.15],["l",0,-.27],["c",0,-.15,-.03,-2.43,-.09,-5.1],["c",-.09,-4.56,-.09,-4.86,-.03,-4.89],["c",.15,-.12,.39,-.15,.72,-.15],["c",.3,0,.54,.03,.69,.15],["c",.06,.03,.06,.33,-.03,4.95],["c",-.06,2.7,-.09,5.04,-.09,5.22],["l",.03,.3],["l",.21,-.15],["c",.69,-.48,1.44,-.69,2.28,-.69],["c",.51,0,.78,.03,1.2,.21],["c",1.32,.63,2.01,2.28,1.53,3.69],["c",-.21,.57,-.51,1.02,-1.05,1.56],["c",-.42,.42,-.81,.72,-1.92,1.5],["c",-1.26,.87,-1.5,1.08,-1.86,1.5],["c",-.39,.45,-.54,.54,-.81,.51],["c",-.18,0,-.21,0,-.33,-.06],["l",-.21,-.21],["l",-.06,-.12],["l",-.03,-.99],["c",-.03,-.54,-.03,-1.29,-.06,-1.68],["l",0,-.69],["l",-.21,.24],["c",-.36,.42,-.75,.75,-1.8,1.62],["c",-1.02,.84,-1.2,.99,-1.44,1.38],["c",-.36,.51,-.54,.6,-.9,.51],["c",-.15,-.03,-.39,-.27,-.42,-.42],["c",-.03,-.06,-.09,-3.27,-.18,-8.34],["c",-.09,-4.53,-.15,-8.58,-.18,-9.03],["l",0,-.78],["l",.12,-.06],["c",.06,-.03,.18,-.09,.27,-.12],["z"],["m",2.52,10.98],["c",-.18,-.09,-.48,-.12,-.66,-.06],["c",-.39,.15,-.69,.54,-.84,1.14],["c",-.06,.24,-.06,.39,-.09,1.74],["c",-.03,1.44,0,2.73,.06,3.18],["l",.03,.15],["l",.27,-.27],["c",.93,-.96,1.5,-1.95,1.74,-3.06],["c",.06,-.27,.06,-.39,.06,-.96],["c",0,-.54,0,-.69,-.06,-.93],["c",-.09,-.51,-.27,-.81,-.51,-.93],["z"],["m",5.43,0],["c",-.18,-.09,-.51,-.12,-.72,-.06],["c",-.54,.12,-.96,.63,-1.17,1.26],["c",-.06,.3,-.12,2.88,-.06,3.9],["c",.03,.42,.03,.81,.06,.9],["l",.03,.12],["l",.36,-.3],["c",.42,-.36,1.02,-.96,1.29,-1.29],["c",.36,-.45,.66,-.99,.81,-1.41],["c",.42,-1.23,.15,-2.76,-.6,-3.12],["z"]],w:11.613,h:18.804},"accidentals.dblsharp":{d:[["M",-.18,-3.96],["c",.06,-.03,.12,-.06,.15,-.06],["c",.09,0,2.76,.27,2.79,.3],["c",.12,.03,.15,.12,.15,.51],["c",.06,.96,.24,1.59,.57,2.1],["c",.06,.09,.15,.21,.18,.24],["l",.09,.06],["l",.09,-.06],["c",.03,-.03,.12,-.15,.18,-.24],["c",.33,-.51,.51,-1.14,.57,-2.1],["c",0,-.39,.03,-.45,.12,-.51],["c",.03,0,.66,-.09,1.44,-.15],["c",1.47,-.15,1.5,-.15,1.56,-.03],["c",.03,.06,0,.42,-.09,1.44],["c",-.09,.72,-.15,1.35,-.15,1.38],["c",0,.03,-.03,.09,-.06,.12],["c",-.06,.06,-.12,.09,-.51,.09],["c",-1.08,.06,-1.8,.3,-2.28,.75],["l",-.12,.09],["l",.09,.09],["c",.12,.15,.39,.33,.63,.45],["c",.42,.18,.96,.27,1.68,.33],["c",.39,0,.45,.03,.51,.09],["c",.03,.03,.06,.09,.06,.12],["c",0,.03,.06,.66,.15,1.38],["c",.09,1.02,.12,1.38,.09,1.44],["c",-.06,.12,-.09,.12,-1.56,-.03],["c",-.78,-.06,-1.41,-.15,-1.44,-.15],["c",-.09,-.06,-.12,-.12,-.12,-.54],["c",-.06,-.93,-.24,-1.56,-.57,-2.07],["c",-.06,-.09,-.15,-.21,-.18,-.24],["l",-.09,-.06],["l",-.09,.06],["c",-.03,.03,-.12,.15,-.18,.24],["c",-.33,.51,-.51,1.14,-.57,2.07],["c",0,.42,-.03,.48,-.12,.54],["c",-.03,0,-.66,.09,-1.44,.15],["c",-1.47,.15,-1.5,.15,-1.56,.03],["c",-.03,-.06,0,-.42,.09,-1.44],["c",.09,-.72,.15,-1.35,.15,-1.38],["c",0,-.03,.03,-.09,.06,-.12],["c",.06,-.06,.12,-.09,.51,-.09],["c",.72,-.06,1.26,-.15,1.68,-.33],["c",.24,-.12,.51,-.3,.63,-.45],["l",.09,-.09],["l",-.12,-.09],["c",-.48,-.45,-1.2,-.69,-2.28,-.75],["c",-.39,0,-.45,-.03,-.51,-.09],["c",-.03,-.03,-.06,-.09,-.06,-.12],["c",0,-.03,-.06,-.63,-.12,-1.38],["c",-.09,-.72,-.15,-1.35,-.15,-1.38],["z"]],w:7.95,h:7.977},"dots.dot":{d:[["M",1.32,-1.68],["c",.09,-.03,.27,-.06,.39,-.06],["c",.96,0,1.74,.78,1.74,1.71],["c",0,.96,-.78,1.74,-1.71,1.74],["c",-.96,0,-1.74,-.78,-1.74,-1.71],["c",0,-.78,.54,-1.5,1.32,-1.68],["z"]],w:3.45,h:3.45},"noteheads.dbl":{d:[["M",-.69,-4.02],["c",.18,-.09,.36,-.09,.54,0],["c",.18,.09,.24,.15,.33,.3],["c",.06,.15,.06,.18,.06,1.41],["l",0,1.23],["l",.12,-.18],["c",.72,-1.26,2.64,-2.31,4.86,-2.64],["c",.81,-.15,1.11,-.15,2.13,-.15],["c",.99,0,1.29,0,2.1,.15],["c",.75,.12,1.38,.27,2.04,.54],["c",1.35,.51,2.34,1.26,2.82,2.1],["l",.12,.18],["l",0,-1.23],["c",0,-1.2,0,-1.26,.06,-1.38],["c",.09,-.18,.15,-.24,.33,-.33],["c",.18,-.09,.36,-.09,.54,0],["c",.18,.09,.24,.15,.33,.3],["l",.06,.15],["l",0,3.54],["l",0,3.54],["l",-.06,.15],["c",-.09,.18,-.15,.24,-.33,.33],["c",-.18,.09,-.36,.09,-.54,0],["c",-.18,-.09,-.24,-.15,-.33,-.33],["c",-.06,-.12,-.06,-.18,-.06,-1.38],["l",0,-1.23],["l",-.12,.18],["c",-.48,.84,-1.47,1.59,-2.82,2.1],["c",-.84,.33,-1.71,.54,-2.85,.66],["c",-.45,.06,-2.16,.06,-2.61,0],["c",-1.14,-.12,-2.01,-.33,-2.85,-.66],["c",-1.35,-.51,-2.34,-1.26,-2.82,-2.1],["l",-.12,-.18],["l",0,1.23],["c",0,1.23,0,1.26,-.06,1.38],["c",-.09,.18,-.15,.24,-.33,.33],["c",-.18,.09,-.36,.09,-.54,0],["c",-.18,-.09,-.24,-.15,-.33,-.33],["l",-.06,-.15],["l",0,-3.54],["c",0,-3.48,0,-3.54,.06,-3.66],["c",.09,-.18,.15,-.24,.33,-.33],["z"],["m",7.71,.63],["c",-.36,-.06,-.9,-.06,-1.14,0],["c",-.3,.03,-.66,.24,-.87,.42],["c",-.6,.54,-.9,1.62,-.75,2.82],["c",.12,.93,.51,1.68,1.11,2.31],["c",.75,.72,1.83,1.2,2.85,1.26],["c",1.05,.06,1.83,-.54,2.1,-1.65],["c",.21,-.9,.12,-1.95,-.24,-2.82],["c",-.36,-.81,-1.08,-1.53,-1.95,-1.95],["c",-.3,-.15,-.78,-.3,-1.11,-.39],["z"]],w:16.83,h:8.145},"noteheads.whole":{d:[["M",6.51,-4.05],["c",.51,-.03,2.01,0,2.52,.03],["c",1.41,.18,2.64,.51,3.72,1.08],["c",1.2,.63,1.95,1.41,2.19,2.31],["c",.09,.33,.09,.9,0,1.23],["c",-.24,.9,-.99,1.68,-2.19,2.31],["c",-1.08,.57,-2.28,.9,-3.75,1.08],["c",-.66,.06,-2.31,.06,-2.97,0],["c",-1.47,-.18,-2.67,-.51,-3.75,-1.08],["c",-1.2,-.63,-1.95,-1.41,-2.19,-2.31],["c",-.09,-.33,-.09,-.9,0,-1.23],["c",.24,-.9,.99,-1.68,2.19,-2.31],["c",1.2,-.63,2.61,-.99,4.23,-1.11],["z"],["m",.57,.66],["c",-.87,-.15,-1.53,0,-2.04,.51],["c",-.15,.15,-.24,.27,-.33,.48],["c",-.24,.51,-.36,1.08,-.33,1.77],["c",.03,.69,.18,1.26,.42,1.77],["c",.6,1.17,1.74,1.98,3.18,2.22],["c",1.11,.21,1.95,-.15,2.34,-.99],["c",.24,-.51,.36,-1.08,.33,-1.8],["c",-.06,-1.11,-.45,-2.04,-1.17,-2.76],["c",-.63,-.63,-1.47,-1.05,-2.4,-1.2],["z"]],w:14.985,h:8.097},"noteheads.half":{d:[["M",7.44,-4.05],["c",.06,-.03,.27,-.03,.48,-.03],["c",1.05,0,1.71,.24,2.1,.81],["c",.42,.6,.45,1.35,.18,2.4],["c",-.42,1.59,-1.14,2.73,-2.16,3.39],["c",-1.41,.93,-3.18,1.44,-5.4,1.53],["c",-1.17,.03,-1.89,-.21,-2.28,-.81],["c",-.42,-.6,-.45,-1.35,-.18,-2.4],["c",.42,-1.59,1.14,-2.73,2.16,-3.39],["c",.63,-.42,1.23,-.72,1.98,-.96],["c",.9,-.3,1.65,-.42,3.12,-.54],["z"],["m",1.29,.87],["c",-.27,-.09,-.63,-.12,-.9,-.03],["c",-.72,.24,-1.53,.69,-3.27,1.8],["c",-2.34,1.5,-3.3,2.25,-3.57,2.79],["c",-.36,.72,-.06,1.5,.66,1.77],["c",.24,.12,.69,.09,.99,0],["c",.84,-.3,1.92,-.93,4.14,-2.37],["c",1.62,-1.08,2.37,-1.71,2.61,-2.19],["c",.36,-.72,.06,-1.5,-.66,-1.77],["z"]],w:10.37,h:8.132},"noteheads.quarter":{d:[["M",6.09,-4.05],["c",.36,-.03,1.2,0,1.53,.06],["c",1.17,.24,1.89,.84,2.16,1.83],["c",.06,.18,.06,.3,.06,.66],["c",0,.45,0,.63,-.15,1.08],["c",-.66,2.04,-3.06,3.93,-5.52,4.38],["c",-.54,.09,-1.44,.09,-1.83,.03],["c",-1.23,-.27,-1.98,-.87,-2.25,-1.86],["c",-.06,-.18,-.06,-.3,-.06,-.66],["c",0,-.45,0,-.63,.15,-1.08],["c",.24,-.78,.75,-1.53,1.44,-2.22],["c",1.2,-1.2,2.85,-2.01,4.47,-2.22],["z"]],w:9.81,h:8.094},"noteheads.slash.nostem":{d:[["M",9.3,-7.77],["c",.06,-.06,.18,-.06,1.71,-.06],["l",1.65,0],["l",.09,.09],["c",.06,.06,.06,.09,.06,.15],["c",-.03,.12,-9.21,15.24,-9.3,15.33],["c",-.06,.06,-.18,.06,-1.71,.06],["l",-1.65,0],["l",-.09,-.09],["c",-.06,-.06,-.06,-.09,-.06,-.15],["c",.03,-.12,9.21,-15.24,9.3,-15.33],["z"]],w:12.81,h:15.63},"noteheads.indeterminate":{d:[["M",.78,-4.05],["c",.12,-.03,.24,-.03,.36,.03],["c",.03,.03,.93,.72,1.95,1.56],["l",1.86,1.5],["l",1.86,-1.5],["c",1.02,-.84,1.92,-1.53,1.95,-1.56],["c",.21,-.12,.33,-.09,.75,.24],["c",.3,.27,.36,.36,.36,.54],["c",0,.03,-.03,.12,-.06,.18],["c",-.03,.06,-.9,.75,-1.89,1.56],["l",-1.8,1.47],["c",0,.03,.81,.69,1.8,1.5],["c",.99,.81,1.86,1.5,1.89,1.56],["c",.03,.06,.06,.15,.06,.18],["c",0,.18,-.06,.27,-.36,.54],["c",-.42,.33,-.54,.36,-.75,.24],["c",-.03,-.03,-.93,-.72,-1.95,-1.56],["l",-1.86,-1.5],["l",-1.86,1.5],["c",-1.02,.84,-1.92,1.53,-1.95,1.56],["c",-.21,.12,-.33,.09,-.75,-.24],["c",-.3,-.27,-.36,-.36,-.36,-.54],["c",0,-.03,.03,-.12,.06,-.18],["c",.03,-.06,.9,-.75,1.89,-1.56],["l",1.8,-1.47],["c",0,-.03,-.81,-.69,-1.8,-1.5],["c",-.99,-.81,-1.86,-1.5,-1.89,-1.56],["c",-.06,-.12,-.09,-.21,-.03,-.36],["c",.03,-.09,.57,-.57,.72,-.63],["z"]],w:9.843,h:8.139},"scripts.ufermata":{d:[["M",-.75,-10.77],["c",.12,0,.45,-.03,.69,-.03],["c",2.91,-.03,5.55,1.53,7.41,4.35],["c",1.17,1.71,1.95,3.72,2.43,6.03],["c",.12,.51,.12,.57,.03,.69],["c",-.12,.21,-.48,.27,-.69,.12],["c",-.12,-.09,-.18,-.24,-.27,-.69],["c",-.78,-3.63,-3.42,-6.54,-6.78,-7.38],["c",-.78,-.21,-1.2,-.24,-2.07,-.24],["c",-.63,0,-.84,0,-1.2,.06],["c",-1.83,.27,-3.42,1.08,-4.8,2.37],["c",-1.41,1.35,-2.4,3.21,-2.85,5.19],["c",-.09,.45,-.15,.6,-.27,.69],["c",-.21,.15,-.57,.09,-.69,-.12],["c",-.09,-.12,-.09,-.18,.03,-.69],["c",.33,-1.62,.78,-3,1.47,-4.38],["c",1.77,-3.54,4.44,-5.67,7.56,-5.97],["z"],["m",.33,7.47],["c",1.38,-.3,2.58,.9,2.31,2.25],["c",-.15,.72,-.78,1.35,-1.47,1.5],["c",-1.38,.27,-2.58,-.93,-2.31,-2.31],["c",.15,-.69,.78,-1.29,1.47,-1.44],["z"]],w:19.748,h:11.289},"scripts.dfermata":{d:[["M",-9.63,-.42],["c",.15,-.09,.36,-.06,.51,.03],["c",.12,.09,.18,.24,.27,.66],["c",.78,3.66,3.42,6.57,6.78,7.41],["c",.78,.21,1.2,.24,2.07,.24],["c",.63,0,.84,0,1.2,-.06],["c",1.83,-.27,3.42,-1.08,4.8,-2.37],["c",1.41,-1.35,2.4,-3.21,2.85,-5.22],["c",.09,-.42,.15,-.57,.27,-.66],["c",.21,-.15,.57,-.09,.69,.12],["c",.09,.12,.09,.18,-.03,.69],["c",-.33,1.62,-.78,3,-1.47,4.38],["c",-1.92,3.84,-4.89,6,-8.31,6],["c",-3.42,0,-6.39,-2.16,-8.31,-6],["c",-.48,-.96,-.84,-1.92,-1.14,-2.97],["c",-.18,-.69,-.42,-1.74,-.42,-1.92],["c",0,-.12,.09,-.27,.24,-.33],["z"],["m",9.21,0],["c",1.2,-.27,2.34,.63,2.34,1.86],["c",0,.9,-.66,1.68,-1.5,1.89],["c",-1.38,.27,-2.58,-.93,-2.31,-2.31],["c",.15,-.69,.78,-1.29,1.47,-1.44],["z"]],w:19.744,h:11.274},"scripts.sforzato":{d:[["M",-6.45,-3.69],["c",.06,-.03,.15,-.06,.18,-.06],["c",.06,0,2.85,.72,6.24,1.59],["l",6.33,1.65],["c",.33,.06,.45,.21,.45,.51],["c",0,.3,-.12,.45,-.45,.51],["l",-6.33,1.65],["c",-3.39,.87,-6.18,1.59,-6.21,1.59],["c",-.21,0,-.48,-.24,-.51,-.45],["c",0,-.15,.06,-.36,.18,-.45],["c",.09,-.06,.87,-.27,3.84,-1.05],["c",2.04,-.54,3.84,-.99,4.02,-1.02],["c",.15,-.06,1.14,-.24,2.22,-.42],["c",1.05,-.18,1.92,-.36,1.92,-.36],["c",0,0,-.87,-.18,-1.92,-.36],["c",-1.08,-.18,-2.07,-.36,-2.22,-.42],["c",-.18,-.03,-1.98,-.48,-4.02,-1.02],["c",-2.97,-.78,-3.75,-.99,-3.84,-1.05],["c",-.12,-.09,-.18,-.3,-.18,-.45],["c",.03,-.15,.15,-.3,.3,-.39],["z"]],w:13.5,h:7.5},"scripts.staccato":{d:[["M",-.36,-1.47],["c",.93,-.21,1.86,.51,1.86,1.47],["c",0,.93,-.87,1.65,-1.8,1.47],["c",-.54,-.12,-1.02,-.57,-1.14,-1.08],["c",-.21,-.81,.27,-1.65,1.08,-1.86],["z"]],w:2.989,h:3.004},"scripts.tenuto":{d:[["M",-4.2,-.48],["l",.12,-.06],["l",4.08,0],["l",4.08,0],["l",.12,.06],["c",.39,.21,.39,.75,0,.96],["l",-.12,.06],["l",-4.08,0],["l",-4.08,0],["l",-.12,-.06],["c",-.39,-.21,-.39,-.75,0,-.96],["z"]],w:8.985,h:1.08},"scripts.umarcato":{d:[["M",-.15,-8.19],["c",.15,-.12,.36,-.03,.45,.15],["c",.21,.42,3.45,7.65,3.45,7.71],["c",0,.12,-.12,.27,-.21,.3],["c",-.03,.03,-.51,.03,-1.14,.03],["c",-1.05,0,-1.08,0,-1.17,-.06],["c",-.09,-.06,-.24,-.36,-1.17,-2.4],["c",-.57,-1.29,-1.05,-2.34,-1.08,-2.34],["c",0,-.03,-.51,1.02,-1.08,2.34],["c",-.93,2.07,-1.08,2.34,-1.14,2.4],["c",-.06,.03,-.15,.06,-.18,.06],["c",-.15,0,-.33,-.18,-.33,-.33],["c",0,-.06,3.24,-7.32,3.45,-7.71],["c",.03,-.06,.09,-.15,.15,-.15],["z"]],w:7.5,h:8.245},"scripts.dmarcato":{d:[["M",-3.57,.03],["c",.03,0,.57,-.03,1.17,-.03],["c",1.05,0,1.08,0,1.17,.06],["c",.09,.06,.24,.36,1.17,2.4],["c",.57,1.29,1.05,2.34,1.08,2.34],["c",0,.03,.51,-1.02,1.08,-2.34],["c",.93,-2.07,1.08,-2.34,1.14,-2.4],["c",.06,-.03,.15,-.06,.18,-.06],["c",.15,0,.33,.18,.33,.33],["c",0,.09,-3.45,7.74,-3.54,7.83],["c",-.12,.12,-.3,.12,-.42,0],["c",-.09,-.09,-3.54,-7.74,-3.54,-7.83],["c",0,-.09,.12,-.27,.18,-.3],["z"]],w:7.5,h:8.25},"scripts.stopped":{d:[["M",-.27,-4.08],["c",.18,-.09,.36,-.09,.54,0],["c",.18,.09,.24,.15,.33,.3],["l",.06,.15],["l",0,1.5],["l",0,1.47],["l",1.47,0],["l",1.5,0],["l",.15,.06],["c",.15,.09,.21,.15,.3,.33],["c",.09,.18,.09,.36,0,.54],["c",-.09,.18,-.15,.24,-.33,.33],["c",-.12,.06,-.18,.06,-1.62,.06],["l",-1.47,0],["l",0,1.47],["l",0,1.47],["l",-.06,.15],["c",-.09,.18,-.15,.24,-.33,.33],["c",-.18,.09,-.36,.09,-.54,0],["c",-.18,-.09,-.24,-.15,-.33,-.33],["l",-.06,-.15],["l",0,-1.47],["l",0,-1.47],["l",-1.47,0],["c",-1.44,0,-1.5,0,-1.62,-.06],["c",-.18,-.09,-.24,-.15,-.33,-.33],["c",-.09,-.18,-.09,-.36,0,-.54],["c",.09,-.18,.15,-.24,.33,-.33],["l",.15,-.06],["l",1.47,0],["l",1.47,0],["l",0,-1.47],["c",0,-1.44,0,-1.5,.06,-1.62],["c",.09,-.18,.15,-.24,.33,-.33],["z"]],w:8.295,h:8.295},"scripts.upbow":{d:[["M",-4.65,-15.54],["c",.12,-.09,.36,-.06,.48,.03],["c",.03,.03,.09,.09,.12,.15],["c",.03,.06,.66,2.13,1.41,4.62],["c",1.35,4.41,1.38,4.56,2.01,6.96],["l",.63,2.46],["l",.63,-2.46],["c",.63,-2.4,.66,-2.55,2.01,-6.96],["c",.75,-2.49,1.38,-4.56,1.41,-4.62],["c",.06,-.15,.18,-.21,.36,-.24],["c",.15,0,.3,.06,.39,.18],["c",.15,.21,.24,-.18,-2.1,7.56],["c",-1.2,3.96,-2.22,7.32,-2.25,7.41],["c",0,.12,-.06,.27,-.09,.3],["c",-.12,.21,-.6,.21,-.72,0],["c",-.03,-.03,-.09,-.18,-.09,-.3],["c",-.03,-.09,-1.05,-3.45,-2.25,-7.41],["c",-2.34,-7.74,-2.25,-7.35,-2.1,-7.56],["c",.03,-.03,.09,-.09,.15,-.12],["z"]],w:9.73,h:15.608},"scripts.downbow":{d:[["M",-5.55,-9.93],["l",.09,-.06],["l",5.46,0],["l",5.46,0],["l",.09,.06],["l",.06,.09],["l",0,4.77],["c",0,5.28,0,4.89,-.18,5.01],["c",-.18,.12,-.42,.06,-.54,-.12],["c",-.06,-.09,-.06,-.18,-.06,-2.97],["l",0,-2.85],["l",-4.83,0],["l",-4.83,0],["l",0,2.85],["c",0,2.79,0,2.88,-.06,2.97],["c",-.15,.24,-.51,.24,-.66,0],["c",-.06,-.09,-.06,-.21,-.06,-4.89],["l",0,-4.77],["z"]],w:11.22,h:9.992},"scripts.turn":{d:[["M",-4.77,-3.9],["c",.36,-.06,1.05,-.06,1.44,.03],["c",.78,.15,1.5,.51,2.34,1.14],["c",.6,.45,1.05,.87,2.22,2.01],["c",1.11,1.08,1.62,1.5,2.22,1.86],["c",.6,.36,1.32,.57,1.92,.57],["c",.9,0,1.71,-.57,1.89,-1.35],["c",.24,-.93,-.39,-1.89,-1.35,-2.1],["l",-.15,-.06],["l",-.09,.15],["c",-.03,.09,-.15,.24,-.24,.33],["c",-.72,.72,-2.04,.54,-2.49,-.36],["c",-.48,-.93,.03,-1.86,1.17,-2.19],["c",.3,-.09,1.02,-.09,1.35,0],["c",.99,.27,1.74,.87,2.25,1.83],["c",.69,1.41,.63,3,-.21,4.26],["c",-.21,.3,-.69,.81,-.99,1.02],["c",-.3,.21,-.84,.45,-1.17,.54],["c",-1.23,.36,-2.49,.15,-3.72,-.6],["c",-.75,-.48,-1.41,-1.02,-2.85,-2.46],["c",-1.11,-1.08,-1.62,-1.5,-2.22,-1.86],["c",-.6,-.36,-1.32,-.57,-1.92,-.57],["c",-.9,0,-1.71,.57,-1.89,1.35],["c",-.24,.93,.39,1.89,1.35,2.1],["l",.15,.06],["l",.09,-.15],["c",.03,-.09,.15,-.24,.24,-.33],["c",.72,-.72,2.04,-.54,2.49,.36],["c",.48,.93,-.03,1.86,-1.17,2.19],["c",-.3,.09,-1.02,.09,-1.35,0],["c",-.99,-.27,-1.74,-.87,-2.25,-1.83],["c",-.69,-1.41,-.63,-3,.21,-4.26],["c",.21,-.3,.69,-.81,.99,-1.02],["c",.48,-.33,1.11,-.57,1.74,-.66],["z"]],w:16.366,h:7.893},"scripts.trill":{d:[["M",-.51,-16.02],["c",.12,-.09,.21,-.18,.21,-.18],["l",-.81,4.02],["l",-.81,4.02],["c",.03,0,.51,-.27,1.08,-.6],["c",.6,-.3,1.14,-.63,1.26,-.66],["c",1.14,-.54,2.31,-.6,3.09,-.18],["c",.27,.15,.54,.36,.6,.51],["l",.06,.12],["l",.21,-.21],["c",.9,-.81,2.22,-.99,3.12,-.42],["c",.6,.42,.9,1.14,.78,2.07],["c",-.15,1.29,-1.05,2.31,-1.95,2.25],["c",-.48,-.03,-.78,-.3,-.96,-.81],["c",-.09,-.27,-.09,-.9,-.03,-1.2],["c",.21,-.75,.81,-1.23,1.59,-1.32],["l",.24,-.03],["l",-.09,-.12],["c",-.51,-.66,-1.62,-.63,-2.31,.03],["c",-.39,.42,-.3,.09,-1.23,4.77],["l",-.81,4.14],["c",-.03,0,-.12,-.03,-.21,-.09],["c",-.33,-.15,-.54,-.18,-.99,-.18],["c",-.42,0,-.66,.03,-1.05,.18],["c",-.12,.06,-.21,.09,-.21,.09],["c",0,-.03,.36,-1.86,.81,-4.11],["c",.9,-4.47,.87,-4.26,.69,-4.53],["c",-.21,-.36,-.66,-.51,-1.17,-.36],["c",-.15,.06,-2.22,1.14,-2.58,1.38],["c",-.12,.09,-.12,.09,-.21,.6],["l",-.09,.51],["l",.21,.24],["c",.63,.75,1.02,1.47,1.2,2.19],["c",.06,.27,.06,.36,.06,.81],["c",0,.42,0,.54,-.06,.78],["c",-.15,.54,-.33,.93,-.63,1.35],["c",-.18,.24,-.57,.63,-.81,.78],["c",-.24,.15,-.63,.36,-.84,.42],["c",-.27,.06,-.66,.06,-.87,.03],["c",-.81,-.18,-1.32,-1.05,-1.38,-2.46],["c",-.03,-.6,.03,-.99,.33,-2.46],["c",.21,-1.08,.24,-1.32,.21,-1.29],["c",-1.2,.48,-2.4,.75,-3.21,.72],["c",-.69,-.06,-1.17,-.3,-1.41,-.72],["c",-.39,-.75,-.12,-1.8,.66,-2.46],["c",.24,-.18,.69,-.42,1.02,-.51],["c",.69,-.18,1.53,-.15,2.31,.09],["c",.3,.09,.75,.3,.99,.45],["c",.12,.09,.15,.09,.15,.03],["c",.03,-.03,.33,-1.59,.72,-3.45],["c",.36,-1.86,.66,-3.42,.69,-3.45],["c",0,-.03,.03,-.03,.21,.03],["c",.21,.06,.27,.06,.48,.06],["c",.42,-.03,.78,-.18,1.26,-.48],["c",.15,-.12,.36,-.27,.48,-.39],["z"],["m",-5.73,7.68],["c",-.27,-.03,-.96,-.06,-1.2,-.03],["c",-.81,.12,-1.35,.57,-1.5,1.2],["c",-.18,.66,.12,1.14,.75,1.29],["c",.66,.12,1.92,-.12,3.18,-.66],["l",.33,-.15],["l",.09,-.39],["c",.06,-.21,.09,-.42,.09,-.45],["c",0,-.03,-.45,-.3,-.75,-.45],["c",-.27,-.15,-.66,-.27,-.99,-.36],["z"],["m",4.29,3.63],["c",-.24,-.39,-.51,-.75,-.51,-.69],["c",-.06,.12,-.39,1.92,-.45,2.28],["c",-.09,.54,-.12,1.14,-.06,1.38],["c",.06,.42,.21,.6,.51,.57],["c",.39,-.06,.75,-.48,.93,-1.14],["c",.09,-.33,.09,-1.05,0,-1.38],["c",-.09,-.39,-.24,-.69,-.42,-1.02],["z"]],w:17.963,h:16.49},"scripts.segno":{d:[["M",-3.72,-11.22],["c",.78,-.09,1.59,.03,2.31,.42],["c",1.2,.6,2.01,1.71,2.31,3.09],["c",.09,.42,.09,1.2,.03,1.5],["c",-.15,.45,-.39,.81,-.66,.93],["c",-.33,.18,-.84,.21,-1.23,.15],["c",-.81,-.18,-1.32,-.93,-1.26,-1.89],["c",.03,-.36,.09,-.57,.24,-.9],["c",.15,-.33,.45,-.6,.72,-.75],["c",.12,-.06,.18,-.09,.18,-.12],["c",0,-.03,-.03,-.15,-.09,-.24],["c",-.18,-.45,-.54,-.87,-.96,-1.08],["c",-1.11,-.57,-2.34,-.18,-2.88,.9],["c",-.24,.51,-.33,1.11,-.24,1.83],["c",.27,1.92,1.5,3.54,3.93,5.13],["c",.48,.33,1.26,.78,1.29,.78],["c",.03,0,1.35,-2.19,2.94,-4.89],["l",2.88,-4.89],["l",.84,0],["l",.87,0],["l",-.03,.06],["c",-.15,.21,-6.15,10.41,-6.15,10.44],["c",0,0,.21,.15,.48,.27],["c",2.61,1.47,4.35,3.03,5.13,4.65],["c",1.14,2.34,.51,5.07,-1.44,6.39],["c",-.66,.42,-1.32,.63,-2.13,.69],["c",-2.01,.09,-3.81,-1.41,-4.26,-3.54],["c",-.09,-.42,-.09,-1.2,-.03,-1.5],["c",.15,-.45,.39,-.81,.66,-.93],["c",.33,-.18,.84,-.21,1.23,-.15],["c",.81,.18,1.32,.93,1.26,1.89],["c",-.03,.36,-.09,.57,-.24,.9],["c",-.15,.33,-.45,.6,-.72,.75],["c",-.12,.06,-.18,.09,-.18,.12],["c",0,.03,.03,.15,.09,.24],["c",.18,.45,.54,.87,.96,1.08],["c",1.11,.57,2.34,.18,2.88,-.9],["c",.24,-.51,.33,-1.11,.24,-1.83],["c",-.27,-1.92,-1.5,-3.54,-3.93,-5.13],["c",-.48,-.33,-1.26,-.78,-1.29,-.78],["c",-.03,0,-1.35,2.19,-2.91,4.89],["l",-2.88,4.89],["l",-.87,0],["l",-.87,0],["l",.03,-.06],["c",.15,-.21,6.15,-10.41,6.15,-10.44],["c",0,0,-.21,-.15,-.48,-.3],["c",-2.61,-1.44,-4.35,-3,-5.13,-4.62],["c",-.9,-1.89,-.72,-4.02,.48,-5.52],["c",.69,-.84,1.68,-1.41,2.73,-1.53],["z"],["m",8.76,9.09],["c",.03,-.03,.15,-.03,.27,-.03],["c",.33,.03,.57,.18,.72,.48],["c",.09,.18,.09,.57,0,.75],["c",-.09,.18,-.21,.3,-.36,.39],["c",-.15,.06,-.21,.06,-.39,.06],["c",-.21,0,-.27,0,-.39,-.06],["c",-.3,-.15,-.48,-.45,-.48,-.75],["c",0,-.39,.24,-.72,.63,-.84],["z"],["m",-10.53,2.61],["c",.03,-.03,.15,-.03,.27,-.03],["c",.33,.03,.57,.18,.72,.48],["c",.09,.18,.09,.57,0,.75],["c",-.09,.18,-.21,.3,-.36,.39],["c",-.15,.06,-.21,.06,-.39,.06],["c",-.21,0,-.27,0,-.39,-.06],["c",-.3,-.15,-.48,-.45,-.48,-.75],["c",0,-.39,.24,-.72,.63,-.84],["z"]],w:15,h:22.504},"scripts.coda":{d:[["M",-.21,-10.47],["c",.18,-.12,.42,-.06,.54,.12],["c",.06,.09,.06,.18,.06,1.5],["l",0,1.38],["l",.18,0],["c",.39,.06,.96,.24,1.38,.48],["c",1.68,.93,2.82,3.24,3.03,6.12],["c",.03,.24,.03,.45,.03,.45],["c",0,.03,.6,.03,1.35,.03],["c",1.5,0,1.47,0,1.59,.18],["c",.09,.12,.09,.3,0,.42],["c",-.12,.18,-.09,.18,-1.59,.18],["c",-.75,0,-1.35,0,-1.35,.03],["c",0,0,0,.21,-.03,.42],["c",-.24,3.15,-1.53,5.58,-3.45,6.36],["c",-.27,.12,-.72,.24,-.96,.27],["l",-.18,0],["l",0,1.38],["c",0,1.32,0,1.41,-.06,1.5],["c",-.15,.24,-.51,.24,-.66,0],["c",-.06,-.09,-.06,-.18,-.06,-1.5],["l",0,-1.38],["l",-.18,0],["c",-.39,-.06,-.96,-.24,-1.38,-.48],["c",-1.68,-.93,-2.82,-3.24,-3.03,-6.15],["c",-.03,-.21,-.03,-.42,-.03,-.42],["c",0,-.03,-.6,-.03,-1.35,-.03],["c",-1.5,0,-1.47,0,-1.59,-.18],["c",-.09,-.12,-.09,-.3,0,-.42],["c",.12,-.18,.09,-.18,1.59,-.18],["c",.75,0,1.35,0,1.35,-.03],["c",0,0,0,-.21,.03,-.45],["c",.24,-3.12,1.53,-5.55,3.45,-6.33],["c",.27,-.12,.72,-.24,.96,-.27],["l",.18,0],["l",0,-1.38],["c",0,-1.53,0,-1.5,.18,-1.62],["z"],["m",-.18,6.93],["c",0,-2.97,0,-3.15,-.06,-3.15],["c",-.09,0,-.51,.15,-.66,.21],["c",-.87,.51,-1.38,1.62,-1.56,3.51],["c",-.06,.54,-.12,1.59,-.12,2.16],["l",0,.42],["l",1.2,0],["l",1.2,0],["l",0,-3.15],["z"],["m",1.17,-3.06],["c",-.09,-.03,-.21,-.06,-.27,-.09],["l",-.12,0],["l",0,3.15],["l",0,3.15],["l",1.2,0],["l",1.2,0],["l",0,-.81],["c",-.06,-2.4,-.33,-3.69,-.93,-4.59],["c",-.27,-.39,-.66,-.69,-1.08,-.81],["z"],["m",-1.17,10.14],["l",0,-3.15],["l",-1.2,0],["l",-1.2,0],["l",0,.81],["c",.03,.96,.06,1.47,.15,2.13],["c",.24,2.04,.96,3.12,2.13,3.36],["l",.12,0],["l",0,-3.15],["z"],["m",3.18,-2.34],["l",0,-.81],["l",-1.2,0],["l",-1.2,0],["l",0,3.15],["l",0,3.15],["l",.12,0],["c",1.17,-.24,1.89,-1.32,2.13,-3.36],["c",.09,-.66,.12,-1.17,.15,-2.13],["z"]],w:16.035,h:21.062},"scripts.comma":{d:[["M",1.14,-4.62],["c",.3,-.12,.69,-.03,.93,.15],["c",.12,.12,.36,.45,.51,.78],["c",.9,1.77,.54,4.05,-1.08,6.75],["c",-.36,.63,-.87,1.38,-.96,1.44],["c",-.18,.12,-.42,.06,-.54,-.12],["c",-.09,-.18,-.09,-.3,.12,-.6],["c",.96,-1.44,1.44,-2.97,1.38,-4.35],["c",-.06,-.93,-.3,-1.68,-.78,-2.46],["c",-.27,-.39,-.33,-.63,-.24,-.96],["c",.09,-.27,.36,-.54,.66,-.63],["z"]],w:3.042,h:9.237},"scripts.roll":{d:[["M",1.95,-6],["c",.21,-.09,.36,-.09,.57,0],["c",.39,.15,.63,.39,1.47,1.35],["c",.66,.75,.78,.87,1.08,1.05],["c",.75,.45,1.65,.42,2.4,-.06],["c",.12,-.09,.27,-.27,.54,-.6],["c",.42,-.54,.51,-.63,.69,-.63],["c",.09,0,.3,.12,.36,.21],["c",.09,.12,.12,.3,.03,.42],["c",-.06,.12,-3.15,3.9,-3.3,4.08],["c",-.06,.06,-.18,.12,-.27,.18],["c",-.27,.12,-.6,.06,-.99,-.27],["c",-.27,-.21,-.42,-.39,-1.08,-1.14],["c",-.63,-.72,-.81,-.9,-1.17,-1.08],["c",-.36,-.18,-.57,-.21,-.99,-.21],["c",-.39,0,-.63,.03,-.93,.18],["c",-.36,.15,-.51,.27,-.9,.81],["c",-.24,.27,-.45,.51,-.48,.54],["c",-.12,.09,-.27,.06,-.39,0],["c",-.24,-.15,-.33,-.39,-.21,-.6],["c",.09,-.12,3.18,-3.87,3.33,-4.02],["c",.06,-.06,.18,-.15,.24,-.21],["z"]],w:10.817,h:6.125},"scripts.prall":{d:[["M",-4.38,-3.69],["c",.06,-.03,.18,-.06,.24,-.06],["c",.3,0,.27,-.03,1.89,1.95],["l",1.53,1.83],["c",.03,0,.57,-.84,1.23,-1.83],["c",1.14,-1.68,1.23,-1.83,1.35,-1.89],["c",.06,-.03,.18,-.06,.24,-.06],["c",.3,0,.27,-.03,1.89,1.95],["l",1.53,1.83],["l",.48,-.69],["c",.51,-.78,.54,-.84,.69,-.9],["c",.42,-.18,.87,.15,.81,.6],["c",-.03,.12,-.3,.51,-1.5,2.37],["c",-1.38,2.07,-1.5,2.22,-1.62,2.28],["c",-.06,.03,-.18,.06,-.24,.06],["c",-.3,0,-.27,.03,-1.89,-1.95],["l",-1.53,-1.83],["c",-.03,0,-.57,.84,-1.23,1.83],["c",-1.14,1.68,-1.23,1.83,-1.35,1.89],["c",-.06,.03,-.18,.06,-.24,.06],["c",-.3,0,-.27,.03,-1.89,-1.95],["l",-1.53,-1.83],["l",-.48,.69],["c",-.51,.78,-.54,.84,-.69,.9],["c",-.42,.18,-.87,-.15,-.81,-.6],["c",.03,-.12,.3,-.51,1.5,-2.37],["c",1.38,-2.07,1.5,-2.22,1.62,-2.28],["z"]],w:15.011,h:7.5},"scripts.mordent":{d:[["M",-.21,-4.95],["c",.27,-.15,.63,0,.75,.27],["c",.06,.12,.06,.24,.06,1.44],["l",0,1.29],["l",.57,-.84],["c",.51,-.75,.57,-.84,.69,-.9],["c",.06,-.03,.18,-.06,.24,-.06],["c",.3,0,.27,-.03,1.89,1.95],["l",1.53,1.83],["l",.48,-.69],["c",.51,-.78,.54,-.84,.69,-.9],["c",.42,-.18,.87,.15,.81,.6],["c",-.03,.12,-.3,.51,-1.5,2.37],["c",-1.38,2.07,-1.5,2.22,-1.62,2.28],["c",-.06,.03,-.18,.06,-.24,.06],["c",-.3,0,-.27,.03,-1.83,-1.89],["c",-.81,-.99,-1.5,-1.8,-1.53,-1.86],["c",-.06,-.03,-.06,-.03,-.12,.03],["c",-.06,.06,-.06,.15,-.06,2.28],["c",0,1.95,0,2.25,-.06,2.34],["c",-.18,.45,-.81,.48,-1.05,.03],["c",-.03,-.06,-.06,-.24,-.06,-1.41],["l",0,-1.35],["l",-.57,.84],["c",-.54,.78,-.6,.87,-.72,.93],["c",-.06,.03,-.18,.06,-.24,.06],["c",-.3,0,-.27,.03,-1.89,-1.95],["l",-1.53,-1.83],["l",-.48,.69],["c",-.51,.78,-.54,.84,-.69,.9],["c",-.42,.18,-.87,-.15,-.81,-.6],["c",.03,-.12,.3,-.51,1.5,-2.37],["c",1.38,-2.07,1.5,-2.22,1.62,-2.28],["c",.06,-.03,.18,-.06,.24,-.06],["c",.3,0,.27,-.03,1.89,1.95],["l",1.53,1.83],["c",.03,0,.06,-.06,.09,-.09],["c",.06,-.12,.06,-.15,.06,-2.28],["c",0,-1.92,0,-2.22,.06,-2.31],["c",.06,-.15,.15,-.24,.3,-.3],["z"]],w:15.011,h:10.012},"flags.u8th":{d:[["M",-.42,3.75],["l",0,-3.75],["l",.21,0],["l",.21,0],["l",0,.18],["c",0,.3,.06,.84,.12,1.23],["c",.24,1.53,.9,3.12,2.13,5.16],["l",.99,1.59],["c",.87,1.44,1.38,2.34,1.77,3.09],["c",.81,1.68,1.2,3.06,1.26,4.53],["c",.03,1.53,-.21,3.27,-.75,5.01],["c",-.21,.69,-.51,1.5,-.6,1.59],["c",-.09,.12,-.27,.21,-.42,.21],["c",-.15,0,-.42,-.12,-.51,-.21],["c",-.15,-.18,-.18,-.42,-.09,-.66],["c",.15,-.33,.45,-1.2,.57,-1.62],["c",.42,-1.38,.6,-2.58,.6,-3.9],["c",0,-.66,0,-.81,-.06,-1.11],["c",-.39,-2.07,-1.8,-4.26,-4.59,-7.14],["l",-.42,-.45],["l",-.21,0],["l",-.21,0],["l",0,-3.75],["z"]],w:6.692,h:22.59},"flags.u16th":{d:[["M",-.42,7.5],["l",0,-7.5],["l",.21,0],["l",.21,0],["l",0,.39],["c",.06,1.08,.39,2.19,.99,3.39],["c",.45,.9,.87,1.59,1.95,3.12],["c",1.29,1.86,1.77,2.64,2.22,3.57],["c",.45,.93,.72,1.8,.87,2.64],["c",.06,.51,.06,1.5,0,1.92],["c",-.12,.6,-.3,1.2,-.54,1.71],["l",-.09,.24],["l",.18,.45],["c",.51,1.2,.72,2.22,.69,3.42],["c",-.06,1.53,-.39,3.03,-.99,4.53],["c",-.3,.75,-.36,.81,-.57,.9],["c",-.15,.09,-.33,.06,-.48,0],["c",-.18,-.09,-.27,-.18,-.33,-.33],["c",-.09,-.18,-.06,-.3,.12,-.75],["c",.66,-1.41,1.02,-2.88,1.08,-4.32],["c",0,-.6,-.03,-1.05,-.18,-1.59],["c",-.3,-1.2,-.99,-2.4,-2.25,-3.87],["c",-.42,-.48,-1.53,-1.62,-2.19,-2.22],["l",-.45,-.42],["l",-.03,1.11],["l",0,1.11],["l",-.21,0],["l",-.21,0],["l",0,-7.5],["z"],["m",1.65,.09],["c",-.3,-.3,-.69,-.72,-.9,-.87],["l",-.33,-.33],["l",0,.15],["c",0,.3,.06,.81,.15,1.26],["c",.27,1.29,.87,2.61,2.04,4.29],["c",.15,.24,.6,.87,.96,1.38],["l",1.08,1.53],["l",.42,.63],["c",.03,0,.12,-.36,.21,-.72],["c",.06,-.33,.06,-1.2,0,-1.62],["c",-.33,-1.71,-1.44,-3.48,-3.63,-5.7],["z"]],w:6.693,h:26.337},"flags.u32nd":{d:[["M",-.42,11.25],["l",0,-11.25],["l",.21,0],["l",.21,0],["l",0,.36],["c",.09,1.68,.69,3.27,2.07,5.46],["l",.87,1.35],["c",1.02,1.62,1.47,2.37,1.86,3.18],["c",.48,1.02,.78,1.92,.93,2.88],["c",.06,.48,.06,1.5,0,1.89],["c",-.09,.42,-.21,.87,-.36,1.26],["l",-.12,.3],["l",.15,.39],["c",.69,1.56,.84,2.88,.54,4.38],["c",-.09,.45,-.27,1.08,-.45,1.47],["l",-.12,.24],["l",.18,.36],["c",.33,.72,.57,1.56,.69,2.34],["c",.12,1.02,-.06,2.52,-.42,3.84],["c",-.27,.93,-.75,2.13,-.93,2.31],["c",-.18,.15,-.45,.18,-.66,.09],["c",-.18,-.09,-.27,-.18,-.33,-.33],["c",-.09,-.18,-.06,-.3,.06,-.6],["c",.21,-.36,.42,-.9,.57,-1.38],["c",.51,-1.41,.69,-3.06,.48,-4.08],["c",-.15,-.81,-.57,-1.68,-1.2,-2.55],["c",-.72,-.99,-1.83,-2.13,-3.3,-3.33],["l",-.48,-.42],["l",-.03,1.53],["l",0,1.56],["l",-.21,0],["l",-.21,0],["l",0,-11.25],["z"],["m",1.26,-3.96],["c",-.27,-.3,-.54,-.6,-.66,-.72],["l",-.18,-.21],["l",0,.42],["c",.06,.87,.24,1.74,.66,2.67],["c",.36,.87,.96,1.86,1.92,3.18],["c",.21,.33,.63,.87,.87,1.23],["c",.27,.39,.6,.84,.75,1.08],["l",.27,.39],["l",.03,-.12],["c",.12,-.45,.15,-1.05,.09,-1.59],["c",-.27,-1.86,-1.38,-3.78,-3.75,-6.33],["z"],["m",-.27,6.09],["c",-.27,-.21,-.48,-.42,-.51,-.45],["c",-.06,-.03,-.06,-.03,-.06,.21],["c",0,.9,.3,2.04,.81,3.09],["c",.48,1.02,.96,1.77,2.37,3.63],["c",.6,.78,1.05,1.44,1.29,1.77],["c",.06,.12,.15,.21,.15,.18],["c",.03,-.03,.18,-.57,.24,-.87],["c",.06,-.45,.06,-1.32,-.03,-1.74],["c",-.09,-.48,-.24,-.9,-.51,-1.44],["c",-.66,-1.35,-1.83,-2.7,-3.75,-4.38],["z"]],w:6.697,h:32.145},"flags.u64th":{d:[["M",-.42,15],["l",0,-15],["l",.21,0],["l",.21,0],["l",0,.36],["c",.06,1.2,.39,2.37,1.02,3.66],["c",.39,.81,.84,1.56,1.8,3.09],["c",.81,1.26,1.05,1.68,1.35,2.22],["c",.87,1.5,1.35,2.79,1.56,4.08],["c",.06,.54,.06,1.56,-.03,2.04],["c",-.09,.48,-.21,.99,-.36,1.35],["l",-.12,.27],["l",.12,.27],["c",.09,.15,.21,.45,.27,.66],["c",.69,1.89,.63,3.66,-.18,5.46],["l",-.18,.39],["l",.15,.33],["c",.3,.66,.51,1.44,.63,2.1],["c",.06,.48,.06,1.35,0,1.71],["c",-.15,.57,-.42,1.2,-.78,1.68],["l",-.21,.27],["l",.18,.33],["c",.57,1.05,.93,2.13,1.02,3.18],["c",.06,.72,0,1.83,-.21,2.79],["c",-.18,1.02,-.63,2.34,-1.02,3.09],["c",-.15,.33,-.48,.45,-.78,.3],["c",-.18,-.09,-.27,-.18,-.33,-.33],["c",-.09,-.18,-.06,-.3,.03,-.54],["c",.75,-1.5,1.23,-3.45,1.17,-4.89],["c",-.06,-1.02,-.42,-2.01,-1.17,-3.15],["c",-.48,-.72,-1.02,-1.35,-1.89,-2.22],["c",-.57,-.57,-1.56,-1.5,-1.92,-1.77],["l",-.12,-.09],["l",0,1.68],["l",0,1.68],["l",-.21,0],["l",-.21,0],["l",0,-15],["z"],["m",.93,-8.07],["c",-.27,-.3,-.48,-.54,-.51,-.54],["c",0,0,0,.69,.03,1.02],["c",.15,1.47,.75,2.94,2.04,4.83],["l",1.08,1.53],["c",.39,.57,.84,1.2,.99,1.44],["c",.15,.24,.3,.45,.3,.45],["c",0,0,.03,-.09,.06,-.21],["c",.36,-1.59,-.15,-3.33,-1.47,-5.4],["c",-.63,-.93,-1.35,-1.83,-2.52,-3.12],["z"],["m",.06,6.72],["c",-.24,-.21,-.48,-.42,-.51,-.45],["l",-.06,-.06],["l",0,.33],["c",0,1.2,.3,2.34,.93,3.6],["c",.45,.9,.96,1.68,2.25,3.51],["c",.39,.54,.84,1.17,1.02,1.44],["c",.21,.33,.33,.51,.33,.48],["c",.06,-.09,.21,-.63,.3,-.99],["c",.06,-.33,.06,-.45,.06,-.96],["c",0,-.6,-.03,-.84,-.18,-1.35],["c",-.3,-1.08,-1.02,-2.28,-2.13,-3.57],["c",-.39,-.45,-1.44,-1.47,-2.01,-1.98],["z"],["m",0,6.72],["c",-.24,-.21,-.48,-.39,-.51,-.42],["l",-.06,-.06],["l",0,.33],["c",0,1.41,.45,2.82,1.38,4.35],["c",.42,.72,.72,1.14,1.86,2.73],["c",.36,.45,.75,.99,.87,1.2],["c",.15,.21,.3,.36,.3,.36],["c",.06,0,.3,-.48,.39,-.75],["c",.09,-.36,.12,-.63,.12,-1.05],["c",-.06,-1.05,-.45,-2.04,-1.2,-3.18],["c",-.57,-.87,-1.11,-1.53,-2.07,-2.49],["c",-.36,-.33,-.84,-.78,-1.08,-1.02],["z"]],w:6.682,h:39.694},"flags.d8th":{d:[["M",5.67,-21.63],["c",.24,-.12,.54,-.06,.69,.15],["c",.06,.06,.21,.36,.39,.66],["c",.84,1.77,1.26,3.36,1.32,5.1],["c",.03,1.29,-.21,2.37,-.81,3.63],["c",-.6,1.23,-1.26,2.13,-3.21,4.38],["c",-1.35,1.53,-1.86,2.19,-2.4,2.97],["c",-.63,.93,-1.11,1.92,-1.38,2.79],["c",-.15,.54,-.27,1.35,-.27,1.8],["l",0,.15],["l",-.21,0],["l",-.21,0],["l",0,-3.75],["l",0,-3.75],["l",.21,0],["l",.21,0],["l",.48,-.3],["c",1.83,-1.11,3.12,-2.1,4.17,-3.12],["c",.78,-.81,1.32,-1.53,1.71,-2.31],["c",.45,-.93,.6,-1.74,.51,-2.88],["c",-.12,-1.56,-.63,-3.18,-1.47,-4.68],["c",-.12,-.21,-.15,-.33,-.06,-.51],["c",.06,-.15,.15,-.24,.33,-.33],["z"]], w:8.492,h:21.691},"flags.ugrace":{d:[["M",6.03,6.93],["c",.15,-.09,.33,-.06,.51,0],["c",.15,.09,.21,.15,.3,.33],["c",.09,.18,.06,.39,-.03,.54],["c",-.06,.15,-10.89,8.88,-11.07,8.97],["c",-.15,.09,-.33,.06,-.48,0],["c",-.18,-.09,-.24,-.15,-.33,-.33],["c",-.09,-.18,-.06,-.39,.03,-.54],["c",.06,-.15,10.89,-8.88,11.07,-8.97],["z"]],w:12.019,h:9.954},"flags.dgrace":{d:[["M",-6.06,-15.93],["c",.18,-.09,.33,-.12,.48,-.06],["c",.18,.09,14.01,8.04,14.1,8.1],["c",.12,.12,.18,.33,.18,.51],["c",-.03,.21,-.15,.39,-.36,.48],["c",-.18,.09,-.33,.12,-.48,.06],["c",-.18,-.09,-14.01,-8.04,-14.1,-8.1],["c",-.12,-.12,-.18,-.33,-.18,-.51],["c",.03,-.21,.15,-.39,.36,-.48],["z"]],w:15.12,h:9.212},"flags.d16th":{d:[["M",6.84,-22.53],["c",.27,-.12,.57,-.06,.72,.15],["c",.15,.15,.33,.87,.45,1.56],["c",.06,.33,.06,1.35,0,1.65],["c",-.06,.33,-.15,.78,-.27,1.11],["c",-.12,.33,-.45,.96,-.66,1.32],["l",-.18,.27],["l",.09,.18],["c",.48,1.02,.72,2.25,.69,3.3],["c",-.06,1.23,-.42,2.28,-1.26,3.45],["c",-.57,.87,-.99,1.32,-3,3.39],["c",-1.56,1.56,-2.22,2.4,-2.76,3.45],["c",-.42,.84,-.66,1.8,-.66,2.55],["l",0,.15],["l",-.21,0],["l",-.21,0],["l",0,-7.5],["l",0,-7.5],["l",.21,0],["l",.21,0],["l",0,1.14],["l",0,1.11],["l",.27,-.15],["c",1.11,-.57,1.77,-.99,2.52,-1.47],["c",2.37,-1.56,3.69,-3.15,4.05,-4.83],["c",.03,-.18,.03,-.39,.03,-.78],["c",0,-.6,-.03,-.93,-.24,-1.5],["c",-.06,-.18,-.12,-.39,-.15,-.45],["c",-.03,-.24,.12,-.48,.36,-.6],["z"],["m",-.63,7.5],["c",-.06,-.18,-.15,-.36,-.15,-.36],["c",-.03,0,-.03,.03,-.06,.06],["c",-.06,.12,-.96,1.02,-1.95,1.98],["c",-.63,.57,-1.26,1.17,-1.44,1.35],["c",-1.53,1.62,-2.28,2.85,-2.55,4.32],["c",-.03,.18,-.03,.54,-.06,.99],["l",0,.69],["l",.18,-.09],["c",.93,-.54,2.1,-1.29,2.82,-1.83],["c",.69,-.51,1.02,-.81,1.53,-1.29],["c",1.86,-1.89,2.37,-3.66,1.68,-5.82],["z"]],w:8.475,h:22.591},"flags.d32nd":{d:[["M",6.84,-29.13],["c",.27,-.12,.57,-.06,.72,.15],["c",.12,.12,.27,.63,.36,1.11],["c",.33,1.59,.06,3.06,-.81,4.47],["l",-.18,.27],["l",.09,.15],["c",.12,.24,.33,.69,.45,1.05],["c",.63,1.83,.45,3.57,-.57,5.22],["l",-.18,.3],["l",.15,.27],["c",.42,.87,.6,1.71,.57,2.61],["c",-.06,1.29,-.48,2.46,-1.35,3.78],["c",-.54,.81,-.93,1.29,-2.46,3],["c",-.51,.54,-1.05,1.17,-1.26,1.41],["c",-1.56,1.86,-2.25,3.36,-2.37,5.01],["l",0,.33],["l",-.21,0],["l",-.21,0],["l",0,-11.25],["l",0,-11.25],["l",.21,0],["l",.21,0],["l",0,1.35],["l",.03,1.35],["l",.78,-.39],["c",1.38,-.69,2.34,-1.26,3.24,-1.92],["c",1.38,-1.02,2.28,-2.13,2.64,-3.21],["c",.15,-.48,.18,-.72,.18,-1.29],["c",0,-.57,-.06,-.9,-.24,-1.47],["c",-.06,-.18,-.12,-.39,-.15,-.45],["c",-.03,-.24,.12,-.48,.36,-.6],["z"],["m",-.63,7.2],["c",-.09,-.18,-.12,-.21,-.12,-.15],["c",-.03,.09,-1.02,1.08,-2.04,2.04],["c",-1.17,1.08,-1.65,1.56,-2.07,2.04],["c",-.84,.96,-1.38,1.86,-1.68,2.76],["c",-.21,.57,-.27,.99,-.3,1.65],["l",0,.54],["l",.66,-.33],["c",3.57,-1.86,5.49,-3.69,5.94,-5.7],["c",.06,-.39,.06,-1.2,-.03,-1.65],["c",-.06,-.39,-.24,-.9,-.36,-1.2],["z"],["m",-.06,7.2],["c",-.06,-.15,-.12,-.33,-.15,-.45],["l",-.06,-.18],["l",-.18,.21],["l",-1.83,1.83],["c",-.87,.9,-1.77,1.8,-1.95,2.01],["c",-1.08,1.29,-1.62,2.31,-1.89,3.51],["c",-.06,.3,-.06,.51,-.09,.93],["l",0,.57],["l",.09,-.06],["c",.75,-.45,1.89,-1.26,2.52,-1.74],["c",.81,-.66,1.74,-1.53,2.22,-2.16],["c",1.26,-1.53,1.68,-3.06,1.32,-4.47],["z"]],w:8.385,h:29.191},"flags.d64th":{d:[["M",7.08,-32.88],["c",.3,-.12,.66,-.03,.78,.24],["c",.18,.33,.27,2.1,.15,2.64],["c",-.09,.39,-.21,.78,-.39,1.08],["l",-.15,.3],["l",.09,.27],["c",.03,.12,.09,.45,.12,.69],["c",.27,1.44,.18,2.55,-.3,3.6],["l",-.12,.33],["l",.06,.42],["c",.27,1.35,.33,2.82,.21,3.63],["c",-.12,.6,-.3,1.23,-.57,1.8],["l",-.15,.27],["l",.03,.42],["c",.06,1.02,.06,2.7,.03,3.06],["c",-.15,1.47,-.66,2.76,-1.74,4.41],["c",-.45,.69,-.75,1.11,-1.74,2.37],["c",-1.05,1.38,-1.5,1.98,-1.95,2.73],["c",-.93,1.5,-1.38,2.82,-1.44,4.2],["l",0,.42],["l",-.21,0],["l",-.21,0],["l",0,-15],["l",0,-15],["l",.21,0],["l",.21,0],["l",0,1.86],["l",0,1.89],["c",0,0,.21,-.03,.45,-.09],["c",2.22,-.39,4.08,-1.11,5.19,-2.01],["c",.63,-.54,1.02,-1.14,1.2,-1.8],["c",.06,-.3,.06,-1.14,-.03,-1.65],["c",-.03,-.18,-.06,-.39,-.09,-.48],["c",-.03,-.24,.12,-.48,.36,-.6],["z"],["m",-.45,6.15],["c",-.03,-.18,-.06,-.42,-.06,-.54],["l",-.03,-.18],["l",-.33,.3],["c",-.42,.36,-.87,.72,-1.68,1.29],["c",-1.98,1.38,-2.25,1.59,-2.85,2.16],["c",-.75,.69,-1.23,1.44,-1.47,2.19],["c",-.15,.45,-.18,.63,-.21,1.35],["l",0,.66],["l",.39,-.18],["c",1.83,-.9,3.45,-1.95,4.47,-2.91],["c",.93,-.9,1.53,-1.83,1.74,-2.82],["c",.06,-.33,.06,-.87,.03,-1.32],["z"],["m",-.27,4.86],["c",-.03,-.21,-.06,-.36,-.06,-.36],["c",0,-.03,-.12,.09,-.24,.24],["c",-.39,.48,-.99,1.08,-2.16,2.19],["c",-1.47,1.38,-1.92,1.83,-2.46,2.49],["c",-.66,.87,-1.08,1.74,-1.29,2.58],["c",-.09,.42,-.15,.87,-.15,1.44],["l",0,.54],["l",.48,-.33],["c",1.5,-1.02,2.58,-1.89,3.51,-2.82],["c",1.47,-1.47,2.25,-2.85,2.4,-4.26],["c",.03,-.39,.03,-1.17,-.03,-1.71],["z"],["m",-.66,7.68],["c",.03,-.15,.03,-.6,.03,-.99],["l",0,-.72],["l",-.27,.33],["l",-1.74,1.98],["c",-1.77,1.92,-2.43,2.76,-2.97,3.9],["c",-.51,1.02,-.72,1.77,-.75,2.91],["c",0,.63,0,.63,.06,.6],["c",.03,-.03,.3,-.27,.63,-.54],["c",.66,-.6,1.86,-1.8,2.31,-2.31],["c",1.65,-1.89,2.52,-3.54,2.7,-5.16],["z"]],w:8.485,h:32.932},"clefs.C":{d:[["M",.06,-14.94],["l",.09,-.06],["l",1.92,0],["l",1.92,0],["l",.09,.06],["l",.06,.09],["l",0,14.85],["l",0,14.82],["l",-.06,.09],["l",-.09,.06],["l",-1.92,0],["l",-1.92,0],["l",-.09,-.06],["l",-.06,-.09],["l",0,-14.82],["l",0,-14.85],["z"],["m",5.37,0],["c",.09,-.06,.09,-.06,.57,-.06],["c",.45,0,.45,0,.54,.06],["l",.06,.09],["l",0,7.14],["l",0,7.11],["l",.09,-.06],["c",.18,-.18,.72,-.84,.96,-1.2],["c",.3,-.45,.66,-1.17,.84,-1.65],["c",.36,-.9,.57,-1.83,.6,-2.79],["c",.03,-.48,.03,-.54,.09,-.63],["c",.12,-.18,.36,-.21,.54,-.12],["c",.18,.09,.21,.15,.24,.66],["c",.06,.87,.21,1.56,.57,2.22],["c",.51,1.02,1.26,1.68,2.22,1.92],["c",.21,.06,.33,.06,.78,.06],["c",.45,0,.57,0,.84,-.06],["c",.45,-.12,.81,-.33,1.08,-.6],["c",.57,-.57,.87,-1.41,.99,-2.88],["c",.06,-.54,.06,-3,0,-3.57],["c",-.21,-2.58,-.84,-3.87,-2.16,-4.5],["c",-.48,-.21,-1.17,-.36,-1.77,-.36],["c",-.69,0,-1.29,.27,-1.5,.72],["c",-.06,.15,-.06,.21,-.06,.42],["c",0,.24,0,.3,.06,.45],["c",.12,.24,.24,.39,.63,.66],["c",.42,.3,.57,.48,.69,.72],["c",.06,.15,.06,.21,.06,.48],["c",0,.39,-.03,.63,-.21,.96],["c",-.3,.6,-.87,1.08,-1.5,1.26],["c",-.27,.06,-.87,.06,-1.14,0],["c",-.78,-.24,-1.44,-.87,-1.65,-1.68],["c",-.12,-.42,-.09,-1.17,.09,-1.71],["c",.51,-1.65,1.98,-2.82,3.81,-3.09],["c",.84,-.09,2.46,.03,3.51,.27],["c",2.22,.57,3.69,1.8,4.44,3.75],["c",.36,.93,.57,2.13,.57,3.36],["c",0,1.44,-.48,2.73,-1.38,3.81],["c",-1.26,1.5,-3.27,2.43,-5.28,2.43],["c",-.48,0,-.51,0,-.75,-.09],["c",-.15,-.03,-.48,-.21,-.78,-.36],["c",-.69,-.36,-.87,-.42,-1.26,-.42],["c",-.27,0,-.3,0,-.51,.09],["c",-.57,.3,-.81,.9,-.81,2.1],["c",0,1.23,.24,1.83,.81,2.13],["c",.21,.09,.24,.09,.51,.09],["c",.39,0,.57,-.06,1.26,-.42],["c",.3,-.15,.63,-.33,.78,-.36],["c",.24,-.09,.27,-.09,.75,-.09],["c",2.01,0,4.02,.93,5.28,2.4],["c",.9,1.11,1.38,2.4,1.38,3.84],["c",0,1.5,-.3,2.88,-.84,3.96],["c",-.78,1.59,-2.19,2.64,-4.17,3.15],["c",-1.05,.24,-2.67,.36,-3.51,.27],["c",-1.83,-.27,-3.3,-1.44,-3.81,-3.09],["c",-.18,-.54,-.21,-1.29,-.09,-1.74],["c",.15,-.6,.63,-1.2,1.23,-1.47],["c",.36,-.18,.57,-.21,.99,-.21],["c",.42,0,.63,.03,1.02,.21],["c",.42,.21,.84,.63,1.05,1.05],["c",.18,.36,.21,.6,.21,.96],["c",0,.3,0,.36,-.06,.51],["c",-.12,.24,-.27,.42,-.69,.72],["c",-.57,.42,-.69,.63,-.69,1.08],["c",0,.24,0,.3,.06,.45],["c",.12,.21,.3,.39,.57,.54],["c",.42,.18,.87,.21,1.53,.15],["c",1.08,-.15,1.8,-.57,2.34,-1.32],["c",.54,-.75,.84,-1.83,.99,-3.51],["c",.06,-.57,.06,-3.03,0,-3.57],["c",-.12,-1.47,-.42,-2.31,-.99,-2.88],["c",-.27,-.27,-.63,-.48,-1.08,-.6],["c",-.27,-.06,-.39,-.06,-.84,-.06],["c",-.45,0,-.57,0,-.78,.06],["c",-1.14,.27,-2.01,1.17,-2.46,2.49],["c",-.21,.57,-.3,.99,-.33,1.65],["c",-.03,.51,-.06,.57,-.24,.66],["c",-.12,.06,-.27,.06,-.39,0],["c",-.21,-.09,-.21,-.15,-.24,-.75],["c",-.09,-1.92,-.78,-3.72,-2.01,-5.19],["c",-.18,-.21,-.36,-.42,-.39,-.45],["l",-.09,-.06],["l",0,7.11],["l",0,7.14],["l",-.06,.09],["c",-.09,.06,-.09,.06,-.54,.06],["c",-.48,0,-.48,0,-.57,-.06],["l",-.06,-.09],["l",0,-14.82],["l",0,-14.85],["z"]],w:20.31,h:29.97},"clefs.F":{d:[["M",6.3,-7.8],["c",.36,-.03,1.65,0,2.13,.03],["c",3.6,.42,6.03,2.1,6.93,4.86],["c",.27,.84,.36,1.5,.36,2.58],["c",0,.9,-.03,1.35,-.18,2.16],["c",-.78,3.78,-3.54,7.08,-8.37,9.96],["c",-1.74,1.05,-3.87,2.13,-6.18,3.12],["c",-.39,.18,-.75,.33,-.81,.36],["c",-.06,.03,-.15,.06,-.18,.06],["c",-.15,0,-.33,-.18,-.33,-.33],["c",0,-.15,.06,-.21,.51,-.48],["c",3,-1.77,5.13,-3.21,6.84,-4.74],["c",.51,-.45,1.59,-1.5,1.95,-1.95],["c",1.89,-2.19,2.88,-4.32,3.15,-6.78],["c",.06,-.42,.06,-1.77,0,-2.19],["c",-.24,-2.01,-.93,-3.63,-2.04,-4.71],["c",-.63,-.63,-1.29,-1.02,-2.07,-1.2],["c",-1.62,-.39,-3.36,.15,-4.56,1.44],["c",-.54,.6,-1.05,1.47,-1.32,2.22],["l",-.09,.21],["l",.24,-.12],["c",.39,-.21,.63,-.24,1.11,-.24],["c",.3,0,.45,0,.66,.06],["c",1.92,.48,2.85,2.55,1.95,4.38],["c",-.45,.99,-1.41,1.62,-2.46,1.71],["c",-1.47,.09,-2.91,-.87,-3.39,-2.25],["c",-.18,-.57,-.21,-1.32,-.03,-2.28],["c",.39,-2.25,1.83,-4.2,3.81,-5.19],["c",.69,-.36,1.59,-.6,2.37,-.69],["z"],["m",11.58,2.52],["c",.84,-.21,1.71,.3,1.89,1.14],["c",.3,1.17,-.72,2.19,-1.89,1.89],["c",-.99,-.21,-1.5,-1.32,-1.02,-2.25],["c",.18,-.39,.6,-.69,1.02,-.78],["z"],["m",0,7.5],["c",.84,-.21,1.71,.3,1.89,1.14],["c",.21,.87,-.3,1.71,-1.14,1.89],["c",-.87,.21,-1.71,-.3,-1.89,-1.14],["c",-.21,-.84,.3,-1.71,1.14,-1.89],["z"]],w:20.153,h:23.142},"clefs.G":{d:[["M",9.69,-37.41],["c",.09,-.09,.24,-.06,.36,0],["c",.12,.09,.57,.6,.96,1.11],["c",1.77,2.34,3.21,5.85,3.57,8.73],["c",.21,1.56,.03,3.27,-.45,4.86],["c",-.69,2.31,-1.92,4.47,-4.23,7.44],["c",-.3,.39,-.57,.72,-.6,.75],["c",-.03,.06,0,.15,.18,.78],["c",.54,1.68,1.38,4.44,1.68,5.49],["l",.09,.42],["l",.39,0],["c",1.47,.09,2.76,.51,3.96,1.29],["c",1.83,1.23,3.06,3.21,3.39,5.52],["c",.09,.45,.12,1.29,.06,1.74],["c",-.09,1.02,-.33,1.83,-.75,2.73],["c",-.84,1.71,-2.28,3.06,-4.02,3.72],["l",-.33,.12],["l",.03,1.26],["c",0,1.74,-.06,3.63,-.21,4.62],["c",-.45,3.06,-2.19,5.49,-4.47,6.21],["c",-.57,.18,-.9,.21,-1.59,.21],["c",-.69,0,-1.02,-.03,-1.65,-.21],["c",-1.14,-.27,-2.13,-.84,-2.94,-1.65],["c",-.99,-.99,-1.56,-2.16,-1.71,-3.54],["c",-.09,-.81,.06,-1.53,.45,-2.13],["c",.63,-.99,1.83,-1.56,3,-1.53],["c",1.5,.09,2.64,1.32,2.73,2.94],["c",.06,1.47,-.93,2.7,-2.37,2.97],["c",-.45,.06,-.84,.03,-1.29,-.09],["l",-.21,-.09],["l",.09,.12],["c",.39,.54,.78,.93,1.32,1.26],["c",1.35,.87,3.06,1.02,4.35,.36],["c",1.44,-.72,2.52,-2.28,2.97,-4.35],["c",.15,-.66,.24,-1.5,.3,-3.03],["c",.03,-.84,.03,-2.94,0,-3],["c",-.03,0,-.18,0,-.36,.03],["c",-.66,.12,-.99,.12,-1.83,.12],["c",-1.05,0,-1.71,-.06,-2.61,-.3],["c",-4.02,-.99,-7.11,-4.35,-7.8,-8.46],["c",-.12,-.66,-.12,-.99,-.12,-1.83],["c",0,-.84,0,-1.14,.15,-1.92],["c",.36,-2.28,1.41,-4.62,3.3,-7.29],["l",2.79,-3.6],["c",.54,-.66,.96,-1.2,.96,-1.23],["c",0,-.03,-.09,-.33,-.18,-.69],["c",-.96,-3.21,-1.41,-5.28,-1.59,-7.68],["c",-.12,-1.38,-.15,-3.09,-.06,-3.96],["c",.33,-2.67,1.38,-5.07,3.12,-7.08],["c",.36,-.42,.99,-1.05,1.17,-1.14],["z"],["m",2.01,4.71],["c",-.15,-.3,-.3,-.54,-.3,-.54],["c",-.03,0,-.18,.09,-.3,.21],["c",-2.4,1.74,-3.87,4.2,-4.26,7.11],["c",-.06,.54,-.06,1.41,-.03,1.89],["c",.09,1.29,.48,3.12,1.08,5.22],["c",.15,.42,.24,.78,.24,.81],["c",0,.03,.84,-1.11,1.23,-1.68],["c",1.89,-2.73,2.88,-5.07,3.15,-7.53],["c",.09,-.57,.12,-1.74,.06,-2.37],["c",-.09,-1.23,-.27,-1.92,-.87,-3.12],["z"],["m",-2.94,20.7],["c",-.21,-.72,-.39,-1.32,-.42,-1.32],["c",0,0,-1.2,1.47,-1.86,2.37],["c",-2.79,3.63,-4.02,6.3,-4.35,9.3],["c",-.03,.21,-.03,.69,-.03,1.08],["c",0,.69,0,.75,.06,1.11],["c",.12,.54,.27,.99,.51,1.47],["c",.69,1.38,1.83,2.55,3.42,3.42],["c",.96,.54,2.07,.9,3.21,1.08],["c",.78,.12,2.04,.12,2.94,-.03],["c",.51,-.06,.45,-.03,.42,-.3],["c",-.24,-3.33,-.72,-6.33,-1.62,-10.08],["c",-.09,-.39,-.18,-.75,-.18,-.78],["c",-.03,-.03,-.42,0,-.81,.09],["c",-.9,.18,-1.65,.57,-2.22,1.14],["c",-.72,.72,-1.08,1.65,-1.05,2.64],["c",.06,.96,.48,1.83,1.23,2.58],["c",.36,.36,.72,.63,1.17,.9],["c",.33,.18,.36,.21,.42,.33],["c",.18,.42,-.18,.9,-.6,.87],["c",-.18,-.03,-.84,-.36,-1.26,-.63],["c",-.78,-.51,-1.38,-1.11,-1.86,-1.83],["c",-1.77,-2.7,-.99,-6.42,1.71,-8.19],["c",.3,-.21,.81,-.48,1.17,-.63],["c",.3,-.09,1.02,-.3,1.14,-.3],["c",.06,0,.09,0,.09,-.03],["c",.03,-.03,-.51,-1.92,-1.23,-4.26],["z"],["m",3.78,7.41],["c",-.18,-.03,-.36,-.06,-.39,-.06],["c",-.03,0,0,.21,.18,1.02],["c",.75,3.18,1.26,6.3,1.5,9.09],["c",.06,.72,0,.69,.51,.42],["c",.78,-.36,1.44,-.96,1.98,-1.77],["c",1.08,-1.62,1.2,-3.69,.3,-5.55],["c",-.81,-1.62,-2.31,-2.79,-4.08,-3.15],["z"]],w:19.051,h:57.057},"clefs.perc":{d:[["M",5.07,-7.44],["l",.09,-.06],["l",1.53,0],["l",1.53,0],["l",.09,.06],["l",.06,.09],["l",0,7.35],["l",0,7.32],["l",-.06,.09],["l",-.09,.06],["l",-1.53,0],["l",-1.53,0],["l",-.09,-.06],["l",-.06,-.09],["l",0,-7.32],["l",0,-7.35],["z"],["m",6.63,0],["l",.09,-.06],["l",1.53,0],["l",1.53,0],["l",.09,.06],["l",.06,.09],["l",0,7.35],["l",0,7.32],["l",-.06,.09],["l",-.09,.06],["l",-1.53,0],["l",-1.53,0],["l",-.09,-.06],["l",-.06,-.09],["l",0,-7.32],["l",0,-7.35],["z"]],w:9.99,h:14.97},"timesig.common":{d:[["M",6.66,-7.83],["c",.72,-.06,1.41,-.03,1.98,.09],["c",1.2,.27,2.34,.96,3.09,1.92],["c",.63,.81,1.08,1.86,1.14,2.73],["c",.06,1.02,-.51,1.92,-1.44,2.22],["c",-.24,.09,-.3,.09,-.63,.09],["c",-.33,0,-.42,0,-.63,-.06],["c",-.66,-.24,-1.14,-.63,-1.41,-1.2],["c",-.15,-.3,-.21,-.51,-.24,-.9],["c",-.06,-1.08,.57,-2.04,1.56,-2.37],["c",.18,-.06,.27,-.06,.63,-.06],["l",.45,0],["c",.06,.03,.09,.03,.09,0],["c",0,0,-.09,-.12,-.24,-.27],["c",-1.02,-1.11,-2.55,-1.68,-4.08,-1.5],["c",-1.29,.15,-2.04,.69,-2.4,1.74],["c",-.36,.93,-.42,1.89,-.42,5.37],["c",0,2.97,.06,3.96,.24,4.77],["c",.24,1.08,.63,1.68,1.41,2.07],["c",.81,.39,2.16,.45,3.18,.09],["c",1.29,-.45,2.37,-1.53,3.03,-2.97],["c",.15,-.33,.33,-.87,.39,-1.17],["c",.09,-.24,.15,-.36,.3,-.39],["c",.21,-.03,.42,.15,.39,.36],["c",-.06,.39,-.42,1.38,-.69,1.89],["c",-.96,1.8,-2.49,2.94,-4.23,3.18],["c",-.99,.12,-2.58,-.06,-3.63,-.45],["c",-.96,-.36,-1.71,-.84,-2.4,-1.5],["c",-1.11,-1.11,-1.8,-2.61,-2.04,-4.56],["c",-.06,-.6,-.06,-2.01,0,-2.61],["c",.24,-1.95,.9,-3.45,2.01,-4.56],["c",.69,-.66,1.44,-1.11,2.37,-1.47],["c",.63,-.24,1.47,-.42,2.22,-.48],["z"]],w:13.038,h:15.689},"timesig.cut":{d:[["M",6.24,-10.44],["c",.09,-.06,.09,-.06,.48,-.06],["c",.36,0,.36,0,.45,.06],["l",.06,.09],["l",0,1.23],["l",0,1.26],["l",.27,0],["c",1.26,0,2.49,.45,3.48,1.29],["c",1.05,.87,1.8,2.28,1.89,3.48],["c",.06,1.02,-.51,1.92,-1.44,2.22],["c",-.24,.09,-.3,.09,-.63,.09],["c",-.33,0,-.42,0,-.63,-.06],["c",-.66,-.24,-1.14,-.63,-1.41,-1.2],["c",-.15,-.3,-.21,-.51,-.24,-.9],["c",-.06,-1.08,.57,-2.04,1.56,-2.37],["c",.18,-.06,.27,-.06,.63,-.06],["l",.45,0],["c",.06,.03,.09,.03,.09,0],["c",0,-.03,-.45,-.51,-.66,-.69],["c",-.87,-.69,-1.83,-1.05,-2.94,-1.11],["l",-.42,0],["l",0,7.17],["l",0,7.14],["l",.42,0],["c",.69,-.03,1.23,-.18,1.86,-.51],["c",1.05,-.51,1.89,-1.47,2.46,-2.7],["c",.15,-.33,.33,-.87,.39,-1.17],["c",.09,-.24,.15,-.36,.3,-.39],["c",.21,-.03,.42,.15,.39,.36],["c",-.03,.24,-.21,.78,-.39,1.2],["c",-.96,2.37,-2.94,3.9,-5.13,3.9],["l",-.3,0],["l",0,1.26],["l",0,1.23],["l",-.06,.09],["c",-.09,.06,-.09,.06,-.45,.06],["c",-.39,0,-.39,0,-.48,-.06],["l",-.06,-.09],["l",0,-1.29],["l",0,-1.29],["l",-.21,-.03],["c",-1.23,-.21,-2.31,-.63,-3.21,-1.29],["c",-.15,-.09,-.45,-.36,-.66,-.57],["c",-1.11,-1.11,-1.8,-2.61,-2.04,-4.56],["c",-.06,-.6,-.06,-2.01,0,-2.61],["c",.24,-1.95,.93,-3.45,2.04,-4.59],["c",.42,-.39,.78,-.66,1.26,-.93],["c",.75,-.45,1.65,-.75,2.61,-.9],["l",.21,-.03],["l",0,-1.29],["l",0,-1.29],["z"],["m",-.06,10.44],["c",0,-5.58,0,-6.99,-.03,-6.99],["c",-.15,0,-.63,.27,-.87,.45],["c",-.45,.36,-.75,.93,-.93,1.77],["c",-.18,.81,-.24,1.8,-.24,4.74],["c",0,2.97,.06,3.96,.24,4.77],["c",.24,1.08,.66,1.68,1.41,2.07],["c",.12,.06,.3,.12,.33,.15],["l",.09,0],["l",0,-6.96],["z"]],w:13.038,h:20.97},f:{d:[["M",9.93,-14.28],["c",1.53,-.18,2.88,.45,3.12,1.5],["c",.12,.51,0,1.32,-.27,1.86],["c",-.15,.3,-.42,.57,-.63,.69],["c",-.69,.36,-1.56,.03,-1.83,-.69],["c",-.09,-.24,-.09,-.69,0,-.87],["c",.06,-.12,.21,-.24,.45,-.42],["c",.42,-.24,.57,-.45,.6,-.72],["c",.03,-.33,-.09,-.39,-.63,-.42],["c",-.3,0,-.45,0,-.6,.03],["c",-.81,.21,-1.35,.93,-1.74,2.46],["c",-.06,.27,-.48,2.25,-.48,2.31],["c",0,.03,.39,.03,.9,.03],["c",.72,0,.9,0,.99,.06],["c",.42,.15,.45,.72,.03,.9],["c",-.12,.06,-.24,.06,-1.17,.06],["l",-1.05,0],["l",-.78,2.55],["c",-.45,1.41,-.87,2.79,-.96,3.06],["c",-.87,2.37,-2.37,4.74,-3.78,5.91],["c",-1.05,.9,-2.04,1.23,-3.09,1.08],["c",-1.11,-.18,-1.89,-.78,-2.04,-1.59],["c",-.12,-.66,.15,-1.71,.54,-2.19],["c",.69,-.75,1.86,-.54,2.22,.39],["c",.06,.15,.09,.27,.09,.48],["c",0,.24,-.03,.27,-.12,.42],["c",-.03,.09,-.15,.18,-.27,.27],["c",-.09,.06,-.27,.21,-.36,.27],["c",-.24,.18,-.36,.36,-.39,.6],["c",-.03,.33,.09,.39,.63,.42],["c",.42,0,.63,-.03,.9,-.15],["c",.6,-.3,.96,-.96,1.38,-2.64],["c",.09,-.42,.63,-2.55,1.17,-4.77],["l",1.02,-4.08],["c",0,-.03,-.36,-.03,-.81,-.03],["c",-.72,0,-.81,0,-.93,-.06],["c",-.42,-.18,-.39,-.75,.03,-.9],["c",.09,-.06,.27,-.06,1.05,-.06],["l",.96,0],["l",0,-.09],["c",.06,-.18,.3,-.72,.51,-1.17],["c",1.2,-2.46,3.3,-4.23,5.34,-4.5],["z"]],w:16.155,h:19.445},m:{d:[["M",2.79,-8.91],["c",.09,0,.3,-.03,.45,-.03],["c",.24,.03,.3,.03,.45,.12],["c",.36,.15,.63,.54,.75,1.02],["l",.03,.21],["l",.33,-.3],["c",.69,-.69,1.38,-1.02,2.07,-1.02],["c",.27,0,.33,0,.48,.06],["c",.21,.09,.48,.36,.63,.6],["c",.03,.09,.12,.27,.18,.42],["c",.03,.15,.09,.27,.12,.27],["c",0,0,.09,-.09,.18,-.21],["c",.33,-.39,.87,-.81,1.29,-.99],["c",.78,-.33,1.47,-.21,2.01,.33],["c",.3,.33,.48,.69,.6,1.14],["c",.09,.42,.06,.54,-.54,3.06],["c",-.33,1.29,-.57,2.4,-.57,2.43],["c",0,.12,.09,.21,.21,.21],["c",.24,0,.75,-.3,1.2,-.72],["c",.45,-.39,.6,-.45,.78,-.27],["c",.18,.18,.09,.36,-.45,.87],["c",-1.05,.96,-1.83,1.47,-2.58,1.71],["c",-.93,.33,-1.53,.21,-1.8,-.33],["c",-.06,-.15,-.06,-.21,-.06,-.45],["c",0,-.24,.03,-.48,.6,-2.82],["c",.42,-1.71,.6,-2.64,.63,-2.79],["c",.03,-.57,-.3,-.75,-.84,-.48],["c",-.24,.12,-.54,.39,-.66,.63],["c",-.03,.09,-.42,1.38,-.9,3],["c",-.9,3.15,-.84,3,-1.14,3.15],["l",-.15,.09],["l",-.78,0],["c",-.6,0,-.78,0,-.84,-.06],["c",-.09,-.03,-.18,-.18,-.18,-.27],["c",0,-.03,.36,-1.38,.84,-2.97],["c",.57,-2.04,.81,-2.97,.84,-3.12],["c",.03,-.54,-.3,-.72,-.84,-.45],["c",-.24,.12,-.57,.42,-.66,.63],["c",-.06,.09,-.51,1.44,-1.05,2.97],["c",-.51,1.56,-.99,2.85,-.99,2.91],["c",-.06,.12,-.21,.24,-.36,.3],["c",-.12,.06,-.21,.06,-.9,.06],["c",-.6,0,-.78,0,-.84,-.06],["c",-.09,-.03,-.18,-.18,-.18,-.27],["c",0,-.03,.45,-1.38,.99,-2.97],["c",1.05,-3.18,1.05,-3.18,.93,-3.45],["c",-.12,-.27,-.39,-.3,-.72,-.15],["c",-.54,.27,-1.14,1.17,-1.56,2.4],["c",-.06,.15,-.15,.3,-.18,.36],["c",-.21,.21,-.57,.27,-.72,.09],["c",-.09,-.09,-.06,-.21,.06,-.63],["c",.48,-1.26,1.26,-2.46,2.01,-3.21],["c",.57,-.54,1.2,-.87,1.83,-1.02],["z"]],w:14.687,h:9.126},p:{d:[["M",1.92,-8.7],["c",.27,-.09,.81,-.06,1.11,.03],["c",.54,.18,.93,.51,1.17,.99],["c",.09,.15,.15,.33,.18,.36],["l",0,.12],["l",.3,-.27],["c",.66,-.6,1.35,-1.02,2.13,-1.2],["c",.21,-.06,.33,-.06,.78,-.06],["c",.45,0,.51,0,.84,.09],["c",1.29,.33,2.07,1.32,2.25,2.79],["c",.09,.81,-.09,2.01,-.45,2.79],["c",-.54,1.26,-1.86,2.55,-3.18,3.03],["c",-.45,.18,-.81,.24,-1.29,.24],["c",-.69,-.03,-1.35,-.18,-1.86,-.45],["c",-.3,-.15,-.51,-.18,-.69,-.09],["c",-.09,.03,-.18,.09,-.18,.12],["c",-.09,.12,-1.05,2.94,-1.05,3.06],["c",0,.24,.18,.48,.51,.63],["c",.18,.06,.54,.15,.75,.15],["c",.21,0,.36,.06,.42,.18],["c",.12,.18,.06,.42,-.12,.54],["c",-.09,.03,-.15,.03,-.78,0],["c",-1.98,-.15,-3.81,-.15,-5.79,0],["c",-.63,.03,-.69,.03,-.78,0],["c",-.24,-.15,-.24,-.57,.03,-.66],["c",.06,-.03,.48,-.09,.99,-.12],["c",.87,-.06,1.11,-.09,1.35,-.21],["c",.18,-.06,.33,-.18,.39,-.3],["c",.06,-.12,3.24,-9.42,3.27,-9.6],["c",.06,-.33,.03,-.57,-.15,-.69],["c",-.09,-.06,-.12,-.06,-.3,-.06],["c",-.69,.06,-1.53,1.02,-2.28,2.61],["c",-.09,.21,-.21,.45,-.27,.51],["c",-.09,.12,-.33,.24,-.48,.24],["c",-.18,0,-.36,-.15,-.36,-.3],["c",0,-.24,.78,-1.83,1.26,-2.55],["c",.72,-1.11,1.47,-1.74,2.28,-1.92],["z"],["m",5.37,1.47],["c",-.27,-.12,-.75,-.03,-1.14,.21],["c",-.75,.48,-1.47,1.68,-1.89,3.15],["c",-.45,1.47,-.42,2.34,0,2.7],["c",.45,.39,1.26,.21,1.83,-.36],["c",.51,-.51,.99,-1.68,1.38,-3.27],["c",.3,-1.17,.33,-1.74,.15,-2.13],["c",-.09,-.15,-.15,-.21,-.33,-.3],["z"]],w:14.689,h:13.127},r:{d:[["M",6.33,-9.12],["c",.27,-.03,.93,0,1.2,.06],["c",.84,.21,1.23,.81,1.02,1.53],["c",-.24,.75,-.9,1.17,-1.56,.96],["c",-.33,-.09,-.51,-.3,-.66,-.75],["c",-.03,-.12,-.09,-.24,-.12,-.3],["c",-.09,-.15,-.3,-.24,-.48,-.24],["c",-.57,0,-1.38,.54,-1.65,1.08],["c",-.06,.15,-.33,1.17,-.9,3.27],["c",-.57,2.31,-.81,3.12,-.87,3.21],["c",-.03,.06,-.12,.15,-.18,.21],["l",-.12,.06],["l",-.81,.03],["c",-.69,0,-.81,0,-.9,-.03],["c",-.09,-.06,-.18,-.21,-.18,-.3],["c",0,-.06,.39,-1.62,.9,-3.51],["c",.84,-3.24,.87,-3.45,.87,-3.72],["c",0,-.21,0,-.27,-.03,-.36],["c",-.12,-.15,-.21,-.24,-.42,-.24],["c",-.24,0,-.45,.15,-.78,.42],["c",-.33,.36,-.45,.54,-.72,1.14],["c",-.03,.12,-.21,.24,-.36,.27],["c",-.12,0,-.15,0,-.24,-.06],["c",-.18,-.12,-.18,-.21,-.06,-.54],["c",.21,-.57,.42,-.93,.78,-1.32],["c",.54,-.51,1.2,-.81,1.95,-.87],["c",.81,-.03,1.53,.3,1.92,.87],["l",.12,.18],["l",.09,-.09],["c",.57,-.45,1.41,-.84,2.19,-.96],["z"]],w:9.41,h:9.132},s:{d:[["M",4.47,-8.73],["c",.09,0,.36,-.03,.57,-.03],["c",.75,.03,1.29,.24,1.71,.63],["c",.51,.54,.66,1.26,.36,1.83],["c",-.24,.42,-.63,.57,-1.11,.42],["c",-.33,-.09,-.6,-.36,-.6,-.57],["c",0,-.03,.06,-.21,.15,-.39],["c",.12,-.21,.15,-.33,.18,-.48],["c",0,-.24,-.06,-.48,-.15,-.6],["c",-.15,-.21,-.42,-.24,-.75,-.15],["c",-.27,.06,-.48,.18,-.69,.36],["c",-.39,.39,-.51,.96,-.33,1.38],["c",.09,.21,.42,.51,.78,.72],["c",1.11,.69,1.59,1.11,1.89,1.68],["c",.21,.39,.24,.78,.15,1.29],["c",-.18,1.2,-1.17,2.16,-2.52,2.52],["c",-1.02,.24,-1.95,.12,-2.7,-.42],["c",-.72,-.51,-.99,-1.47,-.6,-2.19],["c",.24,-.48,.72,-.63,1.17,-.42],["c",.33,.18,.54,.45,.57,.81],["c",0,.21,-.03,.3,-.33,.51],["c",-.33,.24,-.39,.42,-.27,.69],["c",.06,.15,.21,.27,.45,.33],["c",.3,.09,.87,.09,1.2,0],["c",.75,-.21,1.23,-.72,1.29,-1.35],["c",.03,-.42,-.15,-.81,-.54,-1.2],["c",-.24,-.24,-.48,-.42,-1.41,-1.02],["c",-.69,-.42,-1.05,-.93,-1.05,-1.47],["c",0,-.39,.12,-.87,.3,-1.23],["c",.27,-.57,.78,-1.05,1.38,-1.35],["c",.24,-.12,.63,-.27,.9,-.3],["z"]],w:6.632,h:8.758},z:{d:[["M",2.64,-7.95],["c",.36,-.09,.81,-.03,1.71,.27],["c",.78,.21,.96,.27,1.74,.3],["c",.87,.06,1.02,.03,1.38,-.21],["c",.21,-.15,.33,-.15,.48,-.06],["c",.15,.09,.21,.3,.15,.45],["c",-.03,.06,-1.26,1.26,-2.76,2.67],["l",-2.73,2.55],["l",.54,.03],["c",.54,.03,.72,.03,2.01,.15],["c",.36,.03,.9,.06,1.2,.09],["c",.66,0,.81,-.03,1.02,-.24],["c",.3,-.3,.39,-.72,.27,-1.23],["c",-.06,-.27,-.06,-.27,-.03,-.39],["c",.15,-.3,.54,-.27,.69,.03],["c",.15,.33,.27,1.02,.27,1.5],["c",0,1.47,-1.11,2.7,-2.52,2.79],["c",-.57,.03,-1.02,-.09,-2.01,-.51],["c",-1.02,-.42,-1.23,-.48,-2.13,-.54],["c",-.81,-.06,-.96,-.03,-1.26,.18],["c",-.12,.06,-.24,.12,-.27,.12],["c",-.27,0,-.45,-.3,-.36,-.51],["c",.03,-.06,1.32,-1.32,2.91,-2.79],["l",2.88,-2.73],["c",-.03,0,-.21,.03,-.42,.06],["c",-.21,.03,-.78,.09,-1.23,.12],["c",-1.11,.12,-1.23,.15,-1.95,.27],["c",-.72,.15,-1.17,.18,-1.29,.09],["c",-.27,-.18,-.21,-.75,.12,-1.26],["c",.39,-.6,.93,-1.02,1.59,-1.2],["z"]],w:8.573,h:8.743},"+":{d:[["M",3.48,-9.3],["c",.18,-.09,.36,-.09,.54,0],["c",.18,.09,.24,.15,.33,.3],["l",.06,.15],["l",0,1.29],["l",0,1.29],["l",1.29,0],["c",1.23,0,1.29,0,1.41,.06],["c",.06,.03,.15,.09,.18,.12],["c",.12,.09,.21,.33,.21,.48],["c",0,.15,-.09,.39,-.21,.48],["c",-.03,.03,-.12,.09,-.18,.12],["c",-.12,.06,-.18,.06,-1.41,.06],["l",-1.29,0],["l",0,1.29],["c",0,1.23,0,1.29,-.06,1.41],["c",-.09,.18,-.15,.24,-.3,.33],["c",-.21,.09,-.39,.09,-.57,0],["c",-.18,-.09,-.24,-.15,-.33,-.33],["c",-.06,-.12,-.06,-.18,-.06,-1.41],["l",0,-1.29],["l",-1.29,0],["c",-1.23,0,-1.29,0,-1.41,-.06],["c",-.18,-.09,-.24,-.15,-.33,-.33],["c",-.09,-.18,-.09,-.36,0,-.54],["c",.09,-.18,.15,-.24,.33,-.33],["l",.15,-.06],["l",1.26,0],["l",1.29,0],["l",0,-1.29],["c",0,-1.23,0,-1.29,.06,-1.41],["c",.09,-.18,.15,-.24,.33,-.33],["z"]],w:7.507,h:7.515},",":{d:[["M",1.32,-3.36],["c",.57,-.15,1.17,.03,1.59,.45],["c",.45,.45,.6,.96,.51,1.89],["c",-.09,1.23,-.42,2.46,-.99,3.93],["c",-.3,.72,-.72,1.62,-.78,1.68],["c",-.18,.21,-.51,.18,-.66,-.06],["c",-.03,-.06,-.06,-.15,-.06,-.18],["c",0,-.06,.12,-.33,.24,-.63],["c",.84,-1.8,1.02,-2.61,.69,-3.24],["c",-.12,-.24,-.27,-.36,-.75,-.6],["c",-.36,-.15,-.42,-.21,-.6,-.39],["c",-.69,-.69,-.69,-1.71,0,-2.4],["c",.21,-.21,.51,-.39,.81,-.45],["z"]],w:3.452,h:8.143},"-":{d:[["M",.18,-5.34],["c",.09,-.06,.15,-.06,2.31,-.06],["c",2.46,0,2.37,0,2.46,.21],["c",.12,.21,.03,.42,-.15,.54],["c",-.09,.06,-.15,.06,-2.28,.06],["c",-2.16,0,-2.22,0,-2.31,-.06],["c",-.27,-.15,-.27,-.54,-.03,-.69],["z"]],w:5.001,h:.81},".":{d:[["M",1.32,-3.36],["c",1.05,-.27,2.1,.57,2.1,1.65],["c",0,1.08,-1.05,1.92,-2.1,1.65],["c",-.9,-.21,-1.5,-1.14,-1.26,-2.04],["c",.12,-.63,.63,-1.11,1.26,-1.26],["z"]],w:3.413,h:3.402},"scripts.wedge":{d:[["M",-3.66,-7.44],["c",.06,-.09,0,-.09,.81,.03],["c",1.86,.3,3.84,.3,5.73,0],["c",.78,-.12,.72,-.12,.78,-.03],["c",.15,.15,.12,.24,-.24,.6],["c",-.93,.93,-1.98,2.76,-2.67,4.62],["c",-.3,.78,-.51,1.71,-.51,2.13],["c",0,.15,0,.18,-.06,.27],["c",-.12,.09,-.24,.09,-.36,0],["c",-.06,-.09,-.06,-.12,-.06,-.27],["c",0,-.42,-.21,-1.35,-.51,-2.13],["c",-.69,-1.86,-1.74,-3.69,-2.67,-4.62],["c",-.36,-.36,-.39,-.45,-.24,-.6],["z"]],w:7.49,h:7.752},"scripts.thumb":{d:[["M",-.54,-3.69],["c",.15,-.03,.36,-.06,.51,-.06],["c",1.44,0,2.58,1.11,2.94,2.85],["c",.09,.48,.09,1.32,0,1.8],["c",-.27,1.41,-1.08,2.43,-2.16,2.73],["l",-.18,.06],["l",0,.12],["c",.03,.06,.06,.45,.09,.87],["c",.03,.57,.03,.78,0,.84],["c",-.09,.27,-.39,.48,-.66,.48],["c",-.27,0,-.57,-.21,-.66,-.48],["c",-.03,-.06,-.03,-.27,0,-.84],["c",.03,-.42,.06,-.81,.09,-.87],["l",0,-.12],["l",-.18,-.06],["c",-1.08,-.3,-1.89,-1.32,-2.16,-2.73],["c",-.09,-.48,-.09,-1.32,0,-1.8],["c",.15,-.84,.51,-1.53,1.02,-2.04],["c",.39,-.39,.84,-.63,1.35,-.75],["z"],["m",1.05,.9],["c",-.15,-.09,-.21,-.09,-.45,-.12],["c",-.15,0,-.3,.03,-.39,.03],["c",-.57,.18,-.9,.72,-1.08,1.74],["c",-.06,.48,-.06,1.8,0,2.28],["c",.15,.9,.42,1.44,.9,1.65],["c",.18,.09,.21,.09,.51,.09],["c",.3,0,.33,0,.51,-.09],["c",.48,-.21,.75,-.75,.9,-1.65],["c",.03,-.27,.03,-.54,.03,-1.14],["c",0,-.6,0,-.87,-.03,-1.14],["c",-.15,-.9,-.45,-1.44,-.9,-1.65],["z"]],w:5.955,h:9.75},"scripts.open":{d:[["M",-.54,-3.69],["c",.15,-.03,.36,-.06,.51,-.06],["c",1.44,0,2.58,1.11,2.94,2.85],["c",.09,.48,.09,1.32,0,1.8],["c",-.33,1.74,-1.47,2.85,-2.91,2.85],["c",-1.44,0,-2.58,-1.11,-2.91,-2.85],["c",-.09,-.48,-.09,-1.32,0,-1.8],["c",.15,-.84,.51,-1.53,1.02,-2.04],["c",.39,-.39,.84,-.63,1.35,-.75],["z"],["m",1.11,.9],["c",-.21,-.09,-.27,-.09,-.51,-.12],["c",-.3,0,-.42,.03,-.66,.15],["c",-.24,.12,-.51,.39,-.66,.63],["c",-.54,.93,-.63,2.64,-.21,3.81],["c",.21,.54,.51,.9,.93,1.11],["c",.21,.09,.24,.09,.54,.09],["c",.3,0,.33,0,.54,-.09],["c",.42,-.21,.72,-.57,.93,-1.11],["c",.36,-.99,.36,-2.37,0,-3.36],["c",-.21,-.54,-.51,-.9,-.9,-1.11],["z"]],w:5.955,h:7.5},"scripts.longphrase":{d:[["M",1.47,-15.09],["c",.36,-.09,.66,-.18,.69,-.18],["c",.06,0,.06,.54,.06,11.25],["l",0,11.25],["l",-.63,.15],["c",-.66,.18,-1.44,.39,-1.5,.39],["c",-.03,0,-.03,-3.39,-.03,-11.25],["l",0,-11.25],["l",.36,-.09],["c",.21,-.06,.66,-.18,1.05,-.27],["z"]],w:2.16,h:23.04},"scripts.mediumphrase":{d:[["M",1.47,-7.59],["c",.36,-.09,.66,-.18,.69,-.18],["c",.06,0,.06,.39,.06,7.5],["l",0,7.5],["l",-.63,.15],["c",-.66,.18,-1.44,.39,-1.5,.39],["c",-.03,0,-.03,-2.28,-.03,-7.5],["l",0,-7.5],["l",.36,-.09],["c",.21,-.06,.66,-.18,1.05,-.27],["z"]],w:2.16,h:15.54},"scripts.shortphrase":{d:[["M",1.47,-7.59],["c",.36,-.09,.66,-.18,.69,-.18],["c",.06,0,.06,.21,.06,3.75],["l",0,3.75],["l",-.42,.09],["c",-.57,.18,-1.65,.45,-1.71,.45],["c",-.03,0,-.03,-.72,-.03,-3.75],["l",0,-3.75],["l",.36,-.09],["c",.21,-.06,.66,-.18,1.05,-.27],["z"]],w:2.16,h:8.04},"scripts.snap":{d:[["M",4.5,-3.39],["c",.36,-.03,.96,-.03,1.35,0],["c",1.56,.15,3.15,.9,4.2,2.01],["c",.24,.27,.33,.42,.33,.6],["c",0,.27,.03,.24,-2.46,2.22],["c",-1.29,1.02,-2.4,1.86,-2.49,1.92],["c",-.18,.09,-.3,.09,-.48,0],["c",-.09,-.06,-1.2,-.9,-2.49,-1.92],["c",-2.49,-1.98,-2.46,-1.95,-2.46,-2.22],["c",0,-.18,.09,-.33,.33,-.6],["c",1.05,-1.08,2.64,-1.86,4.17,-2.01],["z"],["m",1.29,1.17],["c",-1.47,-.15,-2.97,.3,-4.14,1.2],["l",-.18,.15],["l",.06,.09],["c",.15,.12,3.63,2.85,3.66,2.85],["c",.03,0,3.51,-2.73,3.66,-2.85],["l",.06,-.09],["l",-.18,-.15],["c",-.84,-.66,-1.89,-1.08,-2.94,-1.2],["z"]],w:10.38,h:6.84}};glyphs["noteheads.slash.whole"]={d:[["M",5,-5],["l",1,1],["l",-5,5],["l",-1,-1],["z"],["m",4,6],["l",-5,-5],["l",2,-2],["l",5,5],["z"],["m",0,-2],["l",1,1],["l",-5,5],["l",-1,-1],["z"],["m",-4,6],["l",-5,-5],["l",2,-2],["l",5,5],["z"]],w:10.81,h:15.63},glyphs["noteheads.slash.quarter"]={d:[["M",9,-6],["l",0,4],["l",-9,9],["l",0,-4],["z"]],w:9,h:9},glyphs["noteheads.harmonic.quarter"]={d:[["M",3.63,-4.02],["c",.09,-.06,.18,-.09,.24,-.03],["c",.03,.03,.87,.93,1.83,2.01],["c",1.5,1.65,1.8,1.98,1.8,2.04],["c",0,.06,-.3,.39,-1.8,2.04],["c",-.96,1.08,-1.8,1.98,-1.83,2.01],["c",-.06,.06,-.15,.03,-.24,-.03],["c",-.12,-.09,-3.54,-3.84,-3.6,-3.93],["c",-.03,-.03,-.03,-.09,-.03,-.15],["c",.03,-.06,3.45,-3.84,3.63,-3.96],["z"]],w:7.5,h:8.165},this.printSymbol=function(x,y,symb,paper,klass){if(!glyphs[symb])return null;var pathArray=this.pathClone(glyphs[symb].d);return pathArray[0][1]+=x,pathArray[0][2]+=y,paper.path().attr({path:pathArray,stroke:"none",fill:"#000000",class:klass})},this.getPathForSymbol=function(x,y,symb,scalex,scaley){if(scalex=scalex||1,scaley=scaley||1,!glyphs[symb])return null;var pathArray=this.pathClone(glyphs[symb].d);return 1===scalex&&1===scaley||this.pathScale(pathArray,scalex,scaley),pathArray[0][1]+=x,pathArray[0][2]+=y,pathArray},this.getSymbolWidth=function(symbol){return glyphs[symbol]?glyphs[symbol].w:0},this.getSymbolHeight=function(symbol){return glyphs[symbol]?glyphs[symbol].h:0},this.symbolHeightInPitches=function(symbol){return this.getSymbolHeight(symbol)/ABCJS.write.spacing.STEP},this.getSymbolAlign=function(symbol){return"scripts"===symbol.substring(0,7)&&"scripts.roll"!==symbol?"center":"left"},this.pathClone=function(pathArray){for(var res=[],i=0,ii=pathArray.length;i<ii;i++){res[i]=[];for(var j=0,jj=pathArray[i].length;j<jj;j++)res[i][j]=pathArray[i][j]}return res},this.pathScale=function(pathArray,kx,ky){for(var i=0,ii=pathArray.length;i<ii;i++){var j,jj,p=pathArray[i];for(j=1,jj=p.length;j<jj;j++)p[j]*=j%2?kx:ky}},this.getYCorr=function(symbol){switch(symbol){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"+":return-2;case"timesig.common":case"timesig.cut":return 0;case"flags.d32nd":return-1;case"flags.d64th":return-2;case"flags.u32nd":return 1;case"flags.u64th":return 3;case"rests.whole":return 1;case"rests.half":return-1;case"rests.8th":return-1;case"rests.quarter":return-1;case"rests.16th":return-1;case"rests.32nd":return-1;case"rests.64th":return-1;case"f":case"m":case"p":case"s":case"z":return-4;case"scripts.trill":case"scripts.upbow":case"scripts.downbow":return-2;case"scripts.ufermata":case"scripts.wedge":case"scripts.roll":case"scripts.shortphrase":case"scripts.longphrase":return-1;case"scripts.dfermata":return 1;default:return 0}}},ABCJS.write.glyphs=new ABCJS.write.Glyphs,window.ABCJS||(window.ABCJS={}),window.ABCJS.write||(window.ABCJS.write={}),ABCJS.write.RelativeElement=function(c,dx,w,pitch,opt){opt=opt||{},this.x=0,this.c=c,this.dx=dx,this.w=w,this.pitch=pitch,this.scalex=opt.scalex||1,this.scaley=opt.scaley||1,this.type=opt.type||"symbol",this.pitch2=opt.pitch2,this.linewidth=opt.linewidth,this.klass=opt.klass,this.top=pitch,void 0!==this.pitch2&&this.pitch2>this.top&&(this.top=this.pitch2),this.bottom=pitch,void 0!==this.pitch2&&this.pitch2<this.bottom&&(this.bottom=this.pitch2), opt.thickness&&(this.top+=opt.thickness/2,this.bottom-=opt.thickness/2),opt.stemHeight&&(opt.stemHeight>0?this.top+=opt.stemHeight:this.bottom+=opt.stemHeight);var height=opt.height?opt.height:4;switch(this.centerVertically=!1,this.type){case"debug":this.chordHeightAbove=height;break;case"lyric":opt.position&&"below"===opt.position?this.lyricHeightBelow=height:this.lyricHeightAbove=height;break;case"chord":opt.position&&"below"===opt.position?this.chordHeightBelow=height:this.chordHeightAbove=height;break;case"text":void 0===this.pitch?opt.position&&"below"===opt.position?this.chordHeightBelow=height:this.chordHeightAbove=height:this.centerVertically=!0;break;case"part":this.partHeightAbove=height}},ABCJS.write.RelativeElement.prototype.setX=function(x){this.x=x+this.dx},ABCJS.write.RelativeElement.prototype.draw=function(renderer,bartop){void 0===this.pitch&&window.console.error(this.type+" Relative Element y-coordinate not set.");var y=renderer.calcY(this.pitch);switch(this.type){case"symbol":if(null===this.c)return null;var klass="symbol";this.klass&&(klass+=" "+this.klass),this.graphelem=renderer.printSymbol(this.x,this.pitch,this.c,this.scalex,this.scaley,renderer.addClasses(klass));break;case"debug":this.graphelem=renderer.renderText(this.x,renderer.calcY(15),""+this.c,"debugfont","debug-msg","start");break;case"barNumber":this.graphelem=renderer.renderText(this.x,y,""+this.c,"measurefont","bar-number","middle");break;case"lyric":this.graphelem=renderer.renderText(this.x,y,this.c,"vocalfont","abc-lyric","middle");break;case"chord":this.graphelem=renderer.renderText(this.x,y,this.c,"gchordfont","chord","middle");break;case"decoration":this.graphelem=renderer.renderText(this.x,y,this.c,"annotationfont","annotation","middle",!0);break;case"text":this.graphelem=renderer.renderText(this.x,y,this.c,"annotationfont","annotation","start",this.centerVertically);break;case"part":this.graphelem=renderer.renderText(this.x,y,this.c,"partsfont","part","start");break;case"bar":this.graphelem=renderer.printStem(this.x,this.linewidth,y,bartop?bartop:renderer.calcY(this.pitch2));break;case"stem":this.graphelem=renderer.printStem(this.x,this.linewidth,y,renderer.calcY(this.pitch2));break;case"ledger":this.graphelem=renderer.printStaveLine(this.x,this.x+this.w,this.pitch)}return 1!==this.scalex&&this.graphelem&&this.graphelem.scale(this.scalex,this.scaley,this.x,y),this.graphelem},window.ABCJS||(window.ABCJS={}),window.ABCJS.write||(window.ABCJS.write={}),ABCJS.write.Renderer=function(paper,doRegression){this.paper=paper,this.controller=null,this.space=3*ABCJS.write.spacing.SPACE,this.padding={},this.doRegression=doRegression,this.doRegression&&(this.regressionLines=[]),this.reset()},ABCJS.write.Renderer.prototype.reset=function(){this.paper.clear(),this.y=0,this.abctune=null,this.lastM=null,this.ingroup=!1,this.path=null,this.isPrint=!1,this.initVerticalSpace(),this.doRegression&&(this.regressionLines=[])},ABCJS.write.Renderer.prototype.setPrintMode=function(isPrint){this.isPrint=isPrint},ABCJS.write.Renderer.prototype.setPaperSize=function(maxwidth,scale){var w=(maxwidth+this.padding.right)*scale,h=(this.y+this.padding.bottom)*scale;this.isPrint&&(h=Math.max(h,1056)),this.doRegression&&this.regressionLines.push("PAPER SIZE: ("+w+","+h+")"),this.paper.setSize(w/scale,h/scale);var isIE=!1;isIE?(this.paper.canvas.parentNode.style.width=w+"px",this.paper.canvas.parentNode.style.height=""+h+"px"):this.paper.canvas.parentNode.setAttribute("style","width:"+w+"px"),1!==scale?(this.paper.canvas.style.transform="scale("+scale+","+scale+")",this.paper.canvas.style["-ms-transform"]="scale("+scale+","+scale+")",this.paper.canvas.style["-webkit-transform"]="scale("+scale+","+scale+")",this.paper.canvas.style["transform-origin"]="0 0",this.paper.canvas.style["-ms-transform-origin-x"]="0",this.paper.canvas.style["-ms-transform-origin-y"]="0",this.paper.canvas.style["-webkit-transform-origin-x"]="0",this.paper.canvas.style["-webkit-transform-origin-y"]="0"):(this.paper.canvas.style.transform="",this.paper.canvas.style["-ms-transform"]="",this.paper.canvas.style["-webkit-transform"]=""),this.paper.canvas.parentNode.style.overflow="hidden",this.paper.canvas.parentNode.style.height=""+h+"px"},ABCJS.write.Renderer.prototype.setPaddingOverride=function(params){this.paddingOverride={top:params.paddingtop,bottom:params.paddingbottom,right:params.paddingright,left:params.paddingleft}},ABCJS.write.Renderer.prototype.setPadding=function(abctune){function setPaddingVariable(self,paddingKey,formattingKey,printDefault,screenDefault){void 0!==abctune.formatting[formattingKey]?self.padding[paddingKey]=abctune.formatting[formattingKey]:void 0!==self.paddingOverride[paddingKey]?self.padding[paddingKey]=self.paddingOverride[paddingKey]:self.isPrint?self.padding[paddingKey]=printDefault:self.padding[paddingKey]=screenDefault}setPaddingVariable(this,"top","topmargin",38,15),setPaddingVariable(this,"bottom","botmargin",38,15),setPaddingVariable(this,"left","leftmargin",68,15),setPaddingVariable(this,"right","rightmargin",68,15)},ABCJS.write.Renderer.prototype.adjustNonScaledItems=function(scale){this.padding.top/=scale,this.padding.bottom/=scale,this.padding.left/=scale,this.padding.right/=scale,this.abctune.formatting.headerfont.size/=scale,this.abctune.formatting.footerfont.size/=scale},ABCJS.write.Renderer.prototype.initVerticalSpace=function(){this.spacing={composer:7.56,graceBefore:8.67,graceInside:10.67,graceAfter:16,info:0,lineSkipFactor:1.1,music:7.56,paragraphSkipFactor:.4,parts:11.33,slurHeight:1,staffSeparation:61.33,stemHeight:36.67,subtitle:3.78,systemStaffSeparation:48,text:18.9,title:7.56,top:30.24,vocal:30.67,words:0}},ABCJS.write.Renderer.prototype.setVerticalSpace=function(formatting){void 0!==formatting.staffsep&&(this.spacing.staffSeparation=4*formatting.staffsep/3),void 0!==formatting.composerspace&&(this.spacing.composer=4*formatting.composerspace/3),void 0!==formatting.partsspace&&(this.spacing.parts=4*formatting.partsspace/3),void 0!==formatting.textspace&&(this.spacing.text=4*formatting.textspace/3),void 0!==formatting.musicspace&&(this.spacing.music=4*formatting.musicspace/3),void 0!==formatting.titlespace&&(this.spacing.title=4*formatting.titlespace/3),void 0!==formatting.sysstaffsep&&(this.spacing.systemStaffSeparation=4*formatting.sysstaffsep/3),void 0!==formatting.subtitlespace&&(this.spacing.subtitle=4*formatting.subtitlespace/3),void 0!==formatting.topspace&&(this.spacing.top=4*formatting.topspace/3),void 0!==formatting.vocalspace&&(this.spacing.vocal=4*formatting.vocalspace/3),void 0!==formatting.wordsspace&&(this.spacing.words=4*formatting.wordsspace/3)},ABCJS.write.Renderer.prototype.topMargin=function(abctune){this.moveY(this.padding.top)},ABCJS.write.Renderer.prototype.addMusicPadding=function(){this.moveY(this.spacing.music)},ABCJS.write.Renderer.prototype.addStaffPadding=function(lastStaffGroup,thisStaffGroup){var lastStaff=lastStaffGroup.staffs[lastStaffGroup.staffs.length-1],lastBottomLine=-(lastStaff.bottom-2),nextTopLine=thisStaffGroup.staffs[0].top-10,naturalSeparation=nextTopLine+lastBottomLine,separationInPixels=naturalSeparation*ABCJS.write.spacing.STEP;separationInPixels<this.spacing.staffSeparation&&this.moveY(this.spacing.staffSeparation-separationInPixels)},ABCJS.write.Renderer.prototype.engraveTopText=function(width,abctune){if(abctune.metaText.header&&this.isPrint){var headerTextHeight=this.getTextSize("XXXX","headerfont","header meta-top").height;this.y-=headerTextHeight,this.outputTextIf(this.padding.left,abctune.metaText.header.left,"headerfont","header meta-top",0,null,"start"),this.outputTextIf(this.padding.left+width/2,abctune.metaText.header.center,"headerfont","header meta-top",0,null,"middle"),this.outputTextIf(this.padding.left+width,abctune.metaText.header.right,"headerfont","header meta-top",0,null,"end"),this.y+=headerTextHeight}if(this.isPrint&&this.moveY(this.spacing.top),this.outputTextIf(this.padding.left+width/2,abctune.metaText.title,"titlefont","title meta-top",this.spacing.title,0,"middle"),abctune.lines[0]&&this.outputTextIf(this.padding.left+width/2,abctune.lines[0].subtitle,"subtitlefont","text meta-top",this.spacing.subtitle,0,"middle"),abctune.metaText.rhythm||abctune.metaText.origin||abctune.metaText.composer){this.moveY(this.spacing.composer);var rSpace=this.outputTextIf(this.padding.left,abctune.metaText.rhythm,"infofont","meta-top",0,null,"start"),composerLine="";if(abctune.metaText.composer&&(composerLine+=abctune.metaText.composer),abctune.metaText.origin&&(composerLine+=" ("+abctune.metaText.origin+")"),composerLine.length>0){var space=this.outputTextIf(this.padding.left+width,composerLine,"composerfont","meta-top",0,null,"end");this.moveY(space[1])}else this.moveY(rSpace[1]);this.moveY(-6)}this.outputTextIf(this.padding.left+width,abctune.metaText.author,"composerfont","meta-top",0,0,"end"),this.outputTextIf(this.padding.left,abctune.metaText.partOrder,"partsfont","meta-bottom",0,0,"start")},ABCJS.write.Renderer.prototype.engraveExtraText=function(width,abctune){this.lineNumber=null,this.measureNumber=null,this.voiceNumber=null;var extraText;if(abctune.metaText.unalignedWords){extraText="";for(var j=0;j<abctune.metaText.unalignedWords.length;j++)if("string"==typeof abctune.metaText.unalignedWords[j])extraText+=abctune.metaText.unalignedWords[j]+"\n";else{for(var k=0;k<abctune.metaText.unalignedWords[j].length;k++)extraText+=" FONT "+abctune.metaText.unalignedWords[j][k].text;extraText+="\n"}this.outputTextIf(this.padding.left+ABCJS.write.spacing.INDENT,extraText,"wordsfont","meta-bottom",this.spacing.words,2,"start")}extraText="",abctune.metaText.book&&(extraText+="Book: "+abctune.metaText.book+"\n"),abctune.metaText.source&&(extraText+="Source: "+abctune.metaText.source+"\n"),abctune.metaText.discography&&(extraText+="Discography: "+abctune.metaText.discography+"\n"),abctune.metaText.notes&&(extraText+="Notes: "+abctune.metaText.notes+"\n"),abctune.metaText.transcription&&(extraText+="Transcription: "+abctune.metaText.transcription+"\n"),abctune.metaText.history&&(extraText+="History: "+abctune.metaText.history+"\n"),abctune.metaText["abc-copyright"]&&(extraText+="Copyright: "+abctune.metaText["abc-copyright"]+"\n"),abctune.metaText["abc-creator"]&&(extraText+="Creator: "+abctune.metaText["abc-creator"]+"\n"),abctune.metaText["abc-edited-by"]&&(extraText+="Edited By: "+abctune.metaText["abc-edited-by"]+"\n"),this.outputTextIf(this.padding.left,extraText,"historyfont","meta-bottom",this.spacing.info,0,"start"),abctune.metaText.footer&&this.isPrint&&(this.outputTextIf(this.padding.left,abctune.metaText.footer.left,"footerfont","header meta-bottom",0,null,"start"),this.outputTextIf(this.padding.left+width/2,abctune.metaText.footer.center,"footerfont","header meta-bottom",0,null,"middle"),this.outputTextIf(this.padding.left+width,abctune.metaText.footer.right,"footerfont","header meta-bottom",0,null,"end"))},ABCJS.write.Renderer.prototype.outputFreeText=function(text){if(""===text){var hash=this.getFontAndAttr("textfont","defined-text");this.moveY(2*hash.attr["font-size"])}else if("string"==typeof text)this.outputTextIf(this.padding.left,text,"textfont","defined-text",0,1,"start");else{for(var str="",isCentered=!1,i=0;i<text.length;i++)text[i].font&&(str+="FONT("+text[i].font+")"),str+=text[i].text,text[i].center&&(isCentered=!0);var alignment=isCentered?"middle":"start",x=isCentered?this.controller.width/2:this.padding.left;this.outputTextIf(x,str,"textfont","defined-text",0,1,alignment)}},ABCJS.write.Renderer.prototype.outputSubtitle=function(width,subtitle){this.outputTextIf(this.padding.left+width/2,subtitle,"subtitlefont","text meta-top",this.spacing.subtitle,0,"middle")},ABCJS.write.Renderer.prototype.beginGroup=function(){this.path=[],this.lastM=[0,0],this.ingroup=!0},ABCJS.write.Renderer.prototype.addPath=function(path){if(path=path||[],0!==path.length){path[0][0]="m",path[0][1]-=this.lastM[0],path[0][2]-=this.lastM[1],this.lastM[0]+=path[0][1],this.lastM[1]+=path[0][2],this.path.push(path[0]);for(var i=1,ii=path.length;i<ii;i++)"m"===path[i][0]&&(this.lastM[0]+=path[i][1],this.lastM[1]+=path[i][2]),this.path.push(path[i])}},ABCJS.write.Renderer.prototype.endGroup=function(klass){if(this.ingroup=!1,0===this.path.length)return null;var ret=this.paper.path().attr({path:this.path,stroke:"none",fill:"#000000",class:this.addClasses(klass)});return this.path=[],this.doRegression&&this.addToRegression(ret),ret},ABCJS.write.Renderer.prototype.printStaveLine=function(x1,x2,pitch,klass){var extraClass="staff";void 0!==klass&&(extraClass+=" "+klass);var isIE=!1,dy=.35,fill="#000000";isIE&&(dy=1,fill="#666666");var y=this.calcY(pitch),pathString=ABCJS.write.sprintf("M %f %f L %f %f L %f %f L %f %f z",x1,y-dy,x2,y-dy,x2,y+dy,x1,y+dy),ret=this.paper.path().attr({path:pathString,stroke:"none",fill:fill,class:this.addClasses(extraClass)}).toBack();return this.doRegression&&this.addToRegression(ret),ret},ABCJS.write.Renderer.prototype.printStem=function(x,dx,y1,y2){if(dx<0){var tmp=y2;y2=y1,y1=tmp}var isIE=!1,fill="#000000";isIE&&dx<1&&(dx=1,fill="#666666"),~~x===x&&(x+=.05);var pathArray=[["M",x,y1],["L",x,y2],["L",x+dx,y2],["L",x+dx,y1],["z"]];if(isIE||!this.ingroup){var ret=this.paper.path().attr({path:pathArray,stroke:"none",fill:fill,class:this.addClasses("stem")}).toBack();return this.doRegression&&this.addToRegression(ret),ret}this.addPath(pathArray)},ABCJS.write.Renderer.prototype.printSymbol=function(x,offset,symbol,scalex,scaley,klass){var el,ycorr;if(!symbol)return null;if(symbol.length>0&&symbol.indexOf(".")<0){for(var elemset=this.paper.set(),dx=0,i=0;i<symbol.length;i++){var s=symbol.charAt(i);ycorr=ABCJS.write.glyphs.getYCorr(s),el=ABCJS.write.glyphs.printSymbol(x+dx,this.calcY(offset+ycorr),s,this.paper,klass),el?(this.doRegression&&this.addToRegression(el),elemset.push(el),i<symbol.length-1&&(dx+=kernSymbols(s,symbol.charAt(i+1),ABCJS.write.glyphs.getSymbolWidth(s)))):this.renderText(x,this.y,"no symbol:"+symbol,"debugfont","debug-msg","start")}return elemset}if(ycorr=ABCJS.write.glyphs.getYCorr(symbol),this.ingroup)this.addPath(ABCJS.write.glyphs.getPathForSymbol(x,this.calcY(offset+ycorr),symbol,scalex,scaley));else{if(el=ABCJS.write.glyphs.printSymbol(x,this.calcY(offset+ycorr),symbol,this.paper,klass))return this.doRegression&&this.addToRegression(el),el;this.renderText(x,this.y,"no symbol:"+symbol,"debugfont","debug-msg","start")}return null},ABCJS.write.Renderer.prototype.printPath=function(attrs){var ret=this.paper.path().attr(attrs);return this.doRegression&&this.addToRegression(ret),ret},ABCJS.write.Renderer.prototype.drawBrace=function(xLeft,yTop,yBottom){var yHeight=yBottom-yTop,xCurve=[7.5,-8,21,0,18.5,-10.5,7.5],yCurve=[0,yHeight/5.5,yHeight/3.14,yHeight/2,yHeight/2.93,yHeight/4.88,0],pathString=ABCJS.write.sprintf("M %f %f C %f %f %f %f %f %f C %f %f %f %f %f %f z",xLeft+xCurve[0],yTop+yCurve[0],xLeft+xCurve[1],yTop+yCurve[1],xLeft+xCurve[2],yTop+yCurve[2],xLeft+xCurve[3],yTop+yCurve[3],xLeft+xCurve[4],yTop+yCurve[4],xLeft+xCurve[5],yTop+yCurve[5],xLeft+xCurve[6],yTop+yCurve[6]),ret1=this.paper.path().attr({path:pathString,stroke:"#000000",fill:"#000000",class:this.addClasses("brace")});xCurve=[0,17.5,-7.5,6.6,-5,20,0],yCurve=[yHeight/2,yHeight/1.46,yHeight/1.22,yHeight,yHeight/1.19,yHeight/1.42,yHeight/2],pathString=ABCJS.write.sprintf("M %f %f C %f %f %f %f %f %f C %f %f %f %f %f %f z",xLeft+xCurve[0],yTop+yCurve[0],xLeft+xCurve[1],yTop+yCurve[1],xLeft+xCurve[2],yTop+yCurve[2],xLeft+xCurve[3],yTop+yCurve[3],xLeft+xCurve[4],yTop+yCurve[4],xLeft+xCurve[5],yTop+yCurve[5],xLeft+xCurve[6],yTop+yCurve[6]);var ret2=this.paper.path().attr({path:pathString,stroke:"#000000",fill:"#000000",class:this.addClasses("brace")});return this.doRegression&&(this.addToRegression(ret1),this.addToRegression(ret2)),ret1+ret2},ABCJS.write.Renderer.prototype.drawArc=function(x1,x2,pitch1,pitch2,above,klass,isTie){var spacing=isTie?1.2:1.5;x1+=6,x2+=4,pitch1+=above?spacing:-spacing,pitch2+=above?spacing:-spacing;var y1=this.calcY(pitch1),y2=this.calcY(pitch2),dx=x2-x1,dy=y2-y1,norm=Math.sqrt(dx*dx+dy*dy),ux=dx/norm,uy=dy/norm,flatten=norm/3.5,maxFlatten=isTie?1.5:25,curve=(above?-1:1)*Math.min(maxFlatten,Math.max(4,flatten)),controlx1=x1+flatten*ux-curve*uy,controly1=y1+flatten*uy+curve*ux,controlx2=x2-flatten*ux-curve*uy,controly2=y2-flatten*uy+curve*ux,thickness=2,pathString=ABCJS.write.sprintf("M %f %f C %f %f %f %f %f %f C %f %f %f %f %f %f z",x1,y1,controlx1,controly1,controlx2,controly2,x2,y2,controlx2-thickness*uy,controly2+thickness*ux,controlx1-thickness*uy,controly1+thickness*ux,x1,y1);klass?klass+=" slur":klass="slur";var ret=this.paper.path().attr({path:pathString,stroke:"none",fill:"#000000",class:this.addClasses(klass)});return this.doRegression&&this.addToRegression(ret),ret},ABCJS.write.Renderer.prototype.calcY=function(ofs){return this.y-ofs*ABCJS.write.spacing.STEP},ABCJS.write.Renderer.prototype.printStave=function(startx,endx,numLines){var klass="top-line";if(1===numLines)return void this.printStaveLine(startx,endx,6,klass);for(var i=numLines-1;i>=0;i--)this.printStaveLine(startx,endx,2*(i+1),klass),klass=void 0},ABCJS.write.Renderer.prototype.addClasses=function(c){var ret=[];return c.length>0&&ret.push(c),null!==this.lineNumber&&ret.push("l"+this.lineNumber),null!==this.measureNumber&&ret.push("m"+this.measureNumber),null!==this.voiceNumber&&ret.push("v"+this.voiceNumber),ret.join(" ")},ABCJS.write.Renderer.prototype.getFontAndAttr=function(type,klass){var font=this.abctune.formatting[type];font=font?{face:font.face,size:4*font.size/3,decoration:font.decoration,style:font.style,weight:font.weight,box:font.box}:{face:"Arial",size:16,decoration:"underline",style:"normal",weight:"normal"};var attr={"font-size":font.size,"font-style":font.style,"font-family":font.face,"font-weight":font.weight,"text-decoration":font.decoration,class:this.addClasses(klass)};return attr.font="",{font:font,attr:attr}},ABCJS.write.Renderer.prototype.getTextSize=function(text,type,klass){var hash=this.getFontAndAttr(type,klass),el=this.paper.text(0,0,text).attr(hash.attr),size=el.getBBox();return isNaN(size.height)&&(size={width:0,height:0}),el.remove(),size},ABCJS.write.Renderer.prototype.renderText=function(x,y,text,type,klass,anchor,centerVertically){var hash=this.getFontAndAttr(type,klass);anchor&&(hash.attr["text-anchor"]=anchor),text=text.replace(/\n\n/g,"\n \n");var el=this.paper.text(x,y,text).attr(hash.attr);if(!centerVertically){var size=el.getBBox();isNaN(size.height)?el.attr({y:y}):(el.attr({y:y+size.height/2}),hash.font.box&&this.paper.rect(size.x-1,size.y+size.height/2-1,size.width+2,size.height+2).attr({stroke:"#888888"}))}return"debugfont"===type&&(console.log("Debug msg: "+text),el.attr({stroke:"#ff0000"})),this.doRegression&&this.addToRegression(el),el},ABCJS.write.Renderer.prototype.moveY=function(em,numLines){void 0===numLines&&(numLines=1),this.y+=em*numLines},ABCJS.write.Renderer.prototype.skipSpaceY=function(){this.y+=this.space},ABCJS.write.Renderer.prototype.outputTextIf=function(x,str,kind,klass,marginTop,marginBottom,alignment){if(str){marginTop&&this.moveY(marginTop);var el=this.renderText(x,this.y,str,kind,klass,alignment),bb=el.getBBox(),width=isNaN(bb.width)?0:bb.width,height=isNaN(bb.height)?0:bb.height;if(null!==marginBottom){var numLines=str.split("\n").length;isNaN(bb.height)||this.moveY(height/numLines,numLines+marginBottom)}return[width,height]}return[0,0]},ABCJS.write.Renderer.prototype.addInvisibleMarker=function(className){var dy=.35,fill="rgba(0,0,0,0)",y=this.y;y=Math.round(y);var x1=0,x2=100,pathString=ABCJS.write.sprintf("M %f %f L %f %f L %f %f L %f %f z",x1,y-dy,x1+x2,y-dy,x2,y+dy,x1,y+dy);this.paper.path().attr({path:pathString,stroke:"none",fill:fill,class:this.addClasses(className),"data-vertical":y}).toBack()},ABCJS.write.Renderer.prototype.printHorizontalLine=function(width,vertical,comment){var dy=.35,fill="rgba(0,0,255,.4)",y=this.y;vertical&&(y=vertical),y=Math.round(y),this.paper.text(10,y,""+Math.round(y)).attr({"text-anchor":"start","font-size":"18px",fill:fill,stroke:fill});var x1=50,x2=width,pathString=ABCJS.write.sprintf("M %f %f L %f %f L %f %f L %f %f z",x1,y-dy,x1+x2,y-dy,x2,y+dy,x1,y+dy);this.paper.path().attr({path:pathString,stroke:"none",fill:fill,class:this.addClasses("staff")}).toBack();for(var i=1;i<width/100;i++)pathString=ABCJS.write.sprintf("M %f %f L %f %f L %f %f L %f %f z",100*i-dy,y-5,100*i-dy,y+5,100*i+dy,y-5,100*i+dy,y+5),this.paper.path().attr({path:pathString,stroke:"none",fill:fill,class:this.addClasses("staff")}).toBack();comment&&this.paper.text(width+70,y,comment).attr({"text-anchor":"start","font-size":"18px",fill:fill,stroke:fill})},ABCJS.write.Renderer.prototype.printShadedBox=function(x,y,width,height,color,comment){var box=this.paper.rect(x,y,width,height).attr({fill:color,stroke:color});return comment&&this.paper.text(0,y+7,comment).attr({"text-anchor":"start","font-size":"14px",fill:"rgba(0,0,255,.4)",stroke:"rgba(0,0,255,.4)"}),box},ABCJS.write.Renderer.prototype.printVerticalLine=function(x,y1,y2){var dy=.35,fill="#00aaaa",pathString=ABCJS.write.sprintf("M %f %f L %f %f L %f %f L %f %f z",x-dy,y1,x-dy,y2,x+dy,y1,x+dy,y2);this.paper.path().attr({path:pathString,stroke:"none",fill:fill,class:this.addClasses("staff")}).toBack(),pathString=ABCJS.write.sprintf("M %f %f L %f %f L %f %f L %f %f z",x-20,y1,x-20,y1+3,x,y1,x,y1+3),this.paper.path().attr({path:pathString,stroke:"none",fill:fill,class:this.addClasses("staff")}).toBack(),pathString=ABCJS.write.sprintf("M %f %f L %f %f L %f %f L %f %f z",x+20,y2,x+20,y2+3,x,y2,x,y2+3),this.paper.path().attr({path:pathString,stroke:"none",fill:fill,class:this.addClasses("staff")}).toBack()},ABCJS.write.Renderer.prototype.addToRegression=function(el){var box=el.getBBox(),str=el.type+" "+box.toString()+" ",attrs=[];for(var key in el.attrs)el.attrs.hasOwnProperty(key)&&("class"===key?str=el.attrs[key]+" "+str:attrs.push(key+": "+el.attrs[key]));attrs.sort(),str+="{ "+attrs.join(" ")+" }",this.regressionLines.push(str)},window.ABCJS||(window.ABCJS={}),window.ABCJS.write||(window.ABCJS.write={}),ABCJS.write.StaffGroupElement=function(){this.voices=[],this.staffs=[],this.brace=void 0},ABCJS.write.StaffGroupElement.prototype.setLimit=function(member,voice){voice.specialY[member]&&(voice.staff.specialY[member]?voice.staff.specialY[member]=Math.max(voice.staff.specialY[member],voice.specialY[member]):voice.staff.specialY[member]=voice.specialY[member])},ABCJS.write.StaffGroupElement.prototype.addVoice=function(voice,staffnumber,stafflines){var voiceNum=this.voices.length;this.voices[voiceNum]=voice,this.staffs[staffnumber]?this.staffs[staffnumber].voices.push(voiceNum):this.staffs[this.staffs.length]={top:10,bottom:2,lines:stafflines,voices:[voiceNum],specialY:{tempoHeightAbove:0,partHeightAbove:0,volumeHeightAbove:0,dynamicHeightAbove:0,endingHeightAbove:0,chordHeightAbove:0,lyricHeightAbove:0,lyricHeightBelow:0,chordHeightBelow:0,volumeHeightBelow:0,dynamicHeightBelow:0}},voice.staff=this.staffs[staffnumber]},ABCJS.write.StaffGroupElement.prototype.setStaffLimits=function(voice){voice.staff.top=Math.max(voice.staff.top,voice.top),voice.staff.bottom=Math.min(voice.staff.bottom,voice.bottom),this.setLimit("tempoHeightAbove",voice),this.setLimit("partHeightAbove",voice),this.setLimit("volumeHeightAbove",voice),this.setLimit("dynamicHeightAbove",voice),this.setLimit("endingHeightAbove",voice),this.setLimit("chordHeightAbove",voice),this.setLimit("lyricHeightAbove",voice),this.setLimit("lyricHeightBelow",voice),this.setLimit("chordHeightBelow",voice),this.setLimit("volumeHeightBelow",voice),this.setLimit("dynamicHeightBelow",voice)};ABCJS.write.StaffGroupElement.prototype.setUpperAndLowerElements=function(renderer){for(var lastStaffBottom,i=0;i<this.staffs.length;i++){var staff=this.staffs[i],positionY={tempoHeightAbove:0,partHeightAbove:0,volumeHeightAbove:0,dynamicHeightAbove:0,endingHeightAbove:0,chordHeightAbove:0,lyricHeightAbove:0,lyricHeightBelow:0,chordHeightBelow:0,volumeHeightBelow:0,dynamicHeightBelow:0};ABCJS.write.debugPlacement&&(staff.originalTop=staff.top,staff.originalBottom=staff.bottom),staff.specialY.lyricHeightAbove&&(staff.top+=staff.specialY.lyricHeightAbove,positionY.lyricHeightAbove=staff.top),staff.specialY.chordHeightAbove&&(staff.top+=staff.specialY.chordHeightAbove,positionY.chordHeightAbove=staff.top),staff.specialY.endingHeightAbove&&(staff.specialY.chordHeightAbove?staff.top+=2:staff.top+=staff.specialY.endingHeightAbove,positionY.endingHeightAbove=staff.top),staff.specialY.dynamicHeightAbove&&staff.specialY.volumeHeightAbove?(staff.top+=Math.max(staff.specialY.dynamicHeightAbove,staff.specialY.volumeHeightAbove),positionY.dynamicHeightAbove=staff.top,positionY.volumeHeightAbove=staff.top):staff.specialY.dynamicHeightAbove?(staff.top+=staff.specialY.dynamicHeightAbove,positionY.dynamicHeightAbove=staff.top):staff.specialY.volumeHeightAbove&&(staff.top+=staff.specialY.volumeHeightAbove,positionY.volumeHeightAbove=staff.top),staff.specialY.partHeightAbove&&(staff.top+=staff.specialY.partHeightAbove,positionY.partHeightAbove=staff.top),staff.specialY.tempoHeightAbove&&(staff.top+=staff.specialY.tempoHeightAbove,positionY.tempoHeightAbove=staff.top),staff.specialY.lyricHeightBelow&&(positionY.lyricHeightBelow=staff.bottom,staff.bottom-=staff.specialY.lyricHeightBelow),staff.specialY.chordHeightBelow&&(positionY.chordHeightBelow=staff.bottom,staff.bottom-=staff.specialY.chordHeightBelow),staff.specialY.volumeHeightBelow&&staff.specialY.dynamicHeightBelow?(positionY.volumeHeightBelow=staff.bottom,positionY.dynamicHeightBelow=staff.bottom,staff.bottom-=Math.max(staff.specialY.volumeHeightBelow,staff.specialY.dynamicHeightBelow)):staff.specialY.volumeHeightBelow?(positionY.volumeHeightBelow=staff.bottom,staff.bottom-=staff.specialY.volumeHeightBelow):staff.specialY.dynamicHeightBelow&&(positionY.dynamicHeightBelow=staff.bottom,staff.bottom-=staff.specialY.dynamicHeightBelow),ABCJS.write.debugPlacement&&(staff.positionY=positionY);for(var j=0;j<staff.voices.length;j++){var voice=this.voices[staff.voices[j]];voice.setUpperAndLowerElements(positionY)}if(void 0!==lastStaffBottom){var thisStaffTop=staff.top-10,forcedSpacingBetween=lastStaffBottom+thisStaffTop,minSpacingInPitches=renderer.spacing.systemStaffSeparation/ABCJS.write.spacing.STEP,addedSpace=minSpacingInPitches-forcedSpacingBetween;addedSpace>0&&(staff.top+=addedSpace)}lastStaffBottom=2-staff.bottom}};ABCJS.write.StaffGroupElement.prototype.finished=function(){for(var i=0;i<this.voices.length;i++)if(!this.voices[i].layoutEnded())return!1;return!0},ABCJS.write.StaffGroupElement.prototype.layout=function(spacing,renderer,debug){var epsilon=1e-7;this.spacingunits=0,this.minspace=1e3;for(var x=renderer.padding.left,voiceheaderw=0,i=0;i<this.voices.length;i++)if(this.voices[i].header){var size=renderer.getTextSize(this.voices[i].header,"voicefont","");voiceheaderw=Math.max(voiceheaderw,size.width)}x+=1.1*voiceheaderw,this.startx=x,this.brace&&(this.brace.setLocation(this.startx),x+=this.brace.getWidth(),this.startx=x);var currentduration=0;for(debug&&console.log("init layout"),i=0;i<this.voices.length;i++)this.voices[i].beginLayout(x);for(var spacingunit=0;!this.finished();){for(currentduration=null,i=0;i<this.voices.length;i++)this.voices[i].layoutEnded()||currentduration&&!(this.voices[i].getDurationIndex()<currentduration)||(currentduration=this.voices[i].getDurationIndex());debug&&console.log("currentduration: ",currentduration);var currentvoices=[],othervoices=[];for(i=0;i<this.voices.length;i++){var durationIndex=this.voices[i].getDurationIndex();durationIndex-currentduration>epsilon?othervoices.push(this.voices[i]):(currentvoices.push(this.voices[i]),debug&&console.log("in: voice ",i))}spacingunit=0;var spacingduration=0;for(i=0;i<currentvoices.length;i++)currentvoices[i].getNextX()>x&&(x=currentvoices[i].getNextX(),spacingunit=currentvoices[i].getSpacingUnits(),spacingduration=currentvoices[i].spacingduration);for(this.spacingunits+=spacingunit,this.minspace=Math.min(this.minspace,spacingunit),i=0;i<currentvoices.length;i++){var voicechildx=currentvoices[i].layoutOneItem(x,spacing),dx=voicechildx-x;if(dx>0){x=voicechildx;for(var j=0;j<i;j++)currentvoices[j].shiftRight(dx)}}for(i=0;i<othervoices.length;i++)othervoices[i].spacingduration-=spacingduration,othervoices[i].updateNextX(x,spacing);for(i=0;i<currentvoices.length;i++){var voice=currentvoices[i];voice.updateIndices()}}for(i=0;i<this.voices.length;i++)this.voices[i].getNextX()>x&&(x=this.voices[i].getNextX(),spacingunit=this.voices[i].getSpacingUnits());for(this.spacingunits+=spacingunit,this.w=x,i=0;i<this.voices.length;i++)this.voices[i].w=this.w},ABCJS.write.StaffGroupElement.prototype.calcHeight=function(){for(var height=0,i=0;i<this.voices.length;i++){var staff=this.voices[i].staff;this.voices[i].duplicate||(height+=staff.top,staff.bottom<0&&(height+=-staff.bottom))}return height},ABCJS.write.StaffGroupElement.prototype.draw=function(renderer){var debugPrint,colorIndex;if(ABCJS.write.debugPlacement){var colors=["rgba(207,27,36,0.4)","rgba(168,214,80,0.4)","rgba(110,161,224,0.4)","rgba(191,119,218,0.4)","rgba(195,30,151,0.4)","rgba(31,170,177,0.4)","rgba(220,166,142,0.4)"];debugPrint=function(staff,key){if(staff.positionY[key]){var height=staff.specialY[key]*ABCJS.write.spacing.STEP;renderer.printShadedBox(renderer.padding.left,renderer.calcY(staff.positionY[key]),renderer.controller.width,height,colors[colorIndex],key.substr(0,4)),colorIndex+=1,colorIndex>6&&(colorIndex=0)}}}renderer.addInvisibleMarker("abcjs-top-of-system");for(var startY=renderer.y,j=0;j<this.staffs.length;j++){var staff1=this.staffs[j];renderer.moveY(ABCJS.write.spacing.STEP,staff1.top),staff1.absoluteY=renderer.y,ABCJS.write.debugPlacement&&(colorIndex=0,renderer.printShadedBox(renderer.padding.left,renderer.calcY(staff1.originalTop),renderer.controller.width,renderer.calcY(staff1.originalBottom)-renderer.calcY(staff1.originalTop),"rgba(0,0,0,0.1)"),debugPrint(staff1,"chordHeightAbove"),debugPrint(staff1,"chordHeightBelow"),debugPrint(staff1,"dynamicHeightAbove"),debugPrint(staff1,"dynamicHeightBelow"),debugPrint(staff1,"endingHeightAbove"),debugPrint(staff1,"lyricHeightAbove"),debugPrint(staff1,"lyricHeightBelow"),debugPrint(staff1,"partHeightAbove"),debugPrint(staff1,"tempoHeightAbove"),debugPrint(staff1,"volumeHeightAbove"),debugPrint(staff1,"volumeHeightBelow")),staff1.bottom<0&&renderer.moveY(ABCJS.write.spacing.STEP,-staff1.bottom)}var topLine,bottomLine,bartop=0;renderer.measureNumber=null;for(var i=0;i<this.voices.length;i++){var staff=this.voices[i].staff;renderer.y=staff.absoluteY,renderer.voiceNumber=i,this.voices[i].duplicate||(topLine||(topLine=renderer.calcY(10)),bottomLine=renderer.calcY(2),0!==staff.lines&&renderer.printStave(this.startx,this.w,staff.lines)),this.voices[i].draw(renderer,bartop),this.voices[i].duplicate||(bartop=renderer.calcY(2)),this.brace&&i===this.brace.length-1&&this.brace&&this.brace.draw(renderer,topLine,bottomLine)}renderer.measureNumber=null,this.staffs.length>1&&renderer.printStem(this.startx,.6,topLine,bottomLine),renderer.y=startY},window.ABCJS||(window.ABCJS={}),window.ABCJS.write||(window.ABCJS.write={}),function(){"use strict";var totalHeightInPitches=5;ABCJS.write.TempoElement=function(tempo,tuneNumber){this.tempo=tempo,this.tuneNumber=tuneNumber,this.tempoHeightAbove=totalHeightInPitches,this.pitch=void 0},ABCJS.write.TempoElement.prototype.setUpperAndLowerElements=function(positionY){this.pitch=positionY.tempoHeightAbove},ABCJS.write.TempoElement.prototype.setX=function(x){this.x=x},ABCJS.write.TempoElement.prototype.draw=function(renderer){var x=this.x;void 0===this.pitch&&window.console.error("Tempo Element y-coordinate not set.");var text,y=renderer.calcY(this.pitch);if(this.tempo.preString){text=renderer.renderText(x,y,this.tempo.preString,"tempofont","tempo","start");var preWidth=text.getBBox().width,charWidth=preWidth/this.tempo.preString.length; x+=preWidth+charWidth}if(this.tempo.duration){var dot,flag,note,temposcale=.75,tempopitch=this.pitch-totalHeightInPitches+1,duration=this.tempo.duration[0],abselem=new ABCJS.write.AbsoluteElement(this.tempo,duration,1,"tempo",this.tuneNumber);duration<=1/32?(note="noteheads.quarter",flag="flags.u32nd",dot=0):duration<=1/16?(note="noteheads.quarter",flag="flags.u16th",dot=0):duration<=3/32?(note="noteheads.quarter",flag="flags.u16nd",dot=1):duration<=1/8?(note="noteheads.quarter",flag="flags.u8th",dot=0):duration<=3/16?(note="noteheads.quarter",flag="flags.u8th",dot=1):duration<=.25?(note="noteheads.quarter",dot=0):duration<=3/8?(note="noteheads.quarter",dot=1):duration<=.5?(note="noteheads.half",dot=0):duration<=.75?(note="noteheads.half",dot=1):duration<=1?(note="noteheads.whole",dot=0):duration<=1.5?(note="noteheads.whole",dot=1):duration<=2?(note="noteheads.dbl",dot=0):(note="noteheads.dbl",dot=1);var temponote=renderer.engraver.createNoteHead(abselem,note,{verticalPos:tempopitch},"up",0,0,flag,dot,0,temposcale);abselem.addHead(temponote);var stem;if("noteheads.whole"!==note&&"noteheads.dbl"!==note){var p1=tempopitch+1/3*temposcale,p2=tempopitch+7*temposcale,dx=temponote.dx+temponote.w,width=-.6;stem=new ABCJS.write.RelativeElement(null,dx,0,p1,{type:"stem",pitch2:p2,linewidth:width}),stem.setX(x),abselem.addExtra(stem)}abselem.setX(x);for(var i=0;i<abselem.children.length;i++)abselem.children[i].draw(renderer,x);x+=abselem.w+5;var str="= "+this.tempo.bpm;text=renderer.renderText(x,y,str,"tempofont","tempo","start");var postWidth=text.getBBox().width,charWidth2=postWidth/str.length;x+=postWidth+charWidth2}this.tempo.postString&&renderer.renderText(x,y,this.tempo.postString,"tempofont","tempo","start")}}(),window.ABCJS||(window.ABCJS={}),window.ABCJS.write||(window.ABCJS.write={}),ABCJS.write.TieElem=function(anchor1,anchor2,above,forceandshift,isTie){this.anchor1=anchor1,this.anchor2=anchor2,this.above=above,this.force=forceandshift,this.isTie=isTie},ABCJS.write.TieElem.prototype.setEndAnchor=function(anchor2){this.anchor2=anchor2,this.isTie&&(this.anchor1&&(this.anchor1.isTie=!0),this.anchor2&&(this.anchor2.isTie=!0))},ABCJS.write.TieElem.prototype.setStartX=function(startLimitElem){this.startLimitX=startLimitElem},ABCJS.write.TieElem.prototype.setEndX=function(endLimitElem){this.endLimitX=endLimitElem},ABCJS.write.TieElem.prototype.setHint=function(){this.hint=!0},ABCJS.write.TieElem.prototype.setUpperAndLowerElements=function(positionY){},ABCJS.write.TieElem.prototype.layout=function(lineStartX,lineEndX){function getPitch(anchor,isAbove,isTie){return isTie?anchor.pitch:isAbove&&void 0!==anchor.highestVert?anchor.highestVert:anchor.pitch}!this.force&&this.anchor2&&this.anchor2.pitch===this.anchor2.highestVert&&(this.above=!0),this.isTie?(this.anchor1&&(this.anchor1.tieAbove=this.above),this.anchor2&&(this.anchor2.tieAbove=this.above)):this.anchor2&&this.anchor2.isTie?this.above=this.anchor2.tieAbove:this.anchor1&&this.anchor1.isTie&&(this.above=this.anchor1.tieAbove),this.anchor1?this.startX=this.anchor1.x:this.startLimitX?this.startX=this.startLimitX.x+this.startLimitX.w:this.startX=lineStartX,this.anchor2?this.endX=this.anchor2.x:this.endLimitX?this.endX=this.endLimitX.x:this.endX=lineEndX,this.anchor1&&this.anchor2?(this.startY=getPitch(this.anchor1,this.above,this.isTie),this.endY=getPitch(this.anchor2,this.above,this.isTie)):this.anchor1?(this.startY=getPitch(this.anchor1,this.above,this.isTie),this.endY=getPitch(this.anchor1,this.above,this.isTie)):this.anchor2?(this.startY=getPitch(this.anchor2,this.above,this.isTie),this.endY=getPitch(this.anchor2,this.above,this.isTie)):(this.startY=this.above?14:0,this.endY=this.above?14:0)},ABCJS.write.TieElem.prototype.draw=function(renderer,linestartx,lineendx){this.layout(linestartx,lineendx);var klass;this.hint&&(klass="abcjs-hint"),renderer.drawArc(this.startX,this.endX,this.startY,this.endY,this.above,klass,this.isTie)},window.ABCJS||(window.ABCJS={}),window.ABCJS.write||(window.ABCJS.write={}),function(){"use strict";function drawLine(renderer,l,t,r,b){var pathString=ABCJS.write.sprintf("M %f %f L %f %f",l,t,r,b);renderer.printPath({path:pathString,stroke:"#000000",class:renderer.addClasses("triplet")})}function drawBracket(renderer,x1,y1,x2,y2){y1=renderer.calcY(y1),y2=renderer.calcY(y2);var bracketHeight=5;drawLine(renderer,x1,y1,x1,y1+bracketHeight),drawLine(renderer,x2,y2,x2,y2+bracketHeight);var midX=x1+(x2-x1)/2,gapWidth=8,slope=(y2-y1)/(x2-x1),leftEndX=midX-gapWidth,leftEndY=y1+(leftEndX-x1)*slope;drawLine(renderer,x1,y1,leftEndX,leftEndY);var rightStartX=midX+gapWidth,rightStartY=y1+(rightStartX-x1)*slope;drawLine(renderer,rightStartX,rightStartY,x2,y2)}ABCJS.write.TripletElem=function(number,anchor1){this.anchor1=anchor1,this.number=number},ABCJS.write.TripletElem.prototype.isClosed=function(){return this.anchor2},ABCJS.write.TripletElem.prototype.setCloseAnchor=function(anchor2){this.anchor2=anchor2,this.anchor1.parent.beam&&(this.endingHeightAbove=4)},ABCJS.write.TripletElem.prototype.setUpperAndLowerElements=function(){},ABCJS.write.TripletElem.prototype.layout=function(){if(this.anchor1&&this.anchor2)if(this.hasBeam=this.anchor1.parent.beam&&this.anchor1.parent.beam===this.anchor2.parent.beam,this.hasBeam){var beam=this.anchor1.parent.beam,left=beam.isAbove()?this.anchor1.x+this.anchor1.w:this.anchor1.x;this.yTextPos=beam.heightAtMidpoint(left,this.anchor2.x),this.yTextPos+=beam.isAbove()?4:-4,beam.isAbove()&&(this.endingHeightAbove=4)}else this.startNote=Math.max(this.anchor1.parent.top,9)+4,this.endNote=Math.max(this.anchor2.parent.top,9)+4,this.yTextPos=this.startNote+(this.endNote-this.startNote)/2},ABCJS.write.TripletElem.prototype.draw=function(renderer){var xTextPos;if(this.hasBeam){var left=this.anchor1.parent.beam.isAbove()?this.anchor1.x+this.anchor1.w:this.anchor1.x;xTextPos=this.anchor1.parent.beam.xAtMidpoint(left,this.anchor2.x)}else xTextPos=this.anchor1.x+(this.anchor2.x+this.anchor2.w-this.anchor1.x)/2,drawBracket(renderer,this.anchor1.x,this.startNote,this.anchor2.x+this.anchor2.w,this.endNote);renderer.renderText(xTextPos,renderer.calcY(this.yTextPos),""+this.number,"tripletfont","triplet","middle",!0)}}(),window.ABCJS||(window.ABCJS={}),window.ABCJS.write||(window.ABCJS.write={}),ABCJS.write.VoiceElement=function(voicenumber,voicetotal){this.children=[],this.beams=[],this.otherchildren=[],this.w=0,this.duplicate=!1,this.voicenumber=voicenumber,this.voicetotal=voicetotal,this.bottom=7,this.top=7,this.specialY={tempoHeightAbove:0,partHeightAbove:0,volumeHeightAbove:0,dynamicHeightAbove:0,endingHeightAbove:0,chordHeightAbove:0,lyricHeightAbove:0,lyricHeightBelow:0,chordHeightBelow:0,volumeHeightBelow:0,dynamicHeightBelow:0}},ABCJS.write.VoiceElement.prototype.addChild=function(child){if("bar"===child.type){for(var firstItem=!0,i=0;firstItem&&i<this.children.length;i++)"staff-extra"!==this.children[i].type&&(firstItem=!1);firstItem||(this.beams.push("bar"),this.otherchildren.push("bar"))}this.children[this.children.length]=child,this.setRange(child)},ABCJS.write.VoiceElement.prototype.setLimit=function(member,child){var specialY=child.specialY;specialY||(specialY=child),specialY[member]&&(this.specialY[member]?this.specialY[member]=Math.max(this.specialY[member],specialY[member]):this.specialY[member]=specialY[member])},ABCJS.write.VoiceElement.prototype.moveDecorations=function(beam){for(var padding=1.5,ch=0;ch<beam.elems.length;ch++){var child=beam.elems[ch];if(child.top)for(var top=beam.yAtNote(child),i=0;i<child.children.length;i++){var el=child.children[i];if("ornament"===el.klass&&el.bottom-padding<top){var distance=top-el.bottom+padding;el.bottom+=distance,el.top+=distance,el.pitch+=distance,top=child.top=el.top}}}},ABCJS.write.VoiceElement.prototype.adjustRange=function(child){void 0!==child.bottom&&(this.bottom=Math.min(this.bottom,child.bottom)),void 0!==child.top&&(this.top=Math.max(this.top,child.top))},ABCJS.write.VoiceElement.prototype.setRange=function(child){this.adjustRange(child),this.setLimit("tempoHeightAbove",child),this.setLimit("partHeightAbove",child),this.setLimit("volumeHeightAbove",child),this.setLimit("dynamicHeightAbove",child),this.setLimit("endingHeightAbove",child),this.setLimit("chordHeightAbove",child),this.setLimit("lyricHeightAbove",child),this.setLimit("lyricHeightBelow",child),this.setLimit("chordHeightBelow",child),this.setLimit("volumeHeightBelow",child),this.setLimit("dynamicHeightBelow",child)},ABCJS.write.VoiceElement.prototype.setUpperAndLowerElements=function(positionY){var i;for(i=0;i<this.children.length;i++){var abselem=this.children[i];abselem.setUpperAndLowerElements(positionY)}for(i=0;i<this.otherchildren.length;i++){var abselem=this.otherchildren[i];"string"!=typeof abselem&&abselem.setUpperAndLowerElements(positionY)}},ABCJS.write.VoiceElement.prototype.addOther=function(child){this.otherchildren.push(child),this.setRange(child)},ABCJS.write.VoiceElement.prototype.addBeam=function(child){this.beams.push(child)},ABCJS.write.VoiceElement.prototype.updateIndices=function(){this.layoutEnded()||(this.durationindex+=this.children[this.i].duration,0===this.children[this.i].duration&&(this.durationindex=Math.round(64*this.durationindex)/64),this.i++)},ABCJS.write.VoiceElement.prototype.layoutEnded=function(){return this.i>=this.children.length},ABCJS.write.VoiceElement.prototype.getDurationIndex=function(){return this.durationindex-(this.children[this.i]&&this.children[this.i].duration>0?0:5e-7)},ABCJS.write.VoiceElement.prototype.getSpacingUnits=function(){return Math.sqrt(8*this.spacingduration)},ABCJS.write.VoiceElement.prototype.getNextX=function(){return Math.max(this.minx,this.nextx)},ABCJS.write.VoiceElement.prototype.beginLayout=function(startx){this.i=0,this.durationindex=0,this.startx=startx,this.minx=startx,this.nextx=startx,this.spacingduration=0},ABCJS.write.VoiceElement.prototype.layoutOneItem=function(x,spacing){var child=this.children[this.i];if(!child)return 0;var er=x-this.minx;return er<child.getExtraWidth()&&(x+=child.getExtraWidth()-er),child.setX(x),this.spacingduration=child.duration,this.minx=x+child.getMinWidth(),this.i!==this.children.length-1&&(this.minx+=child.minspacing),this.updateNextX(x,spacing),x},ABCJS.write.VoiceElement.prototype.updateNextX=function(x,spacing){this.nextx=x+spacing*Math.sqrt(8*this.spacingduration)},ABCJS.write.VoiceElement.prototype.shiftRight=function(dx){var child=this.children[this.i];child&&(child.setX(child.x+dx),this.minx+=dx,this.nextx+=dx)},ABCJS.write.VoiceElement.prototype.draw=function(renderer,bartop){var width=this.w-1;if(renderer.staffbottom=this.staff.bottom,renderer.measureNumber=null,this.header){var textpitch=14-(this.voicenumber+1)*(12/(this.voicetotal+1));renderer.renderText(renderer.padding.left,renderer.calcY(textpitch),this.header,"voicefont","staff-extra voice-name","start")}for(var i=0,ii=this.children.length;i<ii;i++){var child=this.children[i],justInitializedMeasureNumber=!1;"staff-extra"!==child.type&&null===renderer.measureNumber&&(renderer.measureNumber=0,justInitializedMeasureNumber=!0),child.draw(renderer,this.barto||i===ii-1?bartop:0),"bar"!==child.type||justInitializedMeasureNumber||renderer.measureNumber++}renderer.measureNumber=0,window.ABCJS.parse.each(this.beams,function(beam){"bar"===beam?renderer.measureNumber++:beam.draw(renderer)}),renderer.measureNumber=0;var self=this;window.ABCJS.parse.each(this.otherchildren,function(child){"bar"===child?renderer.measureNumber++:child.draw(renderer,self.startx+10,width)})},ABCJS.write.VoiceElement.prototype.layoutBeams=function(){for(var i=0;i<this.beams.length;i++)if(this.beams[i].layout){this.beams[i].layout(),this.moveDecorations(this.beams[i]);for(var j=0;j<this.beams[i].elems.length;j++)this.adjustRange(this.beams[i].elems[j])}for(i=0;i<this.otherchildren.length;i++){var child=this.otherchildren[i];child.layout&&child.layout()}this.staff.top=Math.max(this.staff.top,this.top),this.staff.bottom=Math.min(this.staff.bottom,this.bottom)},window.ABCJS||(window.ABCJS={}),window.ABCJS.write||(window.ABCJS.write={}),ABCJS.write.sprintf=function(){for(var a,m,p,c,x,i=0,f=arguments[i++],o=[];f;){if(m=/^[^\x25]+/.exec(f))o.push(m[0]);else if(m=/^\x25{2}/.exec(f))o.push("%");else{if(!(m=/^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f)))throw"Huh ?!";if(null==(a=arguments[m[1]||i++])||void 0==a)throw"Too few arguments.";if(/[^s]/.test(m[7])&&"number"!=typeof a)throw"Expecting number but found "+typeof a;switch(m[7]){case"b":a=a.toString(2);break;case"c":a=String.fromCharCode(a);break;case"d":a=parseInt(a);break;case"e":a=m[6]?a.toExponential(m[6]):a.toExponential();break;case"f":a=m[6]?parseFloat(a).toFixed(m[6]):parseFloat(a);break;case"o":a=a.toString(8);break;case"s":a=(a=String(a))&&m[6]?a.substring(0,m[6]):a;break;case"u":a=Math.abs(a);break;case"x":a=a.toString(16);break;case"X":a=a.toString(16).toUpperCase()}a=/[def]/.test(m[7])&&m[2]&&a>0?"+"+a:a,c=m[3]?"0"==m[3]?"0":m[3].charAt(1):" ",x=m[5]-String(a).length,p=m[5]?str_repeat(c,x):"",o.push(m[4]?a+p:p+a)}f=f.substring(m[0].length)}return o.join("")},window.ABCJS||(window.ABCJS={}),window.ABCJS.Plugin=function(){"use strict";var is_user_script=!1;try{is_user_script=abcjs_is_user_script}catch(ex){}this.show_midi=!is_user_script,this.hide_abc=!1,this.render_before=!1,this.midi_options={},this.render_options={},this.render_classname="abcrendered",this.text_classname="abctext",this.auto_render_threshold=20,this.show_text="show score for: ",this.debug=!1},window.ABCJS.plugin=new window.ABCJS.Plugin,jQuery(function($){"use strict";window.ABCJS.plugin.start=function(){var body=$("body");this.errors="";var elems=this.getABCContainingElements(body);if(this.debug)for(var i=0;i<elems.length;i++){var str="Possible ABC found ("+(i+1)+" of "+elems.length+"):\n\n"+elems[i].innerText;alert(str)}var self=this,divs=elems.map(function(i,elem){return self.convertToDivs(elem)});this.auto_render=divs.size()<=this.auto_render_threshold,divs.each(function(i,elem){self.render(elem,$(elem).data("abctext"))})},window.ABCJS.plugin.getABCContainingElements=function(elem){var results=$(),includeself=!1,self=this;return $(elem).contents().each(function(){3!==this.nodeType||includeself?1!==this.nodeType||$(this).is("textarea")||(results=results.add(self.getABCContainingElements(this))):this.nodeValue.match(/^\s*X:/m)&&"textarea"!==this.parentNode.tagName.toLowerCase()&&(results=results.add($(elem)),includeself=!0)}),results},window.ABCJS.plugin.convertToDivs=function(elem){var self=this,contents=$(elem).contents(),abctext="",abcdiv=null,inabc=!1,brcount=0,results=$();return contents.each(function(i,node){if(3!==node.nodeType||node.nodeValue.match(/^\s*$/))inabc&&$(node).is("br")?(abctext+="\n",abcdiv.append($(node)),brcount++):inabc&&1===node.nodeType?(abctext+="\n",abcdiv.append($(node))):inabc&&(inabc=!1,brcount=0,abctext=abctext.replace(/\n+/,"\n"),abcdiv.data("abctext",abctext),results=results.add(abcdiv));else{brcount=0;var text=node.nodeValue;text.match(/^\s*X:/m)&&(inabc=!0,abctext="",abcdiv=$("<div class='"+self.text_classname+"'></div>"),$(node).before(abcdiv),self.hide_abc&&abcdiv.hide()),inabc&&(abctext+=text.replace(/\n+/,""),abcdiv.append($(node)))}}),inabc&&(abctext=abctext.replace(/\n+$/,"\n").replace(/^\n+/,"\n"),abcdiv.data("abctext",abctext),results=results.add(abcdiv)),results.get()},window.ABCJS.plugin.render=function(contextnode,abcstring){var abcdiv=$("<div class='"+this.render_classname+"'></div>");this.render_before?$(contextnode).before(abcdiv):$(contextnode).after(abcdiv);var self=this;try{this.debug&&alert("About to render:\n\n"+abcstring);var tunebook=new ABCJS.TuneBook(abcstring),abcParser=new ABCJS.parse.Parse;abcParser.parse(tunebook.tunes[0].abc);var tune=abcParser.getTune(),doPrint=function(){try{var paper=Raphael(abcdiv.get(0),800,400),engraver_controller=new ABCJS.write.EngraverController(paper,self.render_options);engraver_controller.engraveABC(tune)}catch(ex){abcdiv.remove(),abcdiv=$("<div class='"+self.render_classname+"'></div>"),paper=Raphael(abcdiv.get(0),800,400),engraver_controller=new ABCJS.write.EngraverController(paper),engraver_controller.engraveABC(tune),self.render_before?$(contextnode).before(abcdiv):$(contextnode).after(abcdiv)}if(ABCJS.MidiWriter&&self.show_midi){var midiwriter=new ABCJS.midi.MidiWriter(abcdiv.get(0),self.midi_options);midiwriter.writeABC(tune)}},showtext="<a class='abcshow' href='#'>"+this.show_text+(tune.metaText.title||"untitled")+"</a>";if(this.auto_render)doPrint();else{var showspan=$(showtext);showspan.click(function(){return doPrint(),showspan.hide(),!1}),abcdiv.before(showspan)}}catch(e){this.errors+=e}};var autostart=!0;try{autostart=abcjs_plugin_autostart}catch(ex){}autostart&&ABCJS.plugin.start()});
ajax/libs/asynquence-contrib/0.12.1/contrib-es6.src.js
maruilian11/cdnjs
/*! asynquence-contrib v0.12.1 (c) Kyle Simpson MIT License: http://getify.mit-license.org */ (function UMD(dependency,definition){ if (typeof module !== "undefined" && module.exports) { // make dependency injection wrapper first module.exports = function $$inject$dependency(dep) { // only try to `require(..)` if dependency is a string module path if (typeof dep == "string") { try { dep = require(dep); } catch (err) { // dependency not yet fulfilled, so just return // dependency injection wrapper again return $$inject$dependency; } } return definition(dep); }; // if possible, immediately try to resolve wrapper // (with peer dependency) if (typeof dependency == "string") { module.exports = module.exports( require("path").join("..",dependency) ); } } else if (typeof define == "function" && define.amd) { define([dependency],definition); } else { definition(dependency); } })(this.ASQ || "asynquence",function DEF(ASQ){ "use strict"; var ARRAY_SLICE = Array.prototype.slice, ø = Object.create(null), brand = "__ASQ__", schedule = ASQ.__schedule, tapSequence = ASQ.__tapSequence ; function wrapGate(api,fns,success,failure,reset) { fns = fns.map(function $$map(v,idx){ var def; // tap any directly-provided sequences immediately if (ASQ.isSequence(v)) { def = { seq: v }; tapSequence(def); return function $$fn(next) { def.seq.val(function $$val(){ success(next,idx,ARRAY_SLICE.call(arguments)); }) .or(function $$or(){ failure(next,idx,ARRAY_SLICE.call(arguments)); }); }; } else { return function $$fn(next) { var args = ARRAY_SLICE.call(arguments); args[0] = function $$next() { success(next,idx,ARRAY_SLICE.call(arguments)); }; args[0].fail = function $$fail() { failure(next,idx,ARRAY_SLICE.call(arguments)); }; args[0].abort = function $$abort() { reset(); }; args[0].errfcb = function $$errfcb(err) { if (err) { failure(next,idx,[err]); } else { success(next,idx,ARRAY_SLICE.call(arguments,1)); } }; v.apply(ø,args); }; } }); api.then(function $$then(){ var args = ARRAY_SLICE.call(arguments); fns.forEach(function $$each(fn){ fn.apply(ø,args); }); }); } function isPromise(v) { var val_type = typeof v; return ( v !== null && ( val_type == "object" || val_type == "function" ) && !ASQ.isSequence(v) && // NOTE: `then` duck-typing of promises is stupid typeof v.then == "function" ); } // "after" ASQ.extend("after",function $$extend(api,internals){ return function $$after(num) { var orig_args = arguments.length > 1 ? ARRAY_SLICE.call(arguments,1) : void 0 ; num = +num || 0; api.then(function $$then(done){ var args = orig_args || ARRAY_SLICE.call(arguments,1); setTimeout(function $$set$timeout(){ done.apply(ø,args); },num); }); return api; }; }); ASQ.after = function $$after() { return ASQ().after.apply(ø,arguments); }; // "any" ASQ.extend("any",function $$extend(api,internals){ return function $$any() { if (internals("seq_error") || internals("seq_aborted") || arguments.length === 0 ) { return api; } var fns = ARRAY_SLICE.call(arguments); api.then(function $$then(done){ function reset() { finished = true; error_messages.length = 0; success_messages.length = 0; } function complete(trigger) { if (success_messages.length > 0) { // any successful segment's message(s) sent // to main sequence to proceed as success success_messages.length = fns.length; trigger.apply(ø,success_messages); } else { // send errors into main sequence error_messages.length = fns.length; trigger.fail.apply(ø,error_messages); } reset(); } function success(trigger,idx,args) { if (!finished) { completed++; success_messages[idx] = args.length > 1 ? ASQ.messages.apply(ø,args) : args[0] ; // all segments complete? if (completed === fns.length) { finished = true; complete(trigger); } } } function failure(trigger,idx,args) { if (!finished && !(idx in error_messages) ) { completed++; error_messages[idx] = args.length > 1 ? ASQ.messages.apply(ø,args) : args[0] ; } // all segments complete? if (!finished && completed === fns.length ) { finished = true; complete(trigger); } } var completed = 0, error_messages = [], finished = false, success_messages = [], sq = ASQ.apply(ø,ARRAY_SLICE.call(arguments,1)) ; wrapGate(sq,fns,success,failure,reset); sq.pipe(done); }); return api; }; }); // "errfcb" ASQ.extend("errfcb",function $$extend(api,internals){ return function $$errfcb() { // create a fake sequence to extract the callbacks var sq = { val: function $$then(cb){ sq.val_cb = cb; return sq; }, or: function $$or(cb){ sq.or_cb = cb; return sq; } }; // trick `seq(..)`s checks for a sequence sq[brand] = true; // immediately register our fake sequence on the // main sequence api.seq(sq); // provide the "error-first" callback return function $$errorfirst$callback(err) { if (err) { sq.or_cb(err); } else { sq.val_cb.apply(ø,ARRAY_SLICE.call(arguments,1)); } }; }; }); // "failAfter" ASQ.extend("failAfter",function $$extend(api,internals){ return function $$failAfter(num) { var args = arguments.length > 1 ? ARRAY_SLICE.call(arguments,1) : void 0 ; num = +num || 0; api.then(function $$then(done){ setTimeout(function $$set$timeout(){ done.fail.apply(ø,args); },num); }); return api; }; }); ASQ.failAfter = function $$fail$after() { return ASQ().failAfter.apply(ø,arguments); }; // "first" ASQ.extend("first",function $$extend(api,internals){ return function $$first() { if (internals("seq_error") || internals("seq_aborted") || arguments.length === 0 ) { return api; } var fns = ARRAY_SLICE.call(arguments); api.then(function $$then(done){ function reset() { error_messages.length = 0; } function success(trigger,idx,args) { if (!finished) { finished = true; // first successful segment triggers // main sequence to proceed as success trigger( args.length > 1 ? ASQ.messages.apply(ø,args) : args[0] ); reset(); } } function failure(trigger,idx,args) { if (!finished && !(idx in error_messages) ) { completed++; error_messages[idx] = args.length > 1 ? ASQ.messages.apply(ø,args) : args[0] ; // all segments complete without success? if (completed === fns.length) { finished = true; // send errors into main sequence error_messages.length = fns.length; trigger.fail.apply(ø,error_messages); reset(); } } } var completed = 0, error_messages = [], finished = false, sq = ASQ.apply(ø,ARRAY_SLICE.call(arguments,1)) ; wrapGate(sq,fns,success,failure,reset); sq.pipe(done); }); return api; }; }); // "go-style CSP" (function IIFE(){ // filter out already-resolved queue entries function filterResolved(queue) { return queue.filter(function $$filter(entry){ return !entry.resolved; }); } function closeQueue(queue,finalValue) { queue.forEach(function $$each(iter){ if (!iter.resolved) { iter.next(); iter.next(finalValue); } }); queue.length = 0; } function channel(bufSize) { var ch = { close: function $$close(){ ch.closed = true; closeQueue(ch.put_queue,false); closeQueue(ch.take_queue,ASQ.csp.CLOSED); }, closed: false, messages: [], put_queue: [], take_queue: [], buffer_size: +bufSize || 0 }; return ch; } function unblock(iter) { if (iter && !iter.resolved) { iter.next(iter.next().value); } } function put(channel,value) { var ret; if (channel.closed) { return false; } // remove already-resolved entries channel.put_queue = filterResolved(channel.put_queue); channel.take_queue = filterResolved(channel.take_queue); // immediate put? if (channel.messages.length < channel.buffer_size) { channel.messages.push(value); unblock(channel.take_queue.shift()); return true; } // queued put else { channel.put_queue.push( // make a notifiable iterable for 'put' blocking ASQ.iterable() .then(function $$then(){ if (!channel.closed) { channel.messages.push(value); return true; } else { return false; } }) ); // wrap a sequence/promise around the iterable ret = ASQ( channel.put_queue[channel.put_queue.length - 1] ); // take waiting on this queued put? if (channel.take_queue.length > 0) { unblock(channel.put_queue.shift()); unblock(channel.take_queue.shift()); } return ret; } } function putAsync(channel,value,cb) { var ret = ASQ(put(channel,value)); if (cb && typeof cb == "function") { ret.val(cb); } else { return ret; } } function take(channel) { var ret; try { ret = takem(channel); } catch (err) { ret = err; } if (ASQ.isSequence(ret)) { ret.pCatch(function $$pcatch(err){ return err; }); } return ret; } function takeAsync(channel,cb) { var ret = ASQ(take(channel)); if (cb && typeof cb == "function") { ret.val(cb); } else { return ret; } } function takem(channel) { var msg; if (channel.closed) { return ASQ.csp.CLOSED; } // remove already-resolved entries channel.put_queue = filterResolved(channel.put_queue); channel.take_queue = filterResolved(channel.take_queue); // immediate take? if (channel.messages.length > 0) { msg = channel.messages.shift(); unblock(channel.put_queue.shift()); if (msg instanceof Error) { throw msg; } return msg; } // queued take else { channel.take_queue.push( // make a notifiable iterable for 'take' blocking ASQ.iterable() .then(function $$then(){ if (!channel.closed) { var v = channel.messages.shift(); if (v instanceof Error) { throw v; } return v; } else { return ASQ.csp.CLOSED; } }) ); // wrap a sequence/promise around the iterable msg = ASQ( channel.take_queue[channel.take_queue.length - 1] ); // put waiting on this take? if (channel.put_queue.length > 0) { unblock(channel.put_queue.shift()); unblock(channel.take_queue.shift()); } return msg; } } function takemAsync(channel,cb) { var ret = ASQ(takem(channel)); if (cb && typeof cb == "function") { ret.pThen(cb,cb); } else { return ret.val(function $$val(v){ if (v instanceof Error) { throw v; } return v; }); } } function alts(actions) { var closed, open, handlers, i, isq, ret, resolved = false; // used `alts(..)` incorrectly? if (!Array.isArray(actions) || actions.length == 0) { throw Error("Invalid usage"); } closed = []; open = []; handlers = []; // separate actions by open/closed channel status actions.forEach(function $$each(action){ var channel = Array.isArray(action) ? action[0] : action; // remove already-resolved entries channel.put_queue = filterResolved(channel.put_queue); channel.take_queue = filterResolved(channel.take_queue); if (channel.closed) { closed.push(channel); } else { open.push(action); } }); // if no channels are still open, we're done if (open.length == 0) { return { value: ASQ.csp.CLOSED, channel: closed }; } // can any channel action be executed immediately? for (i=0; i<open.length; i++) { // put action if (Array.isArray(open[i])) { // immediate put? if (open[i][0].messages.length < open[i][0].buffer_size) { return { value: put(open[i][0],open[i][1]), channel: open[i][0] }; } } // immediate take? else if (open[i].messages.length > 0) { return { value: take(open[i]), channel: open[i] }; } } isq = ASQ.iterable(); var ret = ASQ(isq); // setup channel action handlers for (i=0; i<open.length; i++) { (function iteration(action,channel,value){ // put action? if (Array.isArray(action)) { channel = action[0]; value = action[1]; // define put handler handlers.push( ASQ.iterable() .then(function $$then(){ resolved = true; // mark all handlers across this `alts(..)` as resolved now handlers = handlers.filter(function $$filter(handler){ return !(handler.resolved = true); }); // channel still open? if (!channel.closed) { channel.messages.push(value); isq.next({ value: true, channel: channel }); } // channel already closed? else { isq.next({ value: false, channel: channel }); } }) ); // queue up put handler channel.put_queue.push(handlers[handlers.length-1]); // take waiting on this queued put? if (channel.take_queue.length > 0) { schedule(function handleUnblocking(){ if (!resolved) { unblock(channel.put_queue.shift()); unblock(channel.take_queue.shift()); } },0); } } // take action? else { channel = action; // define take handler handlers.push( ASQ.iterable() .then(function $$then(){ resolved = true; // mark all handlers across this `alts(..)` as resolved now handlers = handlers.filter(function $$filter(handler){ return !(handler.resolved = true); }); // channel still open? if (!channel.closed) { isq.next({ value: channel.messages.shift(), channel: channel }); } // channel already closed? else { isq.next({ value: ASQ.csp.CLOSED, channel: channel }); } }) ); // queue up take handler channel.take_queue.push(handlers[handlers.length-1]); // put waiting on this queued take? if (channel.put_queue.length > 0) { schedule(function handleUnblocking(){ if (!resolved) { unblock(channel.put_queue.shift()); unblock(channel.take_queue.shift()); } }); } } })(open[i]); } return ret; } function altsAsync(chans,cb) { var ret = ASQ(alts(channel)); if (cb && typeof cb == "function") { ret.pThen(cb,cb); } else { return ret; } } function timeout(delay) { var ch = channel(); setTimeout(ch.close,delay); return ch; } function go(gen,args) { // goroutine arguments passed? if (arguments.length > 1) { if (!args || !Array.isArray(args)) { args = [args]; } } else { args = []; } return function *$$go(token) { // unblock the overall goroutine handling function unblock() { if (token.block && !token.block.marked) { token.block.marked = true; token.block.next(); } } var ret, msg, err, type, done = false, it; // keep track of how many goroutines are running // so we can infer when we're done go'ing token.go_count = (token.go_count || 0) + 1; // need to initialize a set of goroutines? if (token.go_count === 1) { // create a default channel for these goroutines token.channel = channel(); token.channel.messages = token.messages; token.channel.go = function $$go(){ // unblock the goroutine handling for these // new goroutine(s)? unblock(); // add the goroutine(s) to the handling queue token.add(go.apply(ø,arguments)); }; // starting out with initial channel messages? if (token.channel.messages.length > 0) { // fake back-pressure blocking for each token.channel.put_queue = token.channel.messages.map(function $$map(){ // make a notifiable iterable for 'put' blocking return ASQ.iterable() .then(function $$then(){ unblock(token.channel.take_queue.shift()); return !token.channel.closed; }); }); } } // initialize the generator it = gen.apply(ø,[token.channel].concat(args)); (function iterate(){ function next() { // keep going with next step in goroutine? if (!done) { iterate(); } // unblock overall goroutine handling to // continue with other goroutines else { unblock(); } } // has a resumption value been achieved yet? if (!ret) { // try to resume the goroutine try { // resume with injected exception? if (err) { ret = it.throw(err); err = null; } // resume normally else { ret = it.next(msg); } } // resumption failed, so bail catch (e) { done = true; err = e; msg = null; unblock(); return; } // keep track of the result of the resumption done = ret.done; ret = ret.value; type = typeof ret; // if this goroutine is complete, unblock the // overall goroutine handling if (done) { unblock(); } // received a thenable/promise back? if (isPromise(ret)) { ret = ASQ().promise(ret); } // wait for the value? if (ASQ.isSequence(ret)) { ret.val(function $$val(){ ret = null; msg = arguments.length > 1 ? ASQ.messages.apply(ø,arguments) : arguments[0] ; next(); }) .or(function $$or(){ ret = null; msg = arguments.length > 1 ? ASQ.messages.apply(ø,arguments) : arguments[0] ; if (msg instanceof Error) { err = msg; msg = null; } next(); }); } // immediate value, prepare it to go right back in else { msg = ret; ret = null; next(); } } })(); // keep this goroutine alive until completion while (!done) { // transfer control to another goroutine yield token; // need to block overall goroutine handling // while idle? if (!done && !token.block) { // wait here while idle yield (token.block = ASQ.iterable()); token.block = false; } } // this goroutine is done now token.go_count--; // all goroutines done? if (token.go_count === 0) { // any lingering blocking need to be cleaned up? unblock(); // capture any untaken messages msg = ASQ.messages.apply(ø,token.messages); // need to implicitly force-close channel? if (token.channel && !token.channel.closed) { token.channel.closed = true; token.channel.put_queue.length = token.channel.take_queue.length = 0; token.channel.close = token.channel.go = token.channel.messages = null; } token.channel = null; } // make sure leftover error or message are // passed along if (err) { throw err; } else if (token.go_count === 0) { return msg; } else { return token; } }; } ASQ.csp = { chan: channel, put: put, putAsync: putAsync, take: take, takeAsync: takeAsync, takem: takem, takemAsync: takemAsync, alts: alts, altsAsync: altsAsync, timeout: timeout, go: go, CLOSED: {} }; })(); // "ASQ.iterable()" (function IIFE(){ var template; ASQ.iterable = function $$iterable() { function throwSequenceErrors() { throw (sequence_errors.length === 1 ? sequence_errors[0] : sequence_errors); } function notifyErrors() { var fn; seq_tick = null; if (seq_error) { if (or_queue.length === 0 && !error_reported) { error_reported = true; throwSequenceErrors(); } while (or_queue.length > 0) { error_reported = true; fn = or_queue.shift(); try { fn.apply(ø,sequence_errors); } catch (err) { if (checkBranding(err)) { sequence_errors = sequence_errors.concat(err); } else { sequence_errors.push(err); } if (or_queue.length === 0) { throwSequenceErrors(); } } } } } function val() { if (seq_error || seq_aborted || arguments.length === 0) { return sequence_api; } var args = ARRAY_SLICE.call(arguments).map(function mapper(arg){ if (typeof arg != "function") return function $$val() { return arg; }; else return arg; }); val_queue.push.apply(val_queue,args); return sequence_api; } function or() { if (seq_aborted || arguments.length === 0) { return sequence_api; } or_queue.push.apply(or_queue,arguments); if (!seq_tick) { seq_tick = schedule(notifyErrors); } return sequence_api; } function pipe() { if (seq_aborted || arguments.length === 0) { return sequence_api; } ARRAY_SLICE.call(arguments) .forEach(function $$each(fn){ val(fn).or(fn.fail); }); return sequence_api; } function next() { if (seq_error || seq_aborted || val_queue.length === 0) { if (val_queue.length > 0) { $throw$("Sequence cannot be iterated"); } return { done: true }; } try { return { value: val_queue.shift().apply(ø,arguments) }; } catch (err) { if (ASQ.isMessageWrapper(err)) { $throw$.apply(ø,err); } else { $throw$(err); } return {}; } } function $throw$() { if (seq_error || seq_aborted) { return sequence_api; } sequence_errors.push.apply(sequence_errors,arguments); seq_error = true; if (!seq_tick) { seq_tick = schedule(notifyErrors); } return sequence_api; } function $return$(val) { if (seq_error || seq_aborted) { val = void 0; } abort(); return { done: true, value: val }; } function abort() { if (seq_error || seq_aborted) { return; } seq_aborted = true; clearTimeout(seq_tick); seq_tick = null; val_queue.length = or_queue.length = sequence_errors.length = 0; } function duplicate() { var isq; template = { val_queue: val_queue.slice(), or_queue: or_queue.slice() }; isq = ASQ.iterable(); template = null; return isq; } // opt-out of global error reporting for this sequence function defer() { or_queue.push(function $$ignored(){}); return sequence_api; } // *********************************************** // Object branding utilities // *********************************************** function brandIt(obj) { Object.defineProperty(obj,brand,{ enumerable: false, value: true }); return obj; } var sequence_api, seq_error = false, error_reported = false, seq_aborted = false, seq_tick, val_queue = [], or_queue = [], sequence_errors = [] ; // *********************************************** // Setup the ASQ.iterable() public API // *********************************************** sequence_api = brandIt({ val: val, then: val, or: or, pipe: pipe, next: next, "throw": $throw$, "return": $return$, abort: abort, duplicate: duplicate, defer: defer }); // useful for ES6 `for..of` loops, // add `@@iterator` to simply hand back // our iterable sequence itself! sequence_api[(typeof Symbol == "function" && Symbol.iterator) || "@@iterator"] = function $$iter() { return sequence_api; }; // templating the iterable-sequence setup? if (template) { val_queue = template.val_queue.slice(0); or_queue = template.or_queue.slice(0); } // treat ASQ.iterable() constructor parameters as having been // passed to `val()` sequence_api.val.apply(ø,arguments); return sequence_api; }; })(); // "last" ASQ.extend("last",function $$extend(api,internals){ return function $$last() { if (internals("seq_error") || internals("seq_aborted") || arguments.length === 0 ) { return api; } var fns = ARRAY_SLICE.call(arguments); api.then(function $$then(done){ function reset() { finished = true; error_messages.length = 0; success_messages = null; } function complete(trigger) { if (success_messages != null) { // last successful segment's message(s) sent // to main sequence to proceed as success trigger( success_messages.length > 1 ? ASQ.messages.apply(ø,success_messages) : success_messages[0] ); } else { // send errors into main sequence error_messages.length = fns.length; trigger.fail.apply(ø,error_messages); } reset(); } function success(trigger,idx,args) { if (!finished) { completed++; success_messages = args; // all segments complete? if (completed === fns.length) { finished = true; complete(trigger); } } } function failure(trigger,idx,args) { if (!finished && !(idx in error_messages) ) { completed++; error_messages[idx] = args.length > 1 ? ASQ.messages.apply(ø,args) : args[0] ; } // all segments complete? if (!finished && completed === fns.length ) { finished = true; complete(trigger); } } var completed = 0, error_messages = [], finished = false, sq = ASQ.apply(ø,ARRAY_SLICE.call(arguments,1)), success_messages ; wrapGate(sq,fns,success,failure,reset); sq.pipe(done); }); return api; }; }); // "map" ASQ.extend("map",function $$extend(api,internals){ return function $$map(pArr,pEach) { if (internals("seq_error") || internals("seq_aborted")) { return api; } api.seq(function $$seq(){ var tmp, args = ARRAY_SLICE.call(arguments), arr = pArr, each = pEach; // if missing `map(..)` args, use value-messages (if any) if (!each) each = args.shift(); if (!arr) arr = args.shift(); // if arg types in reverse order (each,arr), swap if (typeof arr === "function" && Array.isArray(each)) { tmp = arr; arr = each; each = tmp; } return ASQ.apply(ø,args) .gate.apply(ø,arr.map(function $$map(item){ return function $$segment(){ each.apply(ø,[item].concat(ARRAY_SLICE.call(arguments))); }; })); }) .val(function $$val(){ // collect all gate segment output into one value-message // Note: return a normal array here, not a message wrapper! return ARRAY_SLICE.call(arguments); }); return api; }; }); // "none" ASQ.extend("none",function $$extend(api,internals){ return function $$none() { if (internals("seq_error") || internals("seq_aborted") || arguments.length === 0 ) { return api; } var fns = ARRAY_SLICE.call(arguments); api.then(function $$then(done){ function reset() { finished = true; error_messages.length = 0; success_messages.length = 0; } function complete(trigger) { if (success_messages.length > 0) { // any successful segment's message(s) sent // to main sequence to proceed as **error** success_messages.length = fns.length; trigger.fail.apply(ø,success_messages); } else { // send errors as **success** to main sequence error_messages.length = fns.length; trigger.apply(ø,error_messages); } reset(); } function success(trigger,idx,args) { if (!finished) { completed++; success_messages[idx] = args.length > 1 ? ASQ.messages.apply(ø,args) : args[0] ; // all segments complete? if (completed === fns.length) { finished = true; complete(trigger); } } } function failure(trigger,idx,args) { if (!finished && !(idx in error_messages) ) { completed++; error_messages[idx] = args.length > 1 ? ASQ.messages.apply(ø,args) : args[0] ; } // all segments complete? if (!finished && completed === fns.length ) { finished = true; complete(trigger); } } var completed = 0, error_messages = [], finished = false, sq = ASQ.apply(ø,ARRAY_SLICE.call(arguments,1)), success_messages = [] ; wrapGate(sq,fns,success,failure,reset); sq.pipe(done); }); return api; }; }); // "pThen" ASQ.extend("pThen",function $$extend(api,internals){ return function $$pthen(success,failure) { if (internals("seq_aborted")) { return api; } var ignore_success_handler = false, ignore_failure_handler = false; if (typeof success === "function") { api.then(function $$then(done){ if (!ignore_success_handler) { var ret, msgs = ASQ.messages.apply(ø,arguments); msgs.shift(); if (msgs.length === 1) { msgs = msgs[0]; } ignore_failure_handler = true; try { ret = success(msgs); } catch (err) { if (!ASQ.isMessageWrapper(err)) { err = [err]; } done.fail.apply(ø,err); return; } // returned a sequence? if (ASQ.isSequence(ret)) { ret.pipe(done); } // returned a message wrapper? else if (ASQ.isMessageWrapper(ret)) { done.apply(ø,ret); } // returned a promise/thenable? else if (isPromise(ret)) { ret.then(done,done.fail); } // just a normal value to pass along else { done(ret); } } else { done.apply(ø,ARRAY_SLICE.call(arguments,1)); } }); } if (typeof failure === "function") { api.or(function $$or(){ if (!ignore_failure_handler) { var ret, msgs = ASQ.messages.apply(ø,arguments), smgs, or_queue = ARRAY_SLICE.call(internals("or_queue")) ; if (msgs.length === 1) { msgs = msgs[0]; } ignore_success_handler = true; // NOTE: if this call throws, that'll automatically // be handled by core as we'd want it to be ret = failure(msgs); // if we get this far: // first, inject return value (if any) as // next step's sequence messages smgs = internals("sequence_messages"); smgs.length = 0; if (typeof ret !== "undefined") { if (!ASQ.isMessageWrapper(ret)) { ret = [ret]; } smgs.push.apply(smgs,ret); } // reset internal error state, because we've exclusively // handled any errors up to this point of the sequence internals("sequence_errors").length = 0; internals("seq_error",false); internals("then_ready",true); // temporarily empty the or-queue internals("or_queue").length = 0; // make sure to schedule success-procession on the chain api.val(function $$val(){ // pass thru messages return ASQ.messages.apply(ø,arguments); }); // at next cycle, reinstate the or-queue (if any) if (or_queue.length > 0) { schedule(function $$schedule(){ api.or.apply(ø,or_queue); }); } } }); } return api; }; }); // "pCatch" ASQ.extend("pCatch",function $$extend(api,internals){ return function $$pcatch(failure) { if (internals("seq_aborted")) { return api; } api.pThen(void 0,failure); return api; }; }); // "race" ASQ.extend("race",function $$extend(api,internals){ return function $$race() { if (internals("seq_error") || internals("seq_aborted") || arguments.length === 0 ) { return api; } var fns = ARRAY_SLICE.call(arguments) .map(function $$map(v){ var def; // tap any directly-provided sequences immediately if (ASQ.isSequence(v)) { def = { seq: v }; tapSequence(def); return function $$fn(done) { def.seq.pipe(done); }; } else return v; }); api.then(function $$then(done){ var args = ARRAY_SLICE.call(arguments); fns.forEach(function $$each(fn){ fn.apply(ø,args); }); }); return api; }; }); // "react" (reactive sequences) ASQ.react = function $$react(reactor) { function next() { if (template) { var sq = template.duplicate(); sq.unpause.apply(ø,arguments); return sq; } return ASQ(function $$asq(){ throw "Disabled Sequence"; }); } function registerTeardown(fn) { if (template && typeof fn === "function") { teardowns.push(fn); } } var template = ASQ().duplicate(), teardowns = [] ; // add reactive sequence kill switch template.stop = function $$stop() { if (template) { template = null; teardowns.forEach(Function.call,Function.call); teardowns.length = 0; } }; next.onStream = function $$onStream() { ARRAY_SLICE.call(arguments) .forEach(function $$each(stream){ stream.on("data",next); stream.on("error",next); }); }; next.unStream = function $$unStream() { ARRAY_SLICE.call(arguments) .forEach(function $$each(stream){ stream.removeListener("data",next); stream.removeListener("error",next); }); }; // make sure `reactor(..)` is called async ASQ.__schedule(function $$schedule(){ reactor.call(template,next,registerTeardown); }); return template; }; // "react" helpers (function IIFE(){ function tapSequences() { function tapSequence(seq) { // temporary `trigger` which, if called before being replaced // below, creates replacement proxy sequence with the // event message(s) re-fired function trigger() { var args = ARRAY_SLICE.call(arguments); def.seq = ASQ.react(function $$react(next){ next.apply(ø,args); }); } if (ASQ.isSequence(seq)) { var def = { seq: seq }; // listen for events from the sequence-stream seq.val(function $$val(){ trigger.apply(ø,arguments); return ASQ.messages.apply(ø,arguments); }); // make a reactive sequence to act as a proxy to the original // sequence def.seq = ASQ.react(function $$react(next){ // replace the temporary trigger (created above) // with this proxy's trigger trigger = next; }); return def; } } return ARRAY_SLICE.call(arguments) .map(tapSequence) .filter(Boolean); } function createReactOperator(buffer) { return function $$react$operator(){ function reactor(next,registerTeardown){ function processSequence(def) { // sequence-stream event listener function trigger() { var args = ASQ.messages.apply(ø,arguments); // still observing sequence-streams? if (seqs && seqs.length > 0) { // store event message(s), if any seq_events[seq_id] = [].concat( buffer ? seq_events[seq_id] : [], args.length > 0 ? [args] : undefined ); // collect event message(s) across the // sequence-stream sources var messages = seq_events.reduce(function reducer(msgs,eventList,idx){ if (eventList.length > 0) msgs.push(eventList[0]); return msgs; },[]); // did all sequence-streams get an event? if (messages.length == seq_events.length) { if (messages.length == 1) messages = messages[0]; // fire off reactive sequence instance next.apply(ø,messages); // discard stored event message(s) seq_events.forEach(function $$each(eventList){ eventList.shift(); }); } } // keep sequence going return args; } var seq_id = seq_events.length; seq_events.push([]); def.seq.val(trigger); } // process all sequence-streams seqs.forEach(processSequence); // listen for stop() of reactive sequence registerTeardown(function $$teardown(){ seqs = seq_events = null; }); } var seq_events = [], // observe all sequence-streams seqs = tapSequences.apply(null,arguments) ; if (seqs.length == 0) return; return ASQ.react(reactor); }; } ASQ.react.all = ASQ.react.zip = createReactOperator(/*buffer=*/true); ASQ.react.latest = ASQ.react.combine = createReactOperator(/*buffer=false*/); ASQ.react.any = ASQ.react.merge = function $$react$any(){ function reactor(next,registerTeardown){ function processSequence(def){ function trigger(){ var args = ASQ.messages.apply(ø,arguments); // still observing sequence-streams? if (seqs && seqs.length > 0) { // fire off reactive sequence instance next.apply(ø,args); } // keep sequence going return args; } // sequence-stream event listener def.seq.val(trigger); } // observe all sequence-streams seqs.forEach(processSequence); // listen for stop() of reactive sequence registerTeardown(function $$teardown(){ seqs = null; }); } // observe all sequence-streams var seqs = tapSequences.apply(null,arguments); if (seqs.length == 0) return; return ASQ.react(reactor); }; ASQ.react.distinct = function $$react$distinct(seq){ function reactor(next,registerTeardown){ function trigger(){ function isDuplicate(msgs){ return ( msgs.length == messages.length && msgs.every(function $$every(val,idx){ return val === messages[idx]; }) ); } var messages = ASQ.messages.apply(ø,arguments); // still observing? if (prev_messages) { // any messages to check against? if (messages.length > 0) { // messages already sent before? if (prev_messages.some(isDuplicate)) { // bail on duplicate messages return messages; } // save messages for future distinct checking prev_messages.push(messages); } // fire off reactive sequence instance next.apply(ø,messages); } // keep sequence going return messages; } // sequence-stream event listener def.seq.val(trigger); // listen for stop() of reactive sequence registerTeardown(function $$teardown(){ def = prev_messages = null; }); } var prev_messages = [], // observe sequence-stream def = tapSequences(seq)[0] ; if (!def) return; return ASQ.react(reactor); }; ASQ.react.fromObservable = function $$react$from$observable(obsv){ function reactor(next,registerTeardown){ // process buffer (if any) buffer.forEach(next); buffer.length = 0; // start non-buffered notifications? if (!buffer.complete) { notify = next; } registerTeardown(function $$teardown(){ obsv.dispose(); }); } function notify(v) { buffer.push(v); } var buffer = []; obsv.subscribe( function $$on$next(v){ notify(v); }, function $$on$error(){}, function $$on$complete(){ buffer.complete = true; obsv.dispose(); } ); return ASQ.react(reactor); }; ASQ.extend("toObservable",function $$extend(api,internals){ return function $$to$observable(){ function init(observer) { function define(pair){ function listen(){ var args = ASQ.messages.apply(ø,arguments); observer[pair[1]].apply(observer, args.length == 1 ? [args[0]] : args ); return args; } api[pair[0]](listen); } [["val","onNext"],["or","onError"]] .forEach(define); } return Rx.Observable.create(init); }; }); })(); // "runner" ASQ.extend("runner",function $$extend(api,internals){ return function $$runner() { if (internals("seq_error") || internals("seq_aborted") || arguments.length === 0 ) { return api; } var args = ARRAY_SLICE.call(arguments); api .then(function $$then(mainDone){ function wrap(v) { // function? expected to produce an iterator // (like a generator) or a promise if (typeof v === "function") { // call function passing in the control token // note: neutralize `this` in call to prevent // unexpected behavior v = v.call(ø,next_val); // promise returned (ie, from async function)? if (isPromise(v)) { // wrap it in iterable sequence v = ASQ.iterable(v); } } // an iterable sequence? duplicate it (in case of multiple runs) else if (ASQ.isSequence(v) && "next" in v) { v = v.duplicate(); } // wrap anything else in iterable sequence else { v = ASQ.iterable(v); } // a sequence to tap for errors? if (ASQ.isSequence(v)) { // listen for any sequence failures v.or(function $$or(){ // signal iteration-error mainDone.fail.apply(ø,arguments); }); } return v; } function addWrapped() { iterators.push.apply( iterators, ARRAY_SLICE.call(arguments).map(wrap) ); } var iterators = args, token = { messages: ARRAY_SLICE.call(arguments,1), add: addWrapped }, iter, ret, next_val = token ; // map co-routines to round-robin list of iterators iterators = iterators.map(wrap); // async iteration of round-robin list (function iterate(){ // get next co-routine in list iter = iterators.shift(); // process the iteration try { // multiple messages to send to an iterable // sequence? if (ASQ.isMessageWrapper(next_val) && ASQ.isSequence(iter) ) { ret = iter.next.apply(iter,next_val); } else { ret = iter.next(next_val); } } catch (err) { return mainDone.fail(err); } // bail on run in aborted sequence if (internals("seq_aborted")) return; // was the control token yielded? if (ret.value === token) { // round-robin: put co-routine back into the list // at the end where it was so it can be processed // again on next loop-iteration iterators.push(iter); next_val = token; schedule(iterate); // async recurse } else { // not a recognized ASQ instance returned? if (!ASQ.isSequence(ret.value)) { // received a thenable/promise back? if (isPromise(ret.value)) { // wrap in a sequence ret.value = ASQ().promise(ret.value); } // thunk yielded? else if (typeof ret.value === "function") { // wrap thunk call in a sequence var fn = ret.value; ret.value = ASQ(function $$ASQ(done){ fn(done.errfcb); }); } // message wrapper returned? else if (ASQ.isMessageWrapper(ret.value)) { // wrap message(s) in a sequence ret.value = ASQ.apply(ø, // don't let `apply(..)` discard an empty message // wrapper! instead, pass it along as its own value // itself. ret.value.length > 0 ? ret.value : ASQ.messages(undefined) ); } // non-undefined value returned? else if (typeof ret.value !== "undefined") { // wrap the value in a sequence ret.value = ASQ(ret.value); } else { // make an empty sequence ret.value = ASQ(); } } ret.value .val(function $$val(){ // bail on run in aborted sequence if (internals("seq_aborted")) return; if (arguments.length > 0) { // save any return messages for input // to next iteration next_val = arguments.length > 1 ? ASQ.messages.apply(ø,arguments) : arguments[0] ; } // still more to iterate? if (!ret.done) { // was the control token passed along? if (next_val === token) { // round-robin: put co-routine back into the list // at the end, so that the the next iterator can be // processed on next loop-iteration iterators.push(iter); } else { // put co-routine back in where it just // was so it can be processed again on // next loop-iteration iterators.unshift(iter); } } // still have some co-routine runs to process? if (iterators.length > 0) { iterate(); // async recurse } // all done! else { // previous value message? if (typeof next_val !== "undefined") { // not a message wrapper array? if (!ASQ.isMessageWrapper(next_val)) { // wrap value for the subsequent `apply(..)` next_val = [next_val]; } } else { // nothing to affirmatively pass along next_val = []; } // signal done with all co-routine runs mainDone.apply(ø,next_val); } }) .or(function $$or(){ // bail on run in aborted sequence if (internals("seq_aborted")) return; try { // if an error occurs in the step-continuation // promise or sequence, throw it back into the // generator or iterable-sequence iter["throw"].apply(iter,arguments); } catch (err) { // if an error comes back out of after the throw, // pass it out to the main sequence, as iteration // must now be complete mainDone.fail(err); } }); } })(); }); return api; }; }); // "toPromise" ASQ.extend("toPromise",function $$extend(api,internals){ return function $$to$promise() { return new Promise(function $$executor(resolve,reject){ api .val(function $$val(){ var args = ARRAY_SLICE.call(arguments); resolve.call(ø,args.length > 1 ? args : args[0]); return ASQ.messages.apply(ø,args); }) .or(function $$or(){ var args = ARRAY_SLICE.call(arguments); reject.call(ø,args.length > 1 ? args : args[0]); }); }); }; }); // "try" ASQ.extend("try",function $$extend(api,internals){ return function $$try() { if (internals("seq_error") || internals("seq_aborted") || arguments.length === 0 ) { return api; } var fns = ARRAY_SLICE.call(arguments) .map(function $$map(fn){ return function $$then(mainDone) { var main_args = ARRAY_SLICE.call(arguments), sq = ASQ.apply(ø,main_args.slice(1)) ; sq .then(function $$inner$then(){ fn.apply(ø,arguments); }) .val(function $$val(){ mainDone.apply(ø,arguments); }) .or(function $$inner$or(){ var msgs = ASQ.messages.apply(ø,arguments); // failed, so map error(s) as `catch` mainDone({ "catch": msgs.length > 1 ? msgs : msgs[0] }); }); }; }); api.then.apply(ø,fns); return api; }; }); // "until" ASQ.extend("until",function $$extend(api,internals){ return function $$until() { if (internals("seq_error") || internals("seq_aborted") || arguments.length === 0 ) { return api; } var fns = ARRAY_SLICE.call(arguments) .map(function $$map(fn){ return function $$then(mainDone) { var main_args = ARRAY_SLICE.call(arguments), sq = ASQ.apply(ø,main_args.slice(1)) ; sq .then(function $$inner$then(){ var args = ARRAY_SLICE.call(arguments); args[0]["break"] = function $$break(){ mainDone.fail.apply(ø,arguments); sq.abort(); }; fn.apply(ø,args); }) .val(function $$val(){ mainDone.apply(ø,arguments); }) .or(function $$inner$or(){ // failed, retry $$then.apply(ø,main_args); }); }; }); api.then.apply(ø,fns); return api; }; }); // "waterfall" ASQ.extend("waterfall",function $$extend(api,internals){ return function $$waterfall() { if (internals("seq_error") || internals("seq_aborted") || arguments.length === 0 ) { return api; } var fns = ARRAY_SLICE.call(arguments); api.then(function $$then(done){ var msgs = ASQ.messages(), sq = ASQ.apply(ø,ARRAY_SLICE.call(arguments,1)) ; fns.forEach(function $$each(fn){ sq.then(fn) .val(function $$val(){ var args = ASQ.messages.apply(ø,arguments); msgs.push(args.length > 1 ? args : args[0]); return msgs; }); }); sq.pipe(done); }); return api; }; }); // "wrap" ASQ.wrap = function $$wrap(fn,opts) { function checkThis(t,o) { return (!t || (typeof window != "undefined" && t === window) || (typeof global != "undefined" && t === global) ) ? o : t; } var errfcb, params_first, act, this_obj; opts = (opts && typeof opts == "object") ? opts : {}; if ( (opts.errfcb && opts.splitcb) || (opts.errfcb && opts.simplecb) || (opts.splitcb && opts.simplecb) || ("errfcb" in opts && !opts.errfcb && !opts.splitcb && !opts.simplecb) || (opts.params_first && opts.params_last) ) { throw Error("Invalid options"); } // initialize default flags this_obj = (opts["this"] && typeof opts["this"] == "object") ? opts["this"] : ø; errfcb = opts.errfcb || !(opts.splitcb || opts.simplecb); params_first = !!opts.params_first || (!opts.params_last && !("params_first" in opts || opts.params_first)) || ("params_last" in opts && !opts.params_first && !opts.params_last) ; if (params_first) { act = "push"; } else { act = "unshift"; } if (opts.gen) { return function $$wrapped$gen() { return ASQ.apply(ø,arguments).runner(fn); }; } if (errfcb) { return function $$wrapped$errfcb() { var args = ARRAY_SLICE.call(arguments), _this = checkThis(this,this_obj) ; return ASQ(function $$asq(done){ args[act](done.errfcb); fn.apply(_this,args); }); }; } if (opts.splitcb) { return function $$wrapped$splitcb() { var args = ARRAY_SLICE.call(arguments), _this = checkThis(this,this_obj) ; return ASQ(function $$asq(done){ args[act](done,done.fail); fn.apply(_this,args); }); }; } if (opts.simplecb) { return function $$wrapped$simplecb() { var args = ARRAY_SLICE.call(arguments), _this = checkThis(this,this_obj) ; return ASQ(function $$asq(done){ args[act](done); fn.apply(_this,args); }); }; } }; // just return `ASQ` itself for convenience sake return ASQ; });
files/rxjs/2.1.10/rx.js
l3dlp/jsdelivr
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. (function (window, undefined) { var freeExports = typeof exports == 'object' && exports, freeModule = typeof module == 'object' && module && module.exports == freeExports && module, freeGlobal = typeof global == 'object' && global; if (freeGlobal.global === freeGlobal) { window = freeGlobal; } /** * @name Rx * @type Object */ var Rx = { Internals: {} }; // Defaults function noop() { } function identity(x) { return x; } function defaultNow() { return new Date().getTime(); } function defaultComparer(x, y) { return isEqual(x, y); } function defaultSubComparer(x, y) { return x - y; } function defaultKeySerializer(x) { return x.toString(); } function defaultError(err) { throw err; } // Errors var sequenceContainsNoElements = 'Sequence contains no elements.'; var argumentOutOfRange = 'Argument out of range'; var objectDisposed = 'Object has been disposed'; function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } /** Used to determine if values are of the language type Object */ var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 suportNodeClass; try { suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch(e) { suportNodeClass = true; } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } function isArguments(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } function isFunction(value) { return typeof value == 'function'; } // fallback for older versions of Chrome and Safari if (isFunction(/x/)) { isFunction = function(value) { return typeof value == 'function' && toString.call(value) == funcClass; }; } var isEqual = Rx.Internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { var result; // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && !(a && objectTypes[type]) && !(b && objectTypes[otherType])) { return false; } // exit early for `null` and `undefined`, avoiding ES3's Function#call behavior // http://es5.github.io/#x15.3.4.4 if (a == null || b == null) { return a === b; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0`, treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b // but treat `+0` vs. `-0` as not equal : (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!suportNodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !supportsArgsClass && isArguments(a) ? Object : a.constructor, ctorB = !supportsArgsClass && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !( isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB )) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { length = a.length; size = b.length; // compare lengths to determine if a deep comparison is necessary result = size == a.length; // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } return result; } // deep compare each object for(var key in b) { if (hasOwnProperty.call(b, key)) { // count properties and deep compare each property value size++; return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], b[key], stackA, stackB)); } } if (result) { // ensure both objects have the same number of properties for (var key in a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } } } stackA.pop(); stackB.pop(); return result; } var slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var hasProp = {}.hasOwnProperty; /** @private */ var inherits = this.inherits = Rx.Internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; /** @private */ var addProperties = Rx.Internals.addProperties = function (obj) { var sources = slice.call(arguments, 1); for (var i = 0, len = sources.length; i < len; i++) { var source = sources[i]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.Internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; // Collection polyfills function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // Utilities if (!Function.prototype.bind) { Function.prototype.bind = function (that) { var target = this, args = slice.call(arguments, 1); var bound = function () { if (this instanceof bound) { function F() { } F.prototype = target.prototype; var self = new F(); var result = target.apply(self, args.concat(slice.call(arguments))); if (Object(result) === result) { return result; } return self; } else { return target.apply(that, args.concat(slice.call(arguments))); } }; return bound; }; } var boxedString = Object("a"), splitString = boxedString[0] != "a" || !(0 in boxedString); if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var object = Object(this), self = splitString && {}.toString.call(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if ({}.toString.call(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, object)) { return false; } } return true; }; } if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var object = Object(this), self = splitString && {}.toString.call(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, result = Array(length), thisp = arguments[1]; if ({}.toString.call(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) result[i] = fun.call(thisp, self[i], i, object); } return result; }; } if (!Array.prototype.filter) { Array.prototype.filter = function (predicate) { var results = [], item, t = new Object(this); for (var i = 0, len = t.length >>> 0; i < len; i++) { item = t[i]; if (i in t && predicate.call(arguments[1], item, i, t)) { results.push(item); } } return results; }; } if (!Array.isArray) { Array.isArray = function (arg) { return Object.prototype.toString.call(arg) == '[object Array]'; }; } if (!Array.prototype.indexOf) { Array.prototype.indexOf = function indexOf(searchElement) { var t = Object(this); var len = t.length >>> 0; if (len === 0) { return -1; } var n = 0; if (arguments.length > 1) { n = Number(arguments[1]); if (n !== n) { n = 0; } else if (n !== 0 && n != Infinity && n !== -Infinity) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } if (n >= len) { return -1; } var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) { if (k in t && t[k] === searchElement) { return k; } } return -1; }; } // Collections var IndexedItem = function (id, value) { this.id = id; this.value = value; }; IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); if (c === 0) { c = this.id - other.id; } return c; }; // Priority Queue for Scheduling var PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { if (index === undefined) { index = 0; } if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; delete this.items[this.length]; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { this.disposables = argsOrArray(arguments, 0); this.isDisposed = false; this.length = this.disposables.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * * @memberOf CompositeDisposable# * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. * * @memberOf CompositeDisposable# */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. * * @memberOf CompositeDisposable# */ CompositeDisposablePrototype.clear = function () { var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } }; /** * Determines whether the CompositeDisposable contains a specific disposable. * * @memberOf CompositeDisposable# * @param {Mixed} item Disposable to search for. * @returns {Boolean} true if the disposable was found; otherwise, false. */ CompositeDisposablePrototype.contains = function (item) { return this.disposables.indexOf(item) !== -1; }; /** * Converts the existing CompositeDisposable to an array of disposables * * @memberOf CompositeDisposable# * @returns {Array} An array of disposable objects. */ CompositeDisposablePrototype.toArray = function () { return this.disposables.slice(0); }; /** * Provides a set of static methods for creating Disposables. * * @constructor * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** * Performs the task of cleaning up resources. * * @memberOf Disposable# */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * * @static * @memberOf Disposable * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. * * @static * @memberOf Disposable */ var disposableEmpty = Disposable.empty = { dispose: noop }; /** * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. * * @constructor */ var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = function () { this.isDisposed = false; this.current = null; }; var SingleAssignmentDisposablePrototype = SingleAssignmentDisposable.prototype; /** * Gets or sets the underlying disposable. After disposal, the result of getting this method is undefined. * * @memberOf SingleAssignmentDisposable# * @param {Disposable} [value] The new underlying disposable. * @returns {Disposable} The underlying disposable. */ SingleAssignmentDisposablePrototype.disposable = function (value) { return !value ? this.getDisposable() : this.setDisposable(value); }; /** * Gets the underlying disposable. After disposal, the result of getting this method is undefined. * * @memberOf SingleAssignmentDisposable# * @returns {Disposable} The underlying disposable. */ SingleAssignmentDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * * @memberOf SingleAssignmentDisposable# * @param {Disposable} value The new underlying disposable. */ SingleAssignmentDisposablePrototype.setDisposable = function (value) { if (this.current) { throw new Error('Disposable has already been assigned'); } var shouldDispose = this.isDisposed; if (!shouldDispose) { this.current = value; } if (shouldDispose && value) { value.dispose(); } }; /** * Disposes the underlying disposable. * * @memberOf SingleAssignmentDisposable# */ SingleAssignmentDisposablePrototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } if (old) { old.dispose(); } }; /** * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. * * @constructor */ var SerialDisposable = Rx.SerialDisposable = function () { this.isDisposed = false; this.current = null; }; /** * Gets the underlying disposable. * @return The underlying disposable</returns> */ SerialDisposable.prototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * * @memberOf SerialDisposable# * @param {Disposable} value The new underlying disposable. */ SerialDisposable.prototype.setDisposable = function (value) { var shouldDispose = this.isDisposed, old; if (!shouldDispose) { old = this.current; this.current = value; } if (old) { old.dispose(); } if (shouldDispose && value) { value.dispose(); } }; /** * Gets or sets the underlying disposable. * If the SerialDisposable has already been disposed, assignment to this property causes immediate disposal of the given disposable object. Assigning this property disposes the previous disposable object. * * @memberOf SerialDisposable# * @param {Disposable} [value] The new underlying disposable. * @returns {Disposable} The underlying disposable. */ SerialDisposable.prototype.disposable = function (value) { if (!value) { return this.getDisposable(); } else { this.setDisposable(value); } }; /** * Disposes the underlying disposable as well as all future replacements. * * @memberOf SerialDisposable# */ SerialDisposable.prototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } if (old) { old.dispose(); } }; /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { /** * @constructor * @private */ function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } /** @private */ InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed) { if (!this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed * * @memberOf RefCountDisposable# */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed) { if (!this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * * @memberOf RefCountDisposable# * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.H */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); /** * @constructor * @private */ function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler, this.disposable = disposable, this.isDisposed = false; } /** * @private * @memberOf ScheduledDisposable# */ ScheduledDisposable.prototype.dispose = function () { var parent = this; this.scheduler.schedule(function () { if (!parent.isDisposed) { parent.isDisposed = true; parent.disposable.dispose(); } }); }; /** * @private * @constructor */ function ScheduledItem(scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } /** * @private * @memberOf ScheduledItem# */ ScheduledItem.prototype.invoke = function () { this.disposable.disposable(this.invokeCore()); }; /** * @private * @memberOf ScheduledItem# */ ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; /** * @private * @memberOf ScheduledItem# */ ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; /** * @private * @memberOf ScheduledItem# */ ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { /** * @constructor * @private */ function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. * * @memberOf Scheduler# * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. */ schedulerProto.catchException = function (handler) { return new CatchScheduler(this, handler); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * * @memberOf Scheduler# * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ schedulerProto.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, function () { action(); }); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * * @memberOf Scheduler# * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ schedulerProto.schedulePeriodicWithState = function (state, period, action) { var s = state, id = window.setInterval(function () { s = action(s); }, period); return disposableCreate(function () { window.clearInterval(id); }); }; /** * Schedules an action to be executed. * * @memberOf Scheduler# * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * * @memberOf Scheduler# * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * * @memberOf Scheduler# * @param {Function} action Action to execute. * @param {Number}dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * * @memberOf Scheduler# * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * * @memberOf Scheduler# * @param {Function} action Action to execute. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * * @memberOf Scheduler# * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** * Schedules an action to be executed recursively. * * @memberOf Scheduler# * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * * @memberOf Scheduler# * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState({ first: state, second: action }, function (s, p) { return invokeRecImmediate(s, p); }); }; /** * Schedules an action to be executed recursively after a specified relative due time. * * @memberOf Scheduler * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * Schedules an action to be executed recursively after a specified relative due time. * * @memberOf Scheduler * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * * @memberOf Scheduler * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * * @memberOf Scheduler * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * * @static * @memberOf Scheduler * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { if (timeSpan < 0) { timeSpan = 0; } return timeSpan; }; return Scheduler; }()); var schedulerNoBlockError = 'Scheduler is not allowed to block the thread'; /** * Gets a scheduler that schedules work immediately on the current thread. * * @memberOf Scheduler */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } function scheduleRelative(state, dueTime, action) { if (dueTime > 0) throw new Error(schedulerNoBlockError); return action(this, state); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; /** * @private * @constructor */ function Trampoline() { queue = new PriorityQueue(4); } /** * @private * @memberOf Trampoline */ Trampoline.prototype.dispose = function () { queue = null; }; /** * @private * @memberOf Trampoline */ Trampoline.prototype.run = function () { var item; while (queue.length > 0) { item = queue.dequeue(); if (!item.isCancelled()) { while (item.dueTime - Scheduler.now() > 0) { } if (!item.isCancelled()) { item.invoke(); } } } }; function scheduleNow(state, action) { return this.scheduleWithRelativeAndState(state, 0, action); } function scheduleRelative(state, dueTime, action) { var dt = this.now() + Scheduler.normalize(dueTime), si = new ScheduledItem(this, state, action, dt), t; if (!queue) { t = new Trampoline(); try { queue.enqueue(si); t.run(); } catch (e) { throw e; } finally { t.dispose(); } } else { queue.enqueue(si); } return si.disposable; } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); currentScheduler.scheduleRequired = function () { return queue === null; }; currentScheduler.ensureTrampoline = function (action) { if (queue === null) { return this.schedule(action); } else { return action(); } }; return currentScheduler; }()); /** * @private */ var SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } /** * @constructor * @private */ function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); /** Provides a set of extension methods for virtual time scheduling. */ Rx.VirtualTimeScheduler = (function (_super) { function localNow() { return this.toDateTimeOffset(this.clock); } function scheduleNow(state, action) { return this.scheduleAbsoluteWithState(state, this.clock, action); } function scheduleRelative(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action); } function invokeAction(scheduler, action) { action(); return disposableEmpty; } inherits(VirtualTimeScheduler, _super); /** * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. * * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function VirtualTimeScheduler(initialClock, comparer) { this.clock = initialClock; this.comparer = comparer; this.isEnabled = false; this.queue = new PriorityQueue(1024); _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. * * @memberOf VirtualTimeScheduler# * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) { var s = new SchedulePeriodicRecursive(this, state, period, action); return s.start(); }; /** * Schedules an action to be executed after dueTime. * * @memberOf VirtualTimeScheduler# * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) { var runAt = this.add(this.clock, dueTime); return this.scheduleAbsoluteWithState(state, runAt, action); }; /** * Schedules an action to be executed at dueTime. * * @memberOf VirtualTimeScheduler# * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) { return this.scheduleRelativeWithState(action, dueTime, invokeAction); }; /** * Starts the virtual time scheduler. * * @memberOf VirtualTimeScheduler# */ VirtualTimeSchedulerPrototype.start = function () { var next; if (!this.isEnabled) { this.isEnabled = true; do { next = this.getNext(); if (next !== null) { if (this.comparer(next.dueTime, this.clock) > 0) { this.clock = next.dueTime; } next.invoke(); } else { this.isEnabled = false; } } while (this.isEnabled); } }; /** * Stops the virtual time scheduler. * * @memberOf VirtualTimeScheduler# */ VirtualTimeSchedulerPrototype.stop = function () { this.isEnabled = false; }; /** * Advances the scheduler's clock to the specified time, running all work till that point. * * @param {Number} time Absolute time to advance the scheduler's clock to. */ VirtualTimeSchedulerPrototype.advanceTo = function (time) { var next; var dueToClock = this.comparer(this.clock, time); if (this.comparer(this.clock, time) > 0) { throw new Error(argumentOutOfRange); } if (dueToClock === 0) { return; } if (!this.isEnabled) { this.isEnabled = true; do { next = this.getNext(); if (next !== null && this.comparer(next.dueTime, time) <= 0) { if (this.comparer(next.dueTime, this.clock) > 0) { this.clock = next.dueTime; } next.invoke(); } else { this.isEnabled = false; } } while (this.isEnabled); this.clock = time; } }; /** * Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan. * * @memberOf VirtualTimeScheduler# * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.advanceBy = function (time) { var dt = this.add(this.clock, time); var dueToClock = this.comparer(this.clock, dt); if (dueToClock > 0) { throw new Error(argumentOutOfRange); } if (dueToClock === 0) { return; } return this.advanceTo(dt); }; /** * Advances the scheduler's clock by the specified relative time. * * @memberOf VirtualTimeScheduler# * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.sleep = function (time) { var dt = this.add(this.clock, time); if (this.comparer(this.clock, dt) >= 0) { throw new Error(argumentOutOfRange); } this.clock = dt; }; /** * Gets the next scheduled item to be executed. * * @memberOf VirtualTimeScheduler# * @returns {ScheduledItem} The next scheduled item. */ VirtualTimeSchedulerPrototype.getNext = function () { var next; while (this.queue.length > 0) { next = this.queue.peek(); if (next.isCancelled()) { this.queue.dequeue(); } else { return next; } } return null; }; /** * Schedules an action to be executed at dueTime. * * @memberOf VirtualTimeScheduler# * @param {Scheduler} scheduler Scheduler to execute the action on. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) { return this.scheduleAbsoluteWithState(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * * @memberOf VirtualTimeScheduler# * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) { var self = this, run = function (scheduler, state1) { self.queue.remove(si); return action(scheduler, state1); }, si = new ScheduledItem(self, state, run, dueTime, self.comparer); self.queue.enqueue(si); return si.disposable; }; return VirtualTimeScheduler; }(Scheduler)); /** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */ Rx.HistoricalScheduler = (function (_super) { inherits(HistoricalScheduler, _super); /** * Creates a new historical scheduler with the specified initial clock value. * * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function HistoricalScheduler(initialClock, comparer) { var clock = initialClock == null ? 0 : initialClock; var cmp = comparer || defaultSubComparer; _super.call(this, clock, cmp); } var HistoricalSchedulerProto = HistoricalScheduler.prototype; /** * Adds a relative time value to an absolute time value. * * @memberOf HistoricalScheduler * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ HistoricalSchedulerProto.add = function (absolute, relative) { return absolute + relative; }; /** * @private * @memberOf HistoricalScheduler */ HistoricalSchedulerProto.toDateTimeOffset = function (absolute) { return new Date(absolute).getTime(); }; /** * Converts the TimeSpan value to a relative virtual time value. * * @memberOf HistoricalScheduler * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ HistoricalSchedulerProto.toRelative = function (timeSpan) { return timeSpan; }; return HistoricalScheduler; }(Rx.VirtualTimeScheduler)); var scheduleMethod, clearMethod = noop; (function () { function postMessageSupported () { // Ensure not in a worker if (!window.postMessage || window.importScripts) { return false; } var isAsync = false, oldHandler = window.onmessage; // Test for async window.onmessage = function () { isAsync = true; }; window.postMessage('','*'); window.onmessage = oldHandler; return isAsync; } // Check for setImmediate first for Node v0.11+ if (!!window.setImmediate && typeof window.setImmediate === 'function') { scheduleMethod = window.setImmediate; clearMethod = window.clearImmediate; } else if (typeof window.process === 'object' && Object.prototype.toString.call(window.process) === '[object process]') { scheduleMethod = window.process.nextTick; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), tasks = {}, taskId = 0; function onGlobalPostMessage(event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { var handleId = event.data.substring(MSG_PREFIX.length), action = tasks[handleId]; action(); delete tasks[handleId]; } } if (window.addEventListener) { window.addEventListener('message', onGlobalPostMessage, false); } else { window.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; window.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!window.MessageChannel) { var channel = new window.MessageChannel(), channelTasks = {}, channelTaskId = 0; channel.port1.onmessage = function (event) { var id = event.data, action = channelTasks[id]; action(); delete channelTasks[id]; }; scheduleMethod = function (action) { var id = channelTaskId++; channelTasks[id] = action; channel.port2.postMessage(id); }; } else if ('document' in window && 'onreadystatechange' in window.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = window.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; window.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return window.setTimeout(action, 0); }; clearMethod = window.clearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. * * @memberOf Scheduler */ var timeoutScheduler = Scheduler.timeout = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = window.setTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { window.clearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** @private */ var CatchScheduler = (function (_super) { function localNow() { return this._scheduler.now(); } function scheduleNow(state, action) { return this._scheduler.scheduleWithState(state, this._wrap(action)); } function scheduleRelative(state, dueTime, action) { return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); } function scheduleAbsolute(state, dueTime, action) { return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); } inherits(CatchScheduler, _super); /** @private */ function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } /** @private */ CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; /** @private */ CatchScheduler.prototype._wrap = function (action) { var parent = this; return function (self, state) { try { return action(parent._getRecursiveWrapper(self), state); } catch (e) { if (!parent._handler(e)) { throw e; } return disposableEmpty; } }; }; /** @private */ CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { if (this._recursiveOriginal !== scheduler) { this._recursiveOriginal = scheduler; var wrapper = this._clone(scheduler); wrapper._recursiveOriginal = scheduler; wrapper._recursiveWrapper = wrapper; this._recursiveWrapper = wrapper; } return this._recursiveWrapper; }; /** @private */ CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var self = this, failed = false, d = new SingleAssignmentDisposable(); d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { if (failed) { return null; } try { return action(state1); } catch (e) { failed = true; if (!self._handler(e)) { throw e; } d.dispose(); return null; } })); return d; }; return CatchScheduler; }(Scheduler)); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } var NotificationPrototype = Notification.prototype; /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) { if (arguments.length === 1 && typeof observerOrOnNext === 'object') { return this._acceptObservable(observerOrOnNext); } return this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notification * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ NotificationPrototype.toObservable = function (scheduler) { var notification = this; scheduler = scheduler || immediateScheduler; return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); if (notification.kind === 'N') { observer.onCompleted(); } }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * * @static * @memberOf Notification * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept (onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString () { return 'OnNext(' + this.value + ')'; } return function (value) { var notification = new Notification('N', true); notification.value = value; notification._accept = _accept.bind(notification); notification._acceptObservable = _acceptObservable.bind(notification); notification.toString = toString.bind(notification); return notification; }; }()); /** * Creates an object that represents an OnError notification to an observer. * * @static s * @memberOf Notification * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (exception) { var notification = new Notification('E'); notification.exception = exception; notification._accept = _accept.bind(notification); notification._acceptObservable = _acceptObservable.bind(notification); notification.toString = toString.bind(notification); return notification; }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * * @static * @memberOf Notification * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { var notification = new Notification('C'); notification._accept = _accept.bind(notification); notification._acceptObservable = _acceptObservable.bind(notification); notification.toString = toString.bind(notification); return notification; }; }()); /** * @constructor * @private */ var Enumerator = Rx.Internals.Enumerator = function (moveNext, getCurrent, dispose) { this.moveNext = moveNext; this.getCurrent = getCurrent; this.dispose = dispose; }; /** * @static * @memberOf Enumerator * @private */ var enumeratorCreate = Enumerator.create = function (moveNext, getCurrent, dispose) { var done = false; dispose || (dispose = noop); return new Enumerator(function () { if (done) { return false; } var result = moveNext(); if (!result) { done = true; dispose(); } return result; }, function () { return getCurrent(); }, function () { if (!done) { dispose(); done = true; } }); }; /** @private */ var Enumerable = Rx.Internals.Enumerable = (function () { /** * @constructor * @private */ function Enumerable(getEnumerator) { this.getEnumerator = getEnumerator; } /** * @private * @memberOf Enumerable# */ Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (observer) { var e = sources.getEnumerator(), isDisposed = false, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, ex, hasNext = false; if (!isDisposed) { try { hasNext = e.moveNext(); if (hasNext) { current = e.getCurrent(); } else { e.dispose(); } } catch (exception) { ex = exception; e.dispose(); } } else { return; } if (ex) { observer.onError(ex); return; } if (!hasNext) { observer.onCompleted(); return; } var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { self(); }) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; e.dispose(); })); }); }; /** * @private * @memberOf Enumerable# */ Enumerable.prototype.catchException = function () { var sources = this; return new AnonymousObservable(function (observer) { var e = sources.getEnumerator(), isDisposed = false, lastException; var subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, ex, hasNext; hasNext = false; if (!isDisposed) { try { hasNext = e.moveNext(); if (hasNext) { current = e.getCurrent(); } } catch (exception) { ex = exception; } } else { return; } if (ex) { observer.onError(ex); return; } if (!hasNext) { if (lastException) { observer.onError(lastException); } else { observer.onCompleted(); } return; } var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe( observer.onNext.bind(observer), function (exn) { lastException = exn; self(); }, observer.onCompleted.bind(observer))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; return Enumerable; }()); /** * @static * @private * @memberOf Enumerable */ var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount === undefined) { repeatCount = -1; } return new Enumerable(function () { var current, left = repeatCount; return enumeratorCreate(function () { if (left === 0) { return false; } if (left > 0) { left--; } current = value; return true; }, function () { return current; }); }); }; /** * @static * @private * @memberOf Enumerable */ var enumerableFor = Enumerable.forEach = function (source, selector) { selector || (selector = identity); return new Enumerable(function () { var current, index = -1; return enumeratorCreate( function () { if (++index < source.length) { current = selector(source[index], index); return true; } return false; }, function () { return current; } ); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * * @param observer Observer object. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. * If a violation is detected, an Error is thrown from the offending observer method call. * * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. */ Observer.prototype.checked = function () { return new CheckedObserver(this); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * * @static * @memberOf Observer * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler) { return new AnonymousObserver(function (x) { return handler(notificationCreateOnNext(x)); }, function (exception) { return handler(notificationCreateOnError(exception)); }, function () { return handler(notificationCreateOnCompleted()); }); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.Internals.AbstractObserver = (function (_super) { inherits(AbstractObserver, _super); /** * Creates a new observer in a non-stopped state. * * @constructor */ function AbstractObserver() { this.isStopped = false; _super.call(this); } /** * Notifies the observer of a new element in the sequence. * * @memberOf AbstractObserver * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * * @memberOf AbstractObserver * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function () { if (!this.isStopped) { this.isStopped = true; this.error(true); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { inherits(AnonymousObserver, _super); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * * @constructor * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { _super.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * * @memberOf AnonymousObserver * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * * @memberOf AnonymousObserver * @param {Any{ error The error that has occurred. */ AnonymousObserver.prototype.error = function (exception) { this._onError(exception); }; /** * Calls the onCompleted action. * * @memberOf AnonymousObserver */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var CheckedObserver = (function (_super) { inherits(CheckedObserver, _super); function CheckedObserver(observer) { _super.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); try { this._observer.onNext(value); } catch (e) { throw e; } finally { this._state = 0; } }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); try { this._observer.onError(err); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); try { this._observer.onCompleted(); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); /** @private */ var ScheduledObserver = Rx.Internals.ScheduledObserver = (function (_super) { inherits(ScheduledObserver, _super); function ScheduledObserver(scheduler, observer) { _super.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } /** @private */ ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; /** @private */ ScheduledObserver.prototype.error = function (exception) { var self = this; this.queue.push(function () { self.observer.onError(exception); }); }; /** @private */ ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; /** @private */ ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; /** @private */ ScheduledObserver.prototype.dispose = function () { _super.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); /** @private */ var ObserveOnObserver = (function (_super) { inherits(ObserveOnObserver, _super); /** @private */ function ObserveOnObserver() { _super.apply(this, arguments); } /** @private */ ObserveOnObserver.prototype.next = function (value) { _super.prototype.next.call(this, value); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.error = function (e) { _super.prototype.error.call(this, e); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.completed = function () { _super.prototype.completed.call(this); this.ensureActive(); }; return ObserveOnObserver; })(ScheduledObserver); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { /** * @constructor * @private */ function Observable(subscribe) { this._subscribe = subscribe; } observableProto = Observable.prototype; observableProto.finalValue = function () { var source = this; return new AnonymousObservable(function (observer) { var hasValue = false, value; return source.subscribe(function (x) { hasValue = true; value = x; }, observer.onError.bind(observer), function () { if (!hasValue) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); }; /** * Subscribes an observer to the observable sequence. * * @example * 1 - source.subscribe(); * 2 - source.subscribe(observer); * 3 - source.subscribe(function (x) { console.log(x); }); * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { var subscriber; if (typeof observerOrOnNext === 'object') { subscriber = observerOrOnNext; } else { subscriber = observerCreate(observerOrOnNext, onError, onCompleted); } return this._subscribe(subscriber); }; /** * Creates a list from an observable sequence. * * @memberOf Observable * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { function accumulator(list, i) { var newList = list.slice(0); newList.push(i); return newList; } return this.scan([], accumulator).startWith([]).finalValue(); }; return Observable; })(); /** * Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence. * * @example * 1 - res = Rx.Observable.start(function () { console.log('hello'); }); * 2 - res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout); * 2 - res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console); * * @param {Function} func Function to run asynchronously. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. * * Remarks * * The function is called immediately, not during the subscription of the resulting sequence. * * Multiple subscriptions to the resulting sequence can observe the function's result. */ Observable.start = function (func, scheduler, context) { return observableToAsync(func, scheduler)(); }; /** * Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler. * * @example * 1 - res = Rx.Observable.toAsync(function (x, y) { return x + y; })(4, 3); * 2 - res = Rx.Observable.toAsync(function (x, y) { return x + y; }, Rx.Scheduler.timeout)(4, 3); * 2 - res = Rx.Observable.toAsync(function (x) { this.log(x); }, Rx.Scheduler.timeout, console)('hello'); * * @param function Function to convert to an asynchronous function. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Function} Asynchronous function. */ var observableToAsync = Observable.toAsync = function (func, scheduler, context) { scheduler || (scheduler = timeoutScheduler); return function () { var args = slice.call(arguments, 0), subject = new AsyncSubject(); scheduler.schedule(function () { var result; try { result = func.apply(context, args); } catch (e) { subject.onError(e); return; } subject.onNext(result); subject.onCompleted(); }); return subject.asObservable(); }; }; /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }); }; /** * Creates an observable sequence from a specified subscribe method implementation. * * @example * 1 - res = Rx.Observable.create(function (observer) { return function () { } ); * * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = function (subscribe) { return new AnonymousObservable(function (o) { return disposableCreate(subscribe(o)); }); }; /** * Creates an observable sequence from a specified subscribe method implementation. * * @example * 1 - res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * @static * @memberOf Observable * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.createWithDisposable = function (subscribe) { return new AnonymousObservable(subscribe); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * 1 - res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @static * @memberOf Observable * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * 1 - res = Rx.Observable.empty(); * 2 - res = Rx.Observable.empty(Rx.Scheduler.timeout); * @static * @memberOf Observable * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * * @example * 1 - res = Rx.Observable.fromArray([1,2,3]); * 2 - res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); * @static * @memberOf Observable * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0; return scheduler.scheduleRecursive(function (self) { if (count < array.length) { observer.onNext(array[count++]); self(); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * 1 - res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * 2 - res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @static * @memberOf Observable * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); self(); } else { observer.onCompleted(); } }); }); }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * * @static * @memberOf Observable * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * * @example * 1 - res = Rx.Observable.range(0, 10); * 2 - res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); * @static * @memberOf Observable * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleRecursiveWithState(0, function (i, self) { if (i < count) { observer.onNext(start + i); self(i + 1); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * 1 - res = Rx.Observable.repeat(42); * 2 - res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @static * @memberOf Observable * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { scheduler || (scheduler = currentThreadScheduler); if (repeatCount == null) { repeatCount = -1; } return observableReturn(value, scheduler).repeat(repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'returnValue' for browsers <IE9. * * @example * 1 - res = Rx.Observable.return(42); * 2 - res = Rx.Observable.return(42, Rx.Scheduler.timeout); * @static * @memberOf Observable * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.returnValue = function (value, scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwException' for browsers <IE9. * * @example * 1 - res = Rx.Observable.throwException(new Error('Error')); * 2 - res = Rx.Observable.throwException(new Error('Error'), Rx.Scheduler.timeout); * @static * @memberOf Observable * @param {Mixed} exception An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwException = function (exception, scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * * @example * 1 - res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; }); * @static * @memberOf Observable * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); if (resource) { disposable = resource; } source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence that reacts first. * * @memberOf Observable# * @param {Observable} rightSource Second observable sequence. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence that reacts first. * * @example * E.g. winner = Rx.Observable.amb(xs, ys, zs); * @static * @memberOf Observable * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = argsOrArray(arguments, 0); function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (observer) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) { var d, result; try { result = handler(exception); } catch (ex) { observer.onError(ex); return; } d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(observer)); }, observer.onCompleted.bind(observer))); return subscription; }); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @memberOf Observable# * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto.catchException = function (handlerOrSecond) { if (typeof handlerOrSecond === 'function') { return observableCatchHandler(this, handlerOrSecond); } return observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.catchException(xs, ys, zs); * 2 - res = Rx.Observable.catchException([xs, ys, zs]); * @static * @memberOf Observable * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchException = function () { var items = argsOrArray(arguments, 0); return enumerableFor(items).catchException(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @memberOf Observable# * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var args = slice.call(arguments); if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @static * @memberOf Observable * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var args = slice.call(arguments), resultSelector = args.pop(); if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(function (x) { return x; }))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(function (x) { return x; })) { observer.onCompleted(); } } function done (i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(args[i].subscribe(function (x) { values[i] = x; next(i); }, observer.onError.bind(observer), function () { done(i); })); }(idx)); } return new CompositeDisposable(subscriptions); }); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * * @example * 1 - concatenated = xs.concat(ys, zs); * 2 - concatenated = xs.concat([ys, zs]); * @memberOf Observable# * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { var items = slice.call(arguments, 0); items.unshift(this); return observableConcat.apply(this, items); }; /** * Concatenates all the observable sequences. * * @example * 1 - res = Rx.Observable.concat(xs, ys, zs); * 2 - res = Rx.Observable.concat([xs, ys, zs]); * @static * @memberOf Observable * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var sources = argsOrArray(arguments, 0); return enumerableFor(sources).concat(); }; /** * Concatenates an observable sequence of observable sequences. * * @memberOf Observable# * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatObservable = observableProto.concatAll =function () { return this.merge(1); }; /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @memberOf Observable# * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); } var sources = this; return new AnonymousObservable(function (observer) { var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = [], subscribe = function (xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { var s; group.remove(subscription); if (q.length > 0) { s = q.shift(); subscribe(s); } else { activeCount--; if (isStopped && activeCount === 0) { observer.onCompleted(); } } })); }; group.add(sources.subscribe(function (innerSource) { if (activeCount < maxConcurrentOrOther) { activeCount++; subscribe(innerSource); } else { q.push(innerSource); } }, observer.onError.bind(observer), function () { isStopped = true; if (activeCount === 0) { observer.onCompleted(); } })); return group; }); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * * @example * 1 - merged = Rx.Observable.merge(xs, ys, zs); * 2 - merged = Rx.Observable.merge([xs, ys, zs]); * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); * * @static * @memberOf Observable * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources; if (!arguments[0]) { scheduler = immediateScheduler; sources = slice.call(arguments, 1); } else if (arguments[0].now) { scheduler = arguments[0]; sources = slice.call(arguments, 1); } else { scheduler = immediateScheduler; sources = slice.call(arguments, 0); } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableFromArray(sources, scheduler).mergeObservable(); }; /** * Merges an observable sequence of observable sequences into an observable sequence. * * @memberOf Observable# * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeObservable = observableProto.mergeAll =function () { var sources = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(), isStopped = false, m = new SingleAssignmentDisposable(); group.add(m); m.setDisposable(sources.subscribe(function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); innerSubscription.setDisposable(innerSource.subscribe(function (x) { observer.onNext(x); }, observer.onError.bind(observer), function () { group.remove(innerSubscription); if (isStopped && group.length === 1) { observer.onCompleted(); } })); }, observer.onError.bind(observer), function () { isStopped = true; if (group.length === 1) { observer.onCompleted(); } })); return group; }); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @memberOf Observable * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @static * @memberOf Observable * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () { self(); }, function () { self(); })); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * * @memberOf Observable# * @param {Observable} other The observable sequence that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { if (isOpen) { observer.onNext(left); } }, observer.onError.bind(observer), function () { if (isOpen) { observer.onCompleted(); } })); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, observer.onError.bind(observer), function () { rightSubscription.dispose(); })); return disposables; }); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * * @memberOf Observable# * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe(function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); d.setDisposable(innerSource.subscribe(function (x) { if (latest === id) { observer.onNext(x); } }, function (e) { if (latest === id) { observer.onError(e); } }, function () { if (latest === id) { hasLatest = false; if (isStopped) { observer.onCompleted(); } } })); }, observer.onError.bind(observer), function () { isStopped = true; if (!hasLatest) { observer.onCompleted(); } }); return new CompositeDisposable(subscription, innerSubscription); }); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * * @memberOf Observable# * @param {Observable} other Observable sequence that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { return new CompositeDisposable( source.subscribe(observer), other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) ); }); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { observer.onError(e); return; } observer.onNext(result); } else { observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @memberOf Observable# * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); sources.unshift(parent); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); var next = function (i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * * @static * @memberOf Observable * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var args = slice.call(arguments, 0), first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * * @static * @memberOf Observable * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources = slice.call(arguments); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); })(idx); } var compositeDisposable = new CompositeDisposable(subscriptions); compositeDisposable.add(disposableCreate(function () { for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { queues[qIdx] = []; } })); return compositeDisposable; }); }; /** * Hides the identity of an observable sequence. * * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(observer); }); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * 1 - xs.bufferWithCount(10); * 2 - xs.bufferWithCount(10, 1); * * @memberOf Observable# * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (skip === undefined) { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * * @memberOf Observable# * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { return x.accept(observer); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * 1 - var obs = observable.distinctUntilChanged(); * 2 - var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * 3 - var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @memberOf Observable# * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; keySelector || (keySelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var comparerEquals = false, key; try { key = keySelector(value); } catch (exception) { observer.onError(exception); return; } if (hasCurrentKey) { try { comparerEquals = comparer(currentKey, key); } catch (exception) { observer.onError(exception); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * * @example * 1 - observable.doAction(observer); * 2 - observable.doAction(onNext); * 3 - observable.doAction(onNext, onError); * 4 - observable.doAction(onNext, onError, onCompleted); * * @memberOf Observable# * @param {Mixed} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { var source = this, onNextFunc; if (typeof observerOrOnNext === 'function') { onNextFunc = observerOrOnNext; } else { onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); onError = observerOrOnNext.onError.bind(observerOrOnNext); onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); } return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { onNextFunc(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (exception) { if (!onError) { observer.onError(exception); } else { try { onError(exception); } catch (e) { observer.onError(e); } observer.onError(exception); } }, function () { if (!onCompleted) { observer.onCompleted(); } else { try { onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); } }); }); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * * @example * 1 - obs = observable.finallyAction(function () { console.log('sequence ended'; }); * * @memberOf Observable# * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto.finallyAction = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription = source.subscribe(observer); return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * * @memberOf Observable# * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * * @memberOf Observable# * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (exception) { observer.onNext(notificationCreateOnError(exception)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * * @example * 1 - repeated = source.repeat(); * 2 - repeated = source.repeat(42); * * @memberOf Observable# * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * * @example * 1 - retried = retry.repeat(); * 2 - retried = retry.repeat(42); * * @memberOf Observable# * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchException(); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * * 1 - scanned = source.scan(function (acc, x) { return acc + x; }); * 2 - scanned = source.scan(0, function (acc, x) { return acc + x; }); * * @memberOf Observable# * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var seed, hasSeed = false, accumulator; if (arguments.length === 2) { seed = arguments[0]; accumulator = arguments[1]; hasSeed = true; } else { accumulator = arguments[0]; } var source = this; return observableDefer(function () { var hasAccumulation = false, accumulation; return source.select(function (x) { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } return accumulation; }); }); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * * @memberOf Observable# * @description * This operator accumulates a queue with a length enough to store the first <paramref name="count"/> elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); if (q.length > count) { observer.onNext(q.shift()); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * * 1 - source.startWith(1, 2, 3); * 2 - source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * * @memberOf Observable# * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && 'now' in Object(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableFor([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue. * * @example * 1 - obs = source.takeLast(5); * 2 - obs = source.takeLast(5, Rx.Scheduler.timeout); * * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * * @memberOf Observable# * @param {Number} count Number of elements to take from the end of the source sequence. * @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count, scheduler) { return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); }); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * * @memberOf Observable# * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); if (q.length > count) { q.shift(); } }, observer.onError.bind(observer), function () { observer.onNext(q); observer.onCompleted(); }); }); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * 1 - xs.windowWithCount(10); * 2 - xs.windowWithCount(10, 1); * * @memberOf Observable# * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; if (count <= 0) { throw new Error(argumentOutOfRange); } if (skip == null) { skip = count; } if (skip <= 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = [], createWindow = function () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); }; createWindow(); m.setDisposable(source.subscribe(function (x) { var s; for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; if (c >= 0 && c % skip === 0) { s = q.shift(); s.onCompleted(); } n++; if (n % skip === 0) { createWindow(); } }, function (exception) { while (q.length > 0) { q.shift().onError(exception); } observer.onError(exception); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * 1 - obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; if (defaultValue === undefined) { defaultValue = null; } return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, observer.onError.bind(observer), function () { if (!found) { observer.onNext(defaultValue); } observer.onCompleted(); }); }); }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * 1 - obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (x) { return x.toString(); }); * * @memberOf Observable# * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, keySerializer) { var source = this; keySelector || (keySelector = identity); keySerializer || (keySerializer = defaultKeySerializer); return new AnonymousObservable(function (observer) { var hashSet = {}; return source.subscribe(function (x) { var key, serializedKey, otherKey, hasMatch = false; try { key = keySelector(x); serializedKey = keySerializer(key); } catch (exception) { observer.onError(exception); return; } for (otherKey in hashSet) { if (serializedKey === otherKey) { hasMatch = true; break; } } if (!hasMatch) { hashSet[serializedKey] = null; observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. * * @example * 1 - observable.groupBy(function (x) { return x.id; }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); * * @memberOf Observable# * @param {Function} keySelector A function to extract the key for each element. * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. */ observableProto.groupBy = function (keySelector, elementSelector, keySerializer) { return this.groupByUntil(keySelector, elementSelector, function () { return observableNever(); }, keySerializer); }; /** * Groups the elements of an observable sequence according to a specified key selector function. * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. * * @example * 1 - observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); * * @memberOf Observable# * @param {Function} keySelector A function to extract the key for each element. * @param {Function} durationSelector A function to signal the expiration of a group. * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. * @returns {Observable} * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. * */ observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, keySerializer) { var source = this; elementSelector || (elementSelector = identity); keySerializer || (keySerializer = defaultKeySerializer); return new AnonymousObservable(function (observer) { var map = {}, groupDisposable = new CompositeDisposable(), refCountDisposable = new RefCountDisposable(groupDisposable); groupDisposable.add(source.subscribe(function (x) { var duration, durationGroup, element, fireNewMapEntry, group, key, serializedKey, md, writer, w; try { key = keySelector(x); serializedKey = keySerializer(key); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } fireNewMapEntry = false; try { writer = map[serializedKey]; if (!writer) { writer = new Subject(); map[serializedKey] = writer; fireNewMapEntry = true; } } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } if (fireNewMapEntry) { group = new GroupedObservable(key, writer, refCountDisposable); durationGroup = new GroupedObservable(key, writer); try { duration = durationSelector(durationGroup); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } observer.onNext(group); md = new SingleAssignmentDisposable(); groupDisposable.add(md); var expire = function () { if (serializedKey in map) { delete map[serializedKey]; writer.onCompleted(); } groupDisposable.remove(md); }; md.setDisposable(duration.take(1).subscribe(noop, function (exn) { for (w in map) { map[w].onError(exn); } observer.onError(exn); }, function () { expire(); })); } try { element = elementSelector(x); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } writer.onNext(element); }, function (ex) { for (var w in map) { map[w].onError(ex); } observer.onError(ex); }, function () { for (var w in map) { map[w].onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * * @example * source.select(function (value, index) { return value * value + index; }); * * @memberOf Observable# * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.select = function (selector, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var result; try { result = selector.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } observer.onNext(result); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; observableProto.map = observableProto.select; function selectMany(selector) { return this.select(selector).mergeObservable(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * 1 - source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * 1 - source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * 1 - source.selectMany(Rx.Observable.fromArray([1,2,3])); * * @memberOf Observable# * @param selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector) { if (resultSelector) { return this.selectMany(function (x) { return selector(x).select(function (y) { return resultSelector(x, y); }); }); } if (typeof selector === 'function') { return selectMany.call(this, selector); } return selectMany.call(this, function () { return selector; }); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * * @memberOf Observable# * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new Error(argumentOutOfRange); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining <= 0) { observer.onNext(x); } else { remaining--; } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * 1 - source.skipWhile(function (value) { return value < 10; }); * 1 - source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * * @memberOf Observable# * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate) { var source = this; return new AnonymousObservable(function (observer) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !predicate(x, i++); } catch (e) { observer.onError(e); return; } } if (running) { observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * 1 - source.take(5); * 2 - source.take(0, Rx.Scheduler.timeout); * * @memberOf Observable# * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new Error(argumentOutOfRange); } if (count === 0) { return observableEmpty(scheduler); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining > 0) { remaining--; observer.onNext(x); if (remaining === 0) { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * * @example * 1 - source.takeWhile(function (value) { return value < 10; }); * 1 - source.takeWhile(function (value, index) { return value < 10 || index < 10; }); * * @memberOf Observable# * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate) { var observable = this; return new AnonymousObservable(function (observer) { var i = 0, running = true; return observable.subscribe(function (x) { if (running) { try { running = predicate(x, i++); } catch (e) { observer.onError(e); return; } if (running) { observer.onNext(x); } else { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * * @example * 1 - source.where(function (value) { return value < 10; }); * 1 - source.where(function (value, index) { return value < 10 || index < 10; }); * * @memberOf Observable# * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.where = function (predicate, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var shouldRun; try { shouldRun = predicate.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } if (shouldRun) { observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; observableProto.filter = observableProto.where; /** @private */ var AnonymousObservable = Rx.Internals.AnonymousObservable = (function (_super) { inherits(AnonymousObservable, _super); /** * @private * @constructor */ function AnonymousObservable(subscribe) { if (!(this instanceof AnonymousObservable)) { return new AnonymousObservable(subscribe); } function s(observer) { var autoDetachObserver = new AutoDetachObserver(observer); if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(function () { try { autoDetachObserver.disposable(subscribe(autoDetachObserver)); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } }); } else { try { autoDetachObserver.disposable(subscribe(autoDetachObserver)); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } } return autoDetachObserver; } _super.call(this, s); } return AnonymousObservable; }(Observable)); /** @private */ var AutoDetachObserver = (function (_super) { inherits(AutoDetachObserver, _super); /** * @private * @constructor */ function AutoDetachObserver(observer) { _super.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; /** * @private * @memberOf AutoDetachObserver# */ AutoDetachObserverPrototype.next = function (value) { var noError = false; try { this.observer.onNext(value); noError = true; } catch (e) { throw e; } finally { if (!noError) { this.dispose(); } } }; /** * @private * @memberOf AutoDetachObserver# */ AutoDetachObserverPrototype.error = function (exn) { try { this.observer.onError(exn); } catch (e) { throw e; } finally { this.dispose(); } }; /** * @private * @memberOf AutoDetachObserver# */ AutoDetachObserverPrototype.completed = function () { try { this.observer.onCompleted(); } catch (e) { throw e; } finally { this.dispose(); } }; /** * @private * @memberOf AutoDetachObserver# */ AutoDetachObserverPrototype.disposable = function (value) { return this.m.disposable(value); }; /** * @private * @memberOf AutoDetachObserver# */ AutoDetachObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); /** @private */ var GroupedObservable = (function (_super) { inherits(GroupedObservable, _super); function subscribe(observer) { return this.underlyingObservable.subscribe(observer); } /** * @constructor * @private */ function GroupedObservable(key, underlyingObservable, mergedDisposable) { _super.call(this, subscribe); this.key = key; this.underlyingObservable = !mergedDisposable ? underlyingObservable : new AnonymousObservable(function (observer) { return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); }); } return GroupedObservable; }(Observable)); /** @private */ var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; /** * @private * @memberOf InnerSubscription */ InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.exception) { observer.onError(this.exception); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, _super); /** * Creates a subject. * * @constructor */ function Subject() { _super.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; } addProperties(Subject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * * @memberOf ReplaySubject# * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. * * @memberOf ReplaySubject# */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * * @memberOf ReplaySubject# * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * * @memberOf ReplaySubject# * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. * * @memberOf ReplaySubject# */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * * @static * @memberOf Subject * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } var ex = this.exception; var hv = this.hasValue; var v = this.value; if (ex) { observer.onError(ex); } else if (hv) { observer.onNext(v); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, _super); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * * @constructor */ function AsyncSubject() { _super.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.value = null, this.hasValue = false, this.observers = [], this.exception = null; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * * @memberOf AsyncSubject# * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). * * @memberOf AsyncSubject# */ onCompleted: function () { var o, i, len; checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; var v = this.value; var hv = this.hasValue; if (hv) { for (i = 0, len = os.length; i < len; i++) { o = os[i]; o.onNext(v); o.onCompleted(); } } else { for (i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * * @memberOf AsyncSubject# * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * * @memberOf AsyncSubject# * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { this.value = value; this.hasValue = true; } }, /** * Unsubscribe all observers and release resources. * * @memberOf AsyncSubject# */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); /** @private */ var AnonymousSubject = (function (_super) { inherits(AnonymousSubject, _super); function subscribe(observer) { return this.observable.subscribe(observer); } /** * @private * @constructor */ function AnonymousSubject(observer, observable) { _super.call(this, subscribe); this.observer = observer; this.observable = observable; } addProperties(AnonymousSubject.prototype, Observer, { /** * @private * @memberOf AnonymousSubject# */ onCompleted: function () { this.observer.onCompleted(); }, /** * @private * @memberOf AnonymousSubject# */ onError: function (exception) { this.observer.onError(exception); }, /** * @private * @memberOf AnonymousSubject# */ onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); // Check for AMD if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { window.Rx = Rx; return define(function () { return Rx; }); } else if (freeExports) { if (typeof module == 'object' && module && module.exports == freeExports) { module.exports = Rx; } else { freeExports = Rx; } } else { window.Rx = Rx; } }(this));
examples/todomvc/test/components/TodoTextInput.spec.js
camsong/redux
import expect from 'expect' import React from 'react' import TestUtils from 'react-addons-test-utils' import TodoTextInput from '../../components/TodoTextInput' function setup(propOverrides) { const props = Object.assign({ onSave: expect.createSpy(), text: 'Use Redux', placeholder: 'What needs to be done?', editing: false, newTodo: false }, propOverrides) const renderer = TestUtils.createRenderer() renderer.render( <TodoTextInput {...props} /> ) let output = renderer.getRenderOutput() output = renderer.getRenderOutput() return { props: props, output: output, renderer: renderer } } describe('components', () => { describe('TodoTextInput', () => { it('should render correctly', () => { const { output } = setup() expect(output.props.placeholder).toEqual('What needs to be done?') expect(output.props.value).toEqual('Use Redux') expect(output.props.className).toEqual('') }) it('should render correctly when editing=true', () => { const { output } = setup({ editing: true }) expect(output.props.className).toEqual('edit') }) it('should render correctly when newTodo=true', () => { const { output } = setup({ newTodo: true }) expect(output.props.className).toEqual('new-todo') }) it('should update value on change', () => { const { output, renderer } = setup() output.props.onChange({ target: { value: 'Use Radox' } }) const updated = renderer.getRenderOutput() expect(updated.props.value).toEqual('Use Radox') }) it('should call onSave on return key press', () => { const { output, props } = setup() output.props.onKeyDown({ which: 13, target: { value: 'Use Redux' } }) expect(props.onSave).toHaveBeenCalledWith('Use Redux') }) it('should reset state on return key press if newTodo', () => { const { output, renderer } = setup({ newTodo: true }) output.props.onKeyDown({ which: 13, target: { value: 'Use Redux' } }) const updated = renderer.getRenderOutput() expect(updated.props.value).toEqual('') }) it('should call onSave on blur', () => { const { output, props } = setup() output.props.onBlur({ target: { value: 'Use Redux' } }) expect(props.onSave).toHaveBeenCalledWith('Use Redux') }) it('shouldnt call onSave on blur if newTodo', () => { const { output, props } = setup({ newTodo: true }) output.props.onBlur({ target: { value: 'Use Redux' } }) expect(props.onSave.calls.length).toBe(0) }) }) })
programar/node_modules/rx/dist/rx.lite.js
ottohernandezgarzon/tanks-colored-of-war
// Copyright (c) Microsoft, All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'function': true, 'object': true }; function checkGlobal(value) { return (value && value.Object === Object) ? value : null; } var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType) ? exports : null; var freeModule = (objectTypes[typeof module] && module && !module.nodeType) ? module : null; var freeGlobal = checkGlobal(freeExports && freeModule && typeof global === 'object' && global); var freeSelf = checkGlobal(objectTypes[typeof self] && self); var freeWindow = checkGlobal(objectTypes[typeof window] && window); var moduleExports = (freeModule && freeModule.exports === freeExports) ? freeExports : null; var thisGlobal = checkGlobal(objectTypes[typeof this] && this); var root = freeGlobal || ((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) || freeSelf || thisGlobal || Function('return this')(); var Rx = { internals: {}, config: { Promise: root.Promise }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, identity = Rx.helpers.identity = function (x) { return x; }, defaultNow = Rx.helpers.defaultNow = Date.now, defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, defaultError = Rx.helpers.defaultError = function (err) { throw err; }, isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.subscribe !== 'function' && typeof p.then === 'function'; }, isFunction = Rx.helpers.isFunction = (function () { var isFn = function (value) { return typeof value == 'function' || false; }; // fallback for older versions of Chrome and Safari if (isFn(/x/)) { isFn = function(value) { return typeof value == 'function' && toString.call(value) == '[object Function]'; }; } return isFn; }()); function cloneArray(arr) { var len = arr.length, a = new Array(len); for(var i = 0; i < len; i++) { a[i] = arr[i]; } return a; } var errorObj = {e: {}}; function tryCatcherGen(tryCatchTarget) { return function tryCatcher() { try { return tryCatchTarget.apply(this, arguments); } catch (e) { errorObj.e = e; return errorObj; } }; } var tryCatch = Rx.internals.tryCatch = function tryCatch(fn) { if (!isFunction(fn)) { throw new TypeError('fn must be a function'); } return tryCatcherGen(fn); }; function thrower(e) { throw e; } Rx.config.longStackSupport = false; var hasStacks = false, stacks = tryCatch(function () { throw new Error(); })(); hasStacks = !!stacks.e && !!stacks.e.stack; // All code after this point will be filtered from stack traces reported by RxJS var rStartingLine = captureLine(), rFileName; var STACK_JUMP_SEPARATOR = 'From previous event:'; function makeStackTraceLong(error, observable) { // If possible, transform the error stack trace by removing Node and RxJS // cruft, then concatenating with the stack trace of `observable`. if (hasStacks && observable.stack && typeof error === 'object' && error !== null && error.stack && error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1 ) { var stacks = []; for (var o = observable; !!o; o = o.source) { if (o.stack) { stacks.unshift(o.stack); } } stacks.unshift(error.stack); var concatedStacks = stacks.join('\n' + STACK_JUMP_SEPARATOR + '\n'); error.stack = filterStackString(concatedStacks); } } function filterStackString(stackString) { var lines = stackString.split('\n'), desiredLines = []; for (var i = 0, len = lines.length; i < len; i++) { var line = lines[i]; if (!isInternalFrame(line) && !isNodeFrame(line) && line) { desiredLines.push(line); } } return desiredLines.join('\n'); } function isInternalFrame(stackLine) { var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine); if (!fileNameAndLineNumber) { return false; } var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1]; return fileName === rFileName && lineNumber >= rStartingLine && lineNumber <= rEndingLine; } function isNodeFrame(stackLine) { return stackLine.indexOf('(module.js:') !== -1 || stackLine.indexOf('(node.js:') !== -1; } function captureLine() { if (!hasStacks) { return; } try { throw new Error(); } catch (e) { var lines = e.stack.split('\n'); var firstLine = lines[0].indexOf('@') > 0 ? lines[1] : lines[2]; var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine); if (!fileNameAndLineNumber) { return; } rFileName = fileNameAndLineNumber[0]; return fileNameAndLineNumber[1]; } } function getFileNameAndLineNumber(stackLine) { // Named functions: 'at functionName (filename:lineNumber:columnNumber)' var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine); if (attempt1) { return [attempt1[1], Number(attempt1[2])]; } // Anonymous functions: 'at filename:lineNumber:columnNumber' var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine); if (attempt2) { return [attempt2[1], Number(attempt2[2])]; } // Firefox style: 'function@filename:lineNumber or @filename:lineNumber' var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine); if (attempt3) { return [attempt3[1], Number(attempt3[2])]; } } var EmptyError = Rx.EmptyError = function() { this.message = 'Sequence contains no elements.'; Error.call(this); }; EmptyError.prototype = Object.create(Error.prototype); EmptyError.prototype.name = 'EmptyError'; var ObjectDisposedError = Rx.ObjectDisposedError = function() { this.message = 'Object has been disposed'; Error.call(this); }; ObjectDisposedError.prototype = Object.create(Error.prototype); ObjectDisposedError.prototype.name = 'ObjectDisposedError'; var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () { this.message = 'Argument out of range'; Error.call(this); }; ArgumentOutOfRangeError.prototype = Object.create(Error.prototype); ArgumentOutOfRangeError.prototype.name = 'ArgumentOutOfRangeError'; var NotSupportedError = Rx.NotSupportedError = function (message) { this.message = message || 'This operation is not supported'; Error.call(this); }; NotSupportedError.prototype = Object.create(Error.prototype); NotSupportedError.prototype.name = 'NotSupportedError'; var NotImplementedError = Rx.NotImplementedError = function (message) { this.message = message || 'This operation is not implemented'; Error.call(this); }; NotImplementedError.prototype = Object.create(Error.prototype); NotImplementedError.prototype.name = 'NotImplementedError'; var notImplemented = Rx.helpers.notImplemented = function () { throw new NotImplementedError(); }; var notSupported = Rx.helpers.notSupported = function () { throw new NotSupportedError(); }; // Shim in iterator support var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; // Bug for mozilla version if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined }; var isIterable = Rx.helpers.isIterable = function (o) { return o && o[$iterator$] !== undefined; }; var isArrayLike = Rx.helpers.isArrayLike = function (o) { return o && o.length !== undefined; }; Rx.helpers.iterator = $iterator$; var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) { if (typeof thisArg === 'undefined') { return func; } switch(argCount) { case 0: return function() { return func.call(thisArg) }; case 1: return function(arg) { return func.call(thisArg, arg); }; case 2: return function(value, index) { return func.call(thisArg, value, index); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; } return function() { return func.apply(thisArg, arguments); }; }; /** Used to determine if values are of the language type Object */ var dontEnums = ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor'], dontEnumsLength = dontEnums.length; var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; var objectProto = Object.prototype, hasOwnProperty = objectProto.hasOwnProperty, objToString = objectProto.toString, MAX_SAFE_INTEGER = Math.pow(2, 53) - 1; var keys = Object.keys || (function() { var hasOwnProperty = Object.prototype.hasOwnProperty, hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'), dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ], dontEnumsLength = dontEnums.length; return function(obj) { if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) { throw new TypeError('Object.keys called on non-object'); } var result = [], prop, i; for (prop in obj) { if (hasOwnProperty.call(obj, prop)) { result.push(prop); } } if (hasDontEnumBug) { for (i = 0; i < dontEnumsLength; i++) { if (hasOwnProperty.call(obj, dontEnums[i])) { result.push(dontEnums[i]); } } } return result; }; }()); function equalObjects(object, other, equalFunc, isLoose, stackA, stackB) { var objProps = keys(object), objLength = objProps.length, othProps = keys(other), othLength = othProps.length; if (objLength !== othLength && !isLoose) { return false; } var index = objLength, key; while (index--) { key = objProps[index]; if (!(isLoose ? key in other : hasOwnProperty.call(other, key))) { return false; } } var skipCtor = isLoose; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key], result; if (!(result === undefined ? equalFunc(objValue, othValue, isLoose, stackA, stackB) : result)) { return false; } skipCtor || (skipCtor = key === 'constructor'); } if (!skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; if (objCtor !== othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor === 'function' && objCtor instanceof objCtor && typeof othCtor === 'function' && othCtor instanceof othCtor)) { return false; } } return true; } function equalByTag(object, other, tag) { switch (tag) { case boolTag: case dateTag: return +object === +other; case errorTag: return object.name === other.name && object.message === other.message; case numberTag: return (object !== +object) ? other !== +other : object === +other; case regexpTag: case stringTag: return object === (other + ''); } return false; } var isObject = Rx.internals.isObject = function(value) { var type = typeof value; return !!value && (type === 'object' || type === 'function'); }; function isObjectLike(value) { return !!value && typeof value === 'object'; } function isLength(value) { return typeof value === 'number' && value > -1 && value % 1 === 0 && value <= MAX_SAFE_INTEGER; } var isHostObject = (function() { try { Object({ 'toString': 0 } + ''); } catch(e) { return function() { return false; }; } return function(value) { return typeof value.toString !== 'function' && typeof (value + '') === 'string'; }; }()); function isTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)]; } var isArray = Array.isArray || function(value) { return isObjectLike(value) && isLength(value.length) && objToString.call(value) === arrayTag; }; function arraySome (array, predicate) { var index = -1, length = array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } function equalArrays(array, other, equalFunc, isLoose, stackA, stackB) { var index = -1, arrLength = array.length, othLength = other.length; if (arrLength !== othLength && !(isLoose && othLength > arrLength)) { return false; } // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index], result; if (result !== undefined) { if (result) { continue; } return false; } // Recursively compare arrays (susceptible to call stack limits). if (isLoose) { if (!arraySome(other, function(othValue) { return arrValue === othValue || equalFunc(arrValue, othValue, isLoose, stackA, stackB); })) { return false; } } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, isLoose, stackA, stackB))) { return false; } } return true; } function baseIsEqualDeep(object, other, equalFunc, isLoose, stackA, stackB) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = arrayTag, othTag = arrayTag; if (!objIsArr) { objTag = objToString.call(object); if (objTag === argsTag) { objTag = objectTag; } else if (objTag !== objectTag) { objIsArr = isTypedArray(object); } } if (!othIsArr) { othTag = objToString.call(other); if (othTag === argsTag) { othTag = objectTag; } } var objIsObj = objTag === objectTag && !isHostObject(object), othIsObj = othTag === objectTag && !isHostObject(other), isSameTag = objTag === othTag; if (isSameTag && !(objIsArr || objIsObj)) { return equalByTag(object, other, objTag); } if (!isLoose) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, isLoose, stackA, stackB); } } if (!isSameTag) { return false; } // Assume cyclic values are equal. // For more information on detecting circular references see https://es5.github.io/#JO. stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] === object) { return stackB[length] === other; } } // Add `object` and `other` to the stack of traversed objects. stackA.push(object); stackB.push(other); var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, isLoose, stackA, stackB); stackA.pop(); stackB.pop(); return result; } function baseIsEqual(value, other, isLoose, stackA, stackB) { if (value === other) { return true; } if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, baseIsEqual, isLoose, stackA, stackB); } var isEqual = Rx.internals.isEqual = function (value, other) { return baseIsEqual(value, other); }; var hasProp = {}.hasOwnProperty, slice = Array.prototype.slice; var inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; var addProperties = Rx.internals.addProperties = function (obj) { for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } for (var idx = 0, ln = sources.length; idx < ln; idx++) { var source = sources[idx]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new BinaryDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { var args = [], i, len; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { len = arguments.length; args = new Array(len); for(i = 0; i < len; i++) { args[i] = arguments[i]; } } this.disposables = args; this.isDisposed = false; this.length = args.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var len = this.disposables.length, currentDisposables = new Array(len); for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; } this.disposables = []; this.length = 0; for (i = 0; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Provides a set of static methods for creating Disposables. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; /** * Validates whether the given object is a disposable * @param {Object} Object to test whether it has a dispose method * @returns {Boolean} true if a disposable object, else false. */ var isDisposable = Disposable.isDisposable = function (d) { return d && isFunction(d.dispose); }; var checkDisposed = Disposable.checkDisposed = function (disposable) { if (disposable.isDisposed) { throw new ObjectDisposedError(); } }; var disposableFixup = Disposable._fixup = function (result) { return isDisposable(result) ? result : disposableEmpty; }; // Single assignment var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = function () { this.isDisposed = false; this.current = null; }; SingleAssignmentDisposable.prototype.getDisposable = function () { return this.current; }; SingleAssignmentDisposable.prototype.setDisposable = function (value) { if (this.current) { throw new Error('Disposable has already been assigned'); } var shouldDispose = this.isDisposed; !shouldDispose && (this.current = value); shouldDispose && value && value.dispose(); }; SingleAssignmentDisposable.prototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var old = this.current; this.current = null; old && old.dispose(); } }; // Multiple assignment disposable var SerialDisposable = Rx.SerialDisposable = function () { this.isDisposed = false; this.current = null; }; SerialDisposable.prototype.getDisposable = function () { return this.current; }; SerialDisposable.prototype.setDisposable = function (value) { var shouldDispose = this.isDisposed; if (!shouldDispose) { var old = this.current; this.current = value; } old && old.dispose(); shouldDispose && value && value.dispose(); }; SerialDisposable.prototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var old = this.current; this.current = null; } old && old.dispose(); }; var BinaryDisposable = Rx.BinaryDisposable = function (first, second) { this._first = first; this._second = second; this.isDisposed = false; }; BinaryDisposable.prototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var old1 = this._first; this._first = null; old1 && old1.dispose(); var old2 = this._second; this._second = null; old2 && old2.dispose(); } }; var NAryDisposable = Rx.NAryDisposable = function (disposables) { this._disposables = disposables; this.isDisposed = false; }; NAryDisposable.prototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; for (var i = 0, len = this._disposables.length; i < len; i++) { this._disposables[i].dispose(); } this._disposables.length = 0; } }; /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed && !this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed && !this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); }; ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return disposableFixup(this.action(this.scheduler, this.state)); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { function Scheduler() { } /** Determines whether the given object is a scheduler */ Scheduler.isScheduler = function (s) { return s instanceof Scheduler; }; var schedulerProto = Scheduler.prototype; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (state, action) { throw new NotImplementedError(); }; /** * Schedules an action to be executed after dueTime. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleFuture = function (state, dueTime, action) { var dt = dueTime; dt instanceof Date && (dt = dt - this.now()); dt = Scheduler.normalize(dt); if (dt === 0) { return this.schedule(state, action); } return this._scheduleFuture(state, dt, action); }; schedulerProto._scheduleFuture = function (state, dueTime, action) { throw new NotImplementedError(); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** Gets the current time according to the local machine's system clock. */ Scheduler.prototype.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { timeSpan < 0 && (timeSpan = 0); return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize, isScheduler = Scheduler.isScheduler; (function (schedulerProto) { function invokeRecImmediate(scheduler, pair) { var state = pair[0], action = pair[1], group = new CompositeDisposable(); action(state, innerAction); return group; function innerAction(state2) { var isAdded = false, isDone = false; var d = scheduler.schedule(state2, scheduleWork); if (!isDone) { group.add(d); isAdded = true; } function scheduleWork(_, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } action(state3, innerAction); return disposableEmpty; } } } function invokeRecDate(scheduler, pair) { var state = pair[0], action = pair[1], group = new CompositeDisposable(); action(state, innerAction); return group; function innerAction(state2, dueTime1) { var isAdded = false, isDone = false; var d = scheduler.scheduleFuture(state2, dueTime1, scheduleWork); if (!isDone) { group.add(d); isAdded = true; } function scheduleWork(_, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } action(state3, innerAction); return disposableEmpty; } } } /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (state, action) { return this.schedule([state, action], invokeRecImmediate); }; /** * Schedules an action to be executed recursively after a specified relative or absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number | Date} dueTime Relative or absolute time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveFuture = function (state, dueTime, action) { return this.scheduleFuture([state, action], dueTime, invokeRecDate); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ schedulerProto.schedulePeriodic = function(state, period, action) { if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); } period = normalizeTime(period); var s = state, id = root.setInterval(function () { s = action(s); }, period); return disposableCreate(function () { root.clearInterval(id); }); }; }(Scheduler.prototype)); /** Gets a scheduler that schedules work immediately on the current thread. */ var ImmediateScheduler = (function (__super__) { inherits(ImmediateScheduler, __super__); function ImmediateScheduler() { __super__.call(this); } ImmediateScheduler.prototype.schedule = function (state, action) { return disposableFixup(action(this, state)); }; return ImmediateScheduler; }(Scheduler)); var immediateScheduler = Scheduler.immediate = new ImmediateScheduler(); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var CurrentThreadScheduler = (function (__super__) { var queue; function runTrampoline () { while (queue.length > 0) { var item = queue.dequeue(); !item.isCancelled() && item.invoke(); } } inherits(CurrentThreadScheduler, __super__); function CurrentThreadScheduler() { __super__.call(this); } CurrentThreadScheduler.prototype.schedule = function (state, action) { var si = new ScheduledItem(this, state, action, this.now()); if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); var result = tryCatch(runTrampoline)(); queue = null; if (result === errorObj) { thrower(result.e); } } else { queue.enqueue(si); } return si.disposable; }; CurrentThreadScheduler.prototype.scheduleRequired = function () { return !queue; }; return CurrentThreadScheduler; }(Scheduler)); var currentThreadScheduler = Scheduler.currentThread = new CurrentThreadScheduler(); var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function createTick(self) { return function tick(command, recurse) { recurse(0, self._period); var state = tryCatch(self._action)(self._state); if (state === errorObj) { self._cancel.dispose(); thrower(state.e); } self._state = state; }; } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveFuture(0, this._period, createTick(this))); return d; }; return SchedulePeriodicRecursive; }()); var scheduleMethod, clearMethod; var localTimer = (function () { var localSetTimeout, localClearTimeout = noop; if (!!root.setTimeout) { localSetTimeout = root.setTimeout; localClearTimeout = root.clearTimeout; } else if (!!root.WScript) { localSetTimeout = function (fn, time) { root.WScript.Sleep(time); fn(); }; } else { throw new NotSupportedError(); } return { setTimeout: localSetTimeout, clearTimeout: localClearTimeout }; }()); var localSetTimeout = localTimer.setTimeout, localClearTimeout = localTimer.clearTimeout; (function () { var nextHandle = 1, tasksByHandle = {}, currentlyRunning = false; clearMethod = function (handle) { delete tasksByHandle[handle]; }; function runTask(handle) { if (currentlyRunning) { localSetTimeout(function () { runTask(handle); }, 0); } else { var task = tasksByHandle[handle]; if (task) { currentlyRunning = true; var result = tryCatch(task)(); clearMethod(handle); currentlyRunning = false; if (result === errorObj) { thrower(result.e); } } } } var reNative = new RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('', '*'); root.onmessage = oldHandler; return isAsync; } // Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout if (isFunction(setImmediate)) { scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; setImmediate(function () { runTask(id); }); return id; }; } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; process.nextTick(function () { runTask(id); }); return id; }; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(); var onGlobalPostMessage = function (event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { runTask(event.data.substring(MSG_PREFIX.length)); } }; root.addEventListener('message', onGlobalPostMessage, false); scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; root.postMessage(MSG_PREFIX + id, '*'); return id; }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(); channel.port1.onmessage = function (e) { runTask(e.data); }; scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; channel.port2.postMessage(id); return id; }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); var id = nextHandle++; tasksByHandle[id] = action; scriptElement.onreadystatechange = function () { runTask(id); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); return id; }; } else { scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; localSetTimeout(function () { runTask(id); }, 0); return id; }; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var DefaultScheduler = (function (__super__) { inherits(DefaultScheduler, __super__); function DefaultScheduler() { __super__.call(this); } function scheduleAction(disposable, action, scheduler, state) { return function schedule() { disposable.setDisposable(Disposable._fixup(action(scheduler, state))); }; } function ClearDisposable(id) { this._id = id; this.isDisposed = false; } ClearDisposable.prototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; clearMethod(this._id); } }; function LocalClearDisposable(id) { this._id = id; this.isDisposed = false; } LocalClearDisposable.prototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; localClearTimeout(this._id); } }; DefaultScheduler.prototype.schedule = function (state, action) { var disposable = new SingleAssignmentDisposable(), id = scheduleMethod(scheduleAction(disposable, action, this, state)); return new BinaryDisposable(disposable, new ClearDisposable(id)); }; DefaultScheduler.prototype._scheduleFuture = function (state, dueTime, action) { if (dueTime === 0) { return this.schedule(state, action); } var disposable = new SingleAssignmentDisposable(), id = localSetTimeout(scheduleAction(disposable, action, this, state), dueTime); return new BinaryDisposable(disposable, new LocalClearDisposable(id)); }; function scheduleLongRunning(state, action, disposable) { return function () { action(state, disposable); }; } DefaultScheduler.prototype.scheduleLongRunning = function (state, action) { var disposable = disposableCreate(noop); scheduleMethod(scheduleLongRunning(state, action, disposable)); return disposable; }; return DefaultScheduler; }(Scheduler)); var defaultScheduler = Scheduler['default'] = Scheduler.async = new DefaultScheduler(); function IndexedItem(id, value) { this.id = id; this.value = value; } IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); c === 0 && (c = this.id - other.id); return c; }; var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { +index || (index = 0); if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; this.items[this.length] = undefined; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification() { } Notification.prototype._accept = function (onNext, onError, onCompleted) { throw new NotImplementedError(); }; Notification.prototype._acceptObserver = function (onNext, onError, onCompleted) { throw new NotImplementedError(); }; /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * @param {Function | Observer} observerOrOnNext Function to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Function to invoke for an OnError notification. * @param {Function} onCompleted Function to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { return observerOrOnNext && typeof observerOrOnNext === 'object' ? this._acceptObserver(observerOrOnNext) : this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notifications * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ Notification.prototype.toObservable = function (scheduler) { var self = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (o) { return scheduler.schedule(self, function (_, notification) { notification._acceptObserver(o); notification.kind === 'N' && o.onCompleted(); }); }); }; return Notification; })(); var OnNextNotification = (function (__super__) { inherits(OnNextNotification, __super__); function OnNextNotification(value) { this.value = value; this.kind = 'N'; } OnNextNotification.prototype._accept = function (onNext) { return onNext(this.value); }; OnNextNotification.prototype._acceptObserver = function (o) { return o.onNext(this.value); }; OnNextNotification.prototype.toString = function () { return 'OnNext(' + this.value + ')'; }; return OnNextNotification; }(Notification)); var OnErrorNotification = (function (__super__) { inherits(OnErrorNotification, __super__); function OnErrorNotification(error) { this.error = error; this.kind = 'E'; } OnErrorNotification.prototype._accept = function (onNext, onError) { return onError(this.error); }; OnErrorNotification.prototype._acceptObserver = function (o) { return o.onError(this.error); }; OnErrorNotification.prototype.toString = function () { return 'OnError(' + this.error + ')'; }; return OnErrorNotification; }(Notification)); var OnCompletedNotification = (function (__super__) { inherits(OnCompletedNotification, __super__); function OnCompletedNotification() { this.kind = 'C'; } OnCompletedNotification.prototype._accept = function (onNext, onError, onCompleted) { return onCompleted(); }; OnCompletedNotification.prototype._acceptObserver = function (o) { return o.onCompleted(); }; OnCompletedNotification.prototype.toString = function () { return 'OnCompleted()'; }; return OnCompletedNotification; }(Notification)); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = function (value) { return new OnNextNotification(value); }; /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = function (error) { return new OnErrorNotification(error); }; /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = function () { return new OnCompletedNotification(); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) { inherits(AbstractObserver, __super__); /** * Creates a new observer in a non-stopped state. */ function AbstractObserver() { this.isStopped = false; } // Must be implemented by other observers AbstractObserver.prototype.next = notImplemented; AbstractObserver.prototype.error = notImplemented; AbstractObserver.prototype.completed = notImplemented; /** * Notifies the observer of a new element in the sequence. * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { !this.isStopped && this.next(value); }; /** * Notifies the observer that an exception has occurred. * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) { inherits(AnonymousObserver, __super__); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { __super__.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (error) { this._onError(error); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function makeSubscribe(self, subscribe) { return function (o) { var oldOnError = o.onError; o.onError = function (e) { makeStackTraceLong(e, self); oldOnError.call(o, e); }; return subscribe.call(self, o); }; } function Observable() { if (Rx.config.longStackSupport && hasStacks) { var oldSubscribe = this._subscribe; var e = tryCatch(thrower)(new Error()).e; this.stack = e.stack.substring(e.stack.indexOf('\n') + 1); this._subscribe = makeSubscribe(this, oldSubscribe); } } observableProto = Observable.prototype; /** * Determines whether the given object is an Observable * @param {Any} An object to determine whether it is an Observable * @returns {Boolean} true if an Observable, else false. */ Observable.isObservable = function (o) { return o && isFunction(o.subscribe); }; /** * Subscribes an o to the observable sequence. * @param {Mixed} [oOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribe = observableProto.forEach = function (oOrOnNext, onError, onCompleted) { return this._subscribe(typeof oOrOnNext === 'object' ? oOrOnNext : observerCreate(oOrOnNext, onError, onCompleted)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onNext The function to invoke on each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnNext = function (onNext, thisArg) { return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext)); }; /** * Subscribes to an exceptional condition in the sequence with an optional "this" argument. * @param {Function} onError The function to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnError = function (onError, thisArg) { return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnCompleted = function (onCompleted, thisArg) { return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted)); }; return Observable; })(); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) { inherits(ScheduledObserver, __super__); function ScheduledObserver(scheduler, observer) { __super__.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } function enqueueNext(observer, x) { return function () { observer.onNext(x); }; } function enqueueError(observer, e) { return function () { observer.onError(e); }; } function enqueueCompleted(observer) { return function () { observer.onCompleted(); }; } ScheduledObserver.prototype.next = function (x) { this.queue.push(enqueueNext(this.observer, x)); }; ScheduledObserver.prototype.error = function (e) { this.queue.push(enqueueError(this.observer, e)); }; ScheduledObserver.prototype.completed = function () { this.queue.push(enqueueCompleted(this.observer)); }; function scheduleMethod(state, recurse) { var work; if (state.queue.length > 0) { work = state.queue.shift(); } else { state.isAcquired = false; return; } var res = tryCatch(work)(); if (res === errorObj) { state.queue = []; state.hasFaulted = true; return thrower(res.e); } recurse(state); } ScheduledObserver.prototype.ensureActive = function () { var isOwner = false; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } isOwner && this.disposable.setDisposable(this.scheduler.scheduleRecursive(this, scheduleMethod)); }; ScheduledObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); var ObservableBase = Rx.ObservableBase = (function (__super__) { inherits(ObservableBase, __super__); function fixSubscriber(subscriber) { return subscriber && isFunction(subscriber.dispose) ? subscriber : isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; } function setDisposable(s, state) { var ado = state[0], self = state[1]; var sub = tryCatch(self.subscribeCore).call(self, ado); if (sub === errorObj && !ado.fail(errorObj.e)) { thrower(errorObj.e); } ado.setDisposable(fixSubscriber(sub)); } function ObservableBase() { __super__.call(this); } ObservableBase.prototype._subscribe = function (o) { var ado = new AutoDetachObserver(o), state = [ado, this]; if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(state, setDisposable); } else { setDisposable(null, state); } return ado; }; ObservableBase.prototype.subscribeCore = notImplemented; return ObservableBase; }(Observable)); var FlatMapObservable = Rx.FlatMapObservable = (function(__super__) { inherits(FlatMapObservable, __super__); function FlatMapObservable(source, selector, resultSelector, thisArg) { this.resultSelector = isFunction(resultSelector) ? resultSelector : null; this.selector = bindCallback(isFunction(selector) ? selector : function() { return selector; }, thisArg, 3); this.source = source; __super__.call(this); } FlatMapObservable.prototype.subscribeCore = function(o) { return this.source.subscribe(new InnerObserver(o, this.selector, this.resultSelector, this)); }; inherits(InnerObserver, AbstractObserver); function InnerObserver(observer, selector, resultSelector, source) { this.i = 0; this.selector = selector; this.resultSelector = resultSelector; this.source = source; this.o = observer; AbstractObserver.call(this); } InnerObserver.prototype._wrapResult = function(result, x, i) { return this.resultSelector ? result.map(function(y, i2) { return this.resultSelector(x, y, i, i2); }, this) : result; }; InnerObserver.prototype.next = function(x) { var i = this.i++; var result = tryCatch(this.selector)(x, i, this.source); if (result === errorObj) { return this.o.onError(result.e); } isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = Observable.from(result)); this.o.onNext(this._wrapResult(result, x, i)); }; InnerObserver.prototype.error = function(e) { this.o.onError(e); }; InnerObserver.prototype.completed = function() { this.o.onCompleted(); }; return FlatMapObservable; }(ObservableBase)); var Enumerable = Rx.internals.Enumerable = function () { }; function IsDisposedDisposable(state) { this._s = state; this.isDisposed = false; } IsDisposedDisposable.prototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; this._s.isDisposed = true; } }; var ConcatEnumerableObservable = (function(__super__) { inherits(ConcatEnumerableObservable, __super__); function ConcatEnumerableObservable(sources) { this.sources = sources; __super__.call(this); } function scheduleMethod(state, recurse) { if (state.isDisposed) { return; } var currentItem = tryCatch(state.e.next).call(state.e); if (currentItem === errorObj) { return state.o.onError(currentItem.e); } if (currentItem.done) { return state.o.onCompleted(); } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); state.subscription.setDisposable(d); d.setDisposable(currentValue.subscribe(new InnerObserver(state, recurse))); } ConcatEnumerableObservable.prototype.subscribeCore = function (o) { var subscription = new SerialDisposable(); var state = { isDisposed: false, o: o, subscription: subscription, e: this.sources[$iterator$]() }; var cancelable = currentThreadScheduler.scheduleRecursive(state, scheduleMethod); return new NAryDisposable([subscription, cancelable, new IsDisposedDisposable(state)]); }; function InnerObserver(state, recurse) { this._state = state; this._recurse = recurse; AbstractObserver.call(this); } inherits(InnerObserver, AbstractObserver); InnerObserver.prototype.next = function (x) { this._state.o.onNext(x); }; InnerObserver.prototype.error = function (e) { this._state.o.onError(e); }; InnerObserver.prototype.completed = function () { this._recurse(this._state); }; return ConcatEnumerableObservable; }(ObservableBase)); Enumerable.prototype.concat = function () { return new ConcatEnumerableObservable(this); }; var CatchErrorObservable = (function(__super__) { function CatchErrorObservable(sources) { this.sources = sources; __super__.call(this); } inherits(CatchErrorObservable, __super__); function scheduleMethod(state, recurse) { if (state.isDisposed) { return; } var currentItem = tryCatch(state.e.next).call(state.e); if (currentItem === errorObj) { return state.o.onError(currentItem.e); } if (currentItem.done) { return state.lastError !== null ? state.o.onError(state.lastError) : state.o.onCompleted(); } var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); state.subscription.setDisposable(d); d.setDisposable(currentValue.subscribe(new InnerObserver(state, recurse))); } CatchErrorObservable.prototype.subscribeCore = function (o) { var subscription = new SerialDisposable(); var state = { isDisposed: false, e: this.sources[$iterator$](), subscription: subscription, lastError: null, o: o }; var cancelable = currentThreadScheduler.scheduleRecursive(state, scheduleMethod); return new NAryDisposable([subscription, cancelable, new IsDisposedDisposable(state)]); }; function InnerObserver(state, recurse) { this._state = state; this._recurse = recurse; AbstractObserver.call(this); } inherits(InnerObserver, AbstractObserver); InnerObserver.prototype.next = function (x) { this._state.o.onNext(x); }; InnerObserver.prototype.error = function (e) { this._state.lastError = e; this._recurse(this._state); }; InnerObserver.prototype.completed = function () { this._state.o.onCompleted(); }; return CatchErrorObservable; }(ObservableBase)); Enumerable.prototype.catchError = function () { return new CatchErrorObservable(this); }; var RepeatEnumerable = (function (__super__) { inherits(RepeatEnumerable, __super__); function RepeatEnumerable(v, c) { this.v = v; this.c = c == null ? -1 : c; } RepeatEnumerable.prototype[$iterator$] = function () { return new RepeatEnumerator(this); }; function RepeatEnumerator(p) { this.v = p.v; this.l = p.c; } RepeatEnumerator.prototype.next = function () { if (this.l === 0) { return doneEnumerator; } if (this.l > 0) { this.l--; } return { done: false, value: this.v }; }; return RepeatEnumerable; }(Enumerable)); var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { return new RepeatEnumerable(value, repeatCount); }; var OfEnumerable = (function(__super__) { inherits(OfEnumerable, __super__); function OfEnumerable(s, fn, thisArg) { this.s = s; this.fn = fn ? bindCallback(fn, thisArg, 3) : null; } OfEnumerable.prototype[$iterator$] = function () { return new OfEnumerator(this); }; function OfEnumerator(p) { this.i = -1; this.s = p.s; this.l = this.s.length; this.fn = p.fn; } OfEnumerator.prototype.next = function () { return ++this.i < this.l ? { done: false, value: !this.fn ? this.s[this.i] : this.fn(this.s[this.i], this.i, this.s) } : doneEnumerator; }; return OfEnumerable; }(Enumerable)); var enumerableOf = Enumerable.of = function (source, selector, thisArg) { return new OfEnumerable(source, selector, thisArg); }; var ToArrayObservable = (function(__super__) { inherits(ToArrayObservable, __super__); function ToArrayObservable(source) { this.source = source; __super__.call(this); } ToArrayObservable.prototype.subscribeCore = function(o) { return this.source.subscribe(new InnerObserver(o)); }; inherits(InnerObserver, AbstractObserver); function InnerObserver(o) { this.o = o; this.a = []; AbstractObserver.call(this); } InnerObserver.prototype.next = function (x) { this.a.push(x); }; InnerObserver.prototype.error = function (e) { this.o.onError(e); }; InnerObserver.prototype.completed = function () { this.o.onNext(this.a); this.o.onCompleted(); }; return ToArrayObservable; }(ObservableBase)); /** * Creates an array from an observable sequence. * @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { return new ToArrayObservable(this); }; /** * Creates an observable sequence from a specified subscribe method implementation. * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = function (subscribe, parent) { return new AnonymousObservable(subscribe, parent); }; var Defer = (function(__super__) { inherits(Defer, __super__); function Defer(factory) { this._f = factory; __super__.call(this); } Defer.prototype.subscribeCore = function (o) { var result = tryCatch(this._f)(); if (result === errorObj) { return observableThrow(result.e).subscribe(o);} isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(o); }; return Defer; }(ObservableBase)); /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new Defer(observableFactory); }; var EmptyObservable = (function(__super__) { inherits(EmptyObservable, __super__); function EmptyObservable(scheduler) { this.scheduler = scheduler; __super__.call(this); } EmptyObservable.prototype.subscribeCore = function (observer) { var sink = new EmptySink(observer, this.scheduler); return sink.run(); }; function EmptySink(observer, scheduler) { this.observer = observer; this.scheduler = scheduler; } function scheduleItem(s, state) { state.onCompleted(); return disposableEmpty; } EmptySink.prototype.run = function () { var state = this.observer; return this.scheduler === immediateScheduler ? scheduleItem(null, state) : this.scheduler.schedule(state, scheduleItem); }; return EmptyObservable; }(ObservableBase)); var EMPTY_OBSERVABLE = new EmptyObservable(immediateScheduler); /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return scheduler === immediateScheduler ? EMPTY_OBSERVABLE : new EmptyObservable(scheduler); }; var FromObservable = (function(__super__) { inherits(FromObservable, __super__); function FromObservable(iterable, fn, scheduler) { this._iterable = iterable; this._fn = fn; this._scheduler = scheduler; __super__.call(this); } function createScheduleMethod(o, it, fn) { return function loopRecursive(i, recurse) { var next = tryCatch(it.next).call(it); if (next === errorObj) { return o.onError(next.e); } if (next.done) { return o.onCompleted(); } var result = next.value; if (isFunction(fn)) { result = tryCatch(fn)(result, i); if (result === errorObj) { return o.onError(result.e); } } o.onNext(result); recurse(i + 1); }; } FromObservable.prototype.subscribeCore = function (o) { var list = Object(this._iterable), it = getIterable(list); return this._scheduler.scheduleRecursive(0, createScheduleMethod(o, it, this._fn)); }; return FromObservable; }(ObservableBase)); var maxSafeInteger = Math.pow(2, 53) - 1; function StringIterable(s) { this._s = s; } StringIterable.prototype[$iterator$] = function () { return new StringIterator(this._s); }; function StringIterator(s) { this._s = s; this._l = s.length; this._i = 0; } StringIterator.prototype[$iterator$] = function () { return this; }; StringIterator.prototype.next = function () { return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator; }; function ArrayIterable(a) { this._a = a; } ArrayIterable.prototype[$iterator$] = function () { return new ArrayIterator(this._a); }; function ArrayIterator(a) { this._a = a; this._l = toLength(a); this._i = 0; } ArrayIterator.prototype[$iterator$] = function () { return this; }; ArrayIterator.prototype.next = function () { return this._i < this._l ? { done: false, value: this._a[this._i++] } : doneEnumerator; }; function numberIsFinite(value) { return typeof value === 'number' && root.isFinite(value); } function isNan(n) { return n !== n; } function getIterable(o) { var i = o[$iterator$], it; if (!i && typeof o === 'string') { it = new StringIterable(o); return it[$iterator$](); } if (!i && o.length !== undefined) { it = new ArrayIterable(o); return it[$iterator$](); } if (!i) { throw new TypeError('Object is not iterable'); } return o[$iterator$](); } function sign(value) { var number = +value; if (number === 0) { return number; } if (isNaN(number)) { return number; } return number < 0 ? -1 : 1; } function toLength(o) { var len = +o.length; if (isNaN(len)) { return 0; } if (len === 0 || !numberIsFinite(len)) { return len; } len = sign(len) * Math.floor(Math.abs(len)); if (len <= 0) { return 0; } if (len > maxSafeInteger) { return maxSafeInteger; } return len; } /** * This method creates a new Observable sequence from an array-like or iterable object. * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. * @param {Function} [mapFn] Map function to call on every element of the array. * @param {Any} [thisArg] The context to use calling the mapFn if provided. * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) { if (iterable == null) { throw new Error('iterable cannot be null.') } if (mapFn && !isFunction(mapFn)) { throw new Error('mapFn when provided must be a function'); } if (mapFn) { var mapper = bindCallback(mapFn, thisArg, 2); } isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromObservable(iterable, mapper, scheduler); } var FromArrayObservable = (function(__super__) { inherits(FromArrayObservable, __super__); function FromArrayObservable(args, scheduler) { this._args = args; this._scheduler = scheduler; __super__.call(this); } function scheduleMethod(o, args) { var len = args.length; return function loopRecursive (i, recurse) { if (i < len) { o.onNext(args[i]); recurse(i + 1); } else { o.onCompleted(); } }; } FromArrayObservable.prototype.subscribeCore = function (o) { return this._scheduler.scheduleRecursive(0, scheduleMethod(o, this._args)); }; return FromArrayObservable; }(ObservableBase)); /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * @deprecated use Observable.from or Observable.of * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromArrayObservable(array, scheduler) }; var NeverObservable = (function(__super__) { inherits(NeverObservable, __super__); function NeverObservable() { __super__.call(this); } NeverObservable.prototype.subscribeCore = function (observer) { return disposableEmpty; }; return NeverObservable; }(ObservableBase)); var NEVER_OBSERVABLE = new NeverObservable(); /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return NEVER_OBSERVABLE; }; function observableOf (scheduler, array) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromArrayObservable(array, scheduler); } /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.of = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return new FromArrayObservable(args, currentThreadScheduler); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.ofWithScheduler = function (scheduler) { var len = arguments.length, args = new Array(len - 1); for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; } return new FromArrayObservable(args, scheduler); }; var PairsObservable = (function(__super__) { inherits(PairsObservable, __super__); function PairsObservable(o, scheduler) { this._o = o; this._keys = Object.keys(o); this._scheduler = scheduler; __super__.call(this); } function scheduleMethod(o, obj, keys) { return function loopRecursive(i, recurse) { if (i < keys.length) { var key = keys[i]; o.onNext([key, obj[key]]); recurse(i + 1); } else { o.onCompleted(); } }; } PairsObservable.prototype.subscribeCore = function (o) { return this._scheduler.scheduleRecursive(0, scheduleMethod(o, this._o, this._keys)); }; return PairsObservable; }(ObservableBase)); /** * Convert an object into an observable sequence of [key, value] pairs. * @param {Object} obj The object to inspect. * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} An observable sequence of [key, value] pairs from the object. */ Observable.pairs = function (obj, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new PairsObservable(obj, scheduler); }; var RangeObservable = (function(__super__) { inherits(RangeObservable, __super__); function RangeObservable(start, count, scheduler) { this.start = start; this.rangeCount = count; this.scheduler = scheduler; __super__.call(this); } function loopRecursive(start, count, o) { return function loop (i, recurse) { if (i < count) { o.onNext(start + i); recurse(i + 1); } else { o.onCompleted(); } }; } RangeObservable.prototype.subscribeCore = function (o) { return this.scheduler.scheduleRecursive( 0, loopRecursive(this.start, this.rangeCount, o) ); }; return RangeObservable; }(ObservableBase)); /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new RangeObservable(start, count, scheduler); }; var RepeatObservable = (function(__super__) { inherits(RepeatObservable, __super__); function RepeatObservable(value, repeatCount, scheduler) { this.value = value; this.repeatCount = repeatCount == null ? -1 : repeatCount; this.scheduler = scheduler; __super__.call(this); } RepeatObservable.prototype.subscribeCore = function (observer) { var sink = new RepeatSink(observer, this); return sink.run(); }; return RepeatObservable; }(ObservableBase)); function RepeatSink(observer, parent) { this.observer = observer; this.parent = parent; } RepeatSink.prototype.run = function () { var observer = this.observer, value = this.parent.value; function loopRecursive(i, recurse) { if (i === -1 || i > 0) { observer.onNext(value); i > 0 && i--; } if (i === 0) { return observer.onCompleted(); } recurse(i); } return this.parent.scheduler.scheduleRecursive(this.parent.repeatCount, loopRecursive); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new RepeatObservable(value, repeatCount, scheduler); }; var JustObservable = (function(__super__) { inherits(JustObservable, __super__); function JustObservable(value, scheduler) { this._value = value; this._scheduler = scheduler; __super__.call(this); } JustObservable.prototype.subscribeCore = function (o) { var state = [this._value, o]; return this._scheduler === immediateScheduler ? scheduleItem(null, state) : this._scheduler.schedule(state, scheduleItem); }; function scheduleItem(s, state) { var value = state[0], observer = state[1]; observer.onNext(value); observer.onCompleted(); return disposableEmpty; } return JustObservable; }(ObservableBase)); /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'just' or browsers <IE9. * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.just = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new JustObservable(value, scheduler); }; var ThrowObservable = (function(__super__) { inherits(ThrowObservable, __super__); function ThrowObservable(error, scheduler) { this._error = error; this._scheduler = scheduler; __super__.call(this); } ThrowObservable.prototype.subscribeCore = function (o) { var state = [this._error, o]; return this._scheduler === immediateScheduler ? scheduleItem(null, state) : this._scheduler.schedule(state, scheduleItem); }; function scheduleItem(s, state) { var e = state[0], o = state[1]; o.onError(e); return disposableEmpty; } return ThrowObservable; }(ObservableBase)); /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwError' for browsers <IE9. * @param {Mixed} error An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = function (error, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new ThrowObservable(error, scheduler); }; var CatchObservable = (function (__super__) { inherits(CatchObservable, __super__); function CatchObservable(source, fn) { this.source = source; this._fn = fn; __super__.call(this); } CatchObservable.prototype.subscribeCore = function (o) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(this.source.subscribe(new CatchObserver(o, subscription, this._fn))); return subscription; }; return CatchObservable; }(ObservableBase)); var CatchObserver = (function(__super__) { inherits(CatchObserver, __super__); function CatchObserver(o, s, fn) { this._o = o; this._s = s; this._fn = fn; __super__.call(this); } CatchObserver.prototype.next = function (x) { this._o.onNext(x); }; CatchObserver.prototype.completed = function () { return this._o.onCompleted(); }; CatchObserver.prototype.error = function (e) { var result = tryCatch(this._fn)(e); if (result === errorObj) { return this._o.onError(result.e); } isPromise(result) && (result = observableFromPromise(result)); var d = new SingleAssignmentDisposable(); this._s.setDisposable(d); d.setDisposable(result.subscribe(this._o)); }; return CatchObserver; }(AbstractObserver)); /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = function (handlerOrSecond) { return isFunction(handlerOrSecond) ? new CatchObservable(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs. * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable['catch'] = function () { var items; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { var len = arguments.length; items = new Array(len); for(var i = 0; i < len; i++) { items[i] = arguments[i]; } } return enumerableOf(items).catchError(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; function falseFactory() { return false; } function argumentsToArray() { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return args; } var CombineLatestObservable = (function(__super__) { inherits(CombineLatestObservable, __super__); function CombineLatestObservable(params, cb) { this._params = params; this._cb = cb; __super__.call(this); } CombineLatestObservable.prototype.subscribeCore = function(observer) { var len = this._params.length, subscriptions = new Array(len); var state = { hasValue: arrayInitialize(len, falseFactory), hasValueAll: false, isDone: arrayInitialize(len, falseFactory), values: new Array(len) }; for (var i = 0; i < len; i++) { var source = this._params[i], sad = new SingleAssignmentDisposable(); subscriptions[i] = sad; isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(new CombineLatestObserver(observer, i, this._cb, state))); } return new NAryDisposable(subscriptions); }; return CombineLatestObservable; }(ObservableBase)); var CombineLatestObserver = (function (__super__) { inherits(CombineLatestObserver, __super__); function CombineLatestObserver(o, i, cb, state) { this._o = o; this._i = i; this._cb = cb; this._state = state; __super__.call(this); } function notTheSame(i) { return function (x, j) { return j !== i; }; } CombineLatestObserver.prototype.next = function (x) { this._state.values[this._i] = x; this._state.hasValue[this._i] = true; if (this._state.hasValueAll || (this._state.hasValueAll = this._state.hasValue.every(identity))) { var res = tryCatch(this._cb).apply(null, this._state.values); if (res === errorObj) { return this._o.onError(res.e); } this._o.onNext(res); } else if (this._state.isDone.filter(notTheSame(this._i)).every(identity)) { this._o.onCompleted(); } }; CombineLatestObserver.prototype.error = function (e) { this._o.onError(e); }; CombineLatestObserver.prototype.completed = function () { this._state.isDone[this._i] = true; this._state.isDone.every(identity) && this._o.onCompleted(); }; return CombineLatestObserver; }(AbstractObserver)); /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray; Array.isArray(args[0]) && (args = args[0]); return new CombineLatestObservable(args, resultSelector); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } args.unshift(this); return observableConcat.apply(null, args); }; var ConcatObserver = (function(__super__) { inherits(ConcatObserver, __super__); function ConcatObserver(s, fn) { this._s = s; this._fn = fn; __super__.call(this); } ConcatObserver.prototype.next = function (x) { this._s.o.onNext(x); }; ConcatObserver.prototype.error = function (e) { this._s.o.onError(e); }; ConcatObserver.prototype.completed = function () { this._s.i++; this._fn(this._s); }; return ConcatObserver; }(AbstractObserver)); var ConcatObservable = (function(__super__) { inherits(ConcatObservable, __super__); function ConcatObservable(sources) { this._sources = sources; __super__.call(this); } function scheduleRecursive (state, recurse) { if (state.disposable.isDisposed) { return; } if (state.i === state.sources.length) { return state.o.onCompleted(); } // Check if promise var currentValue = state.sources[state.i]; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); state.subscription.setDisposable(d); d.setDisposable(currentValue.subscribe(new ConcatObserver(state, recurse))); } ConcatObservable.prototype.subscribeCore = function(o) { var subscription = new SerialDisposable(); var disposable = disposableCreate(noop); var state = { o: o, i: 0, subscription: subscription, disposable: disposable, sources: this._sources }; var cancelable = immediateScheduler.scheduleRecursive(state, scheduleRecursive); return new NAryDisposable([subscription, disposable, cancelable]); }; return ConcatObservable; }(ObservableBase)); /** * Concatenates all the observable sequences. * @param {Array | Arguments} args Arguments or an array to concat to the observable sequence. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { args = new Array(arguments.length); for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; } } return new ConcatObservable(args); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatAll = function () { return this.merge(1); }; var MergeObservable = (function (__super__) { inherits(MergeObservable, __super__); function MergeObservable(source, maxConcurrent) { this.source = source; this.maxConcurrent = maxConcurrent; __super__.call(this); } MergeObservable.prototype.subscribeCore = function(observer) { var g = new CompositeDisposable(); g.add(this.source.subscribe(new MergeObserver(observer, this.maxConcurrent, g))); return g; }; return MergeObservable; }(ObservableBase)); var MergeObserver = (function (__super__) { function MergeObserver(o, max, g) { this.o = o; this.max = max; this.g = g; this.done = false; this.q = []; this.activeCount = 0; __super__.call(this); } inherits(MergeObserver, __super__); MergeObserver.prototype.handleSubscribe = function (xs) { var sad = new SingleAssignmentDisposable(); this.g.add(sad); isPromise(xs) && (xs = observableFromPromise(xs)); sad.setDisposable(xs.subscribe(new InnerObserver(this, sad))); }; MergeObserver.prototype.next = function (innerSource) { if(this.activeCount < this.max) { this.activeCount++; this.handleSubscribe(innerSource); } else { this.q.push(innerSource); } }; MergeObserver.prototype.error = function (e) { this.o.onError(e); }; MergeObserver.prototype.completed = function () { this.done = true; this.activeCount === 0 && this.o.onCompleted(); }; function InnerObserver(parent, sad) { this.parent = parent; this.sad = sad; __super__.call(this); } inherits(InnerObserver, __super__); InnerObserver.prototype.next = function (x) { this.parent.o.onNext(x); }; InnerObserver.prototype.error = function (e) { this.parent.o.onError(e); }; InnerObserver.prototype.completed = function () { this.parent.g.remove(this.sad); if (this.parent.q.length > 0) { this.parent.handleSubscribe(this.parent.q.shift()); } else { this.parent.activeCount--; this.parent.done && this.parent.activeCount === 0 && this.parent.o.onCompleted(); } }; return MergeObserver; }(AbstractObserver)); /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { return typeof maxConcurrentOrOther !== 'number' ? observableMerge(this, maxConcurrentOrOther) : new MergeObservable(this, maxConcurrentOrOther); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources = [], i, len = arguments.length; if (!arguments[0]) { scheduler = immediateScheduler; for(i = 1; i < len; i++) { sources.push(arguments[i]); } } else if (isScheduler(arguments[0])) { scheduler = arguments[0]; for(i = 1; i < len; i++) { sources.push(arguments[i]); } } else { scheduler = immediateScheduler; for(i = 0; i < len; i++) { sources.push(arguments[i]); } } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableOf(scheduler, sources).mergeAll(); }; var CompositeError = Rx.CompositeError = function(errors) { this.innerErrors = errors; this.message = 'This contains multiple errors. Check the innerErrors'; Error.call(this); }; CompositeError.prototype = Object.create(Error.prototype); CompositeError.prototype.name = 'CompositeError'; var MergeDelayErrorObservable = (function(__super__) { inherits(MergeDelayErrorObservable, __super__); function MergeDelayErrorObservable(source) { this.source = source; __super__.call(this); } MergeDelayErrorObservable.prototype.subscribeCore = function (o) { var group = new CompositeDisposable(), m = new SingleAssignmentDisposable(), state = { isStopped: false, errors: [], o: o }; group.add(m); m.setDisposable(this.source.subscribe(new MergeDelayErrorObserver(group, state))); return group; }; return MergeDelayErrorObservable; }(ObservableBase)); var MergeDelayErrorObserver = (function(__super__) { inherits(MergeDelayErrorObserver, __super__); function MergeDelayErrorObserver(group, state) { this._group = group; this._state = state; __super__.call(this); } function setCompletion(o, errors) { if (errors.length === 0) { o.onCompleted(); } else if (errors.length === 1) { o.onError(errors[0]); } else { o.onError(new CompositeError(errors)); } } MergeDelayErrorObserver.prototype.next = function (x) { var inner = new SingleAssignmentDisposable(); this._group.add(inner); // Check for promises support isPromise(x) && (x = observableFromPromise(x)); inner.setDisposable(x.subscribe(new InnerObserver(inner, this._group, this._state))); }; MergeDelayErrorObserver.prototype.error = function (e) { this._state.errors.push(e); this._state.isStopped = true; this._group.length === 1 && setCompletion(this._state.o, this._state.errors); }; MergeDelayErrorObserver.prototype.completed = function () { this._state.isStopped = true; this._group.length === 1 && setCompletion(this._state.o, this._state.errors); }; inherits(InnerObserver, __super__); function InnerObserver(inner, group, state) { this._inner = inner; this._group = group; this._state = state; __super__.call(this); } InnerObserver.prototype.next = function (x) { this._state.o.onNext(x); }; InnerObserver.prototype.error = function (e) { this._state.errors.push(e); this._group.remove(this._inner); this._state.isStopped && this._group.length === 1 && setCompletion(this._state.o, this._state.errors); }; InnerObserver.prototype.completed = function () { this._group.remove(this._inner); this._state.isStopped && this._group.length === 1 && setCompletion(this._state.o, this._state.errors); }; return MergeDelayErrorObserver; }(AbstractObserver)); /** * Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to * receive all successfully emitted items from all of the source Observables without being interrupted by * an error notification from one of them. * * This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an * error via the Observer's onError, mergeDelayError will refrain from propagating that * error notification until all of the merged Observables have finished emitting items. * @param {Array | Arguments} args Arguments or an array to merge. * @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable */ Observable.mergeDelayError = function() { var args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { var len = arguments.length; args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } } var source = observableOf(null, args); return new MergeDelayErrorObservable(source); }; var MergeAllObservable = (function (__super__) { inherits(MergeAllObservable, __super__); function MergeAllObservable(source) { this.source = source; __super__.call(this); } MergeAllObservable.prototype.subscribeCore = function (o) { var g = new CompositeDisposable(), m = new SingleAssignmentDisposable(); g.add(m); m.setDisposable(this.source.subscribe(new MergeAllObserver(o, g))); return g; }; return MergeAllObservable; }(ObservableBase)); var MergeAllObserver = (function (__super__) { function MergeAllObserver(o, g) { this.o = o; this.g = g; this.done = false; __super__.call(this); } inherits(MergeAllObserver, __super__); MergeAllObserver.prototype.next = function(innerSource) { var sad = new SingleAssignmentDisposable(); this.g.add(sad); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); sad.setDisposable(innerSource.subscribe(new InnerObserver(this, sad))); }; MergeAllObserver.prototype.error = function (e) { this.o.onError(e); }; MergeAllObserver.prototype.completed = function () { this.done = true; this.g.length === 1 && this.o.onCompleted(); }; function InnerObserver(parent, sad) { this.parent = parent; this.sad = sad; __super__.call(this); } inherits(InnerObserver, __super__); InnerObserver.prototype.next = function (x) { this.parent.o.onNext(x); }; InnerObserver.prototype.error = function (e) { this.parent.o.onError(e); }; InnerObserver.prototype.completed = function () { this.parent.g.remove(this.sad); this.parent.done && this.parent.g.length === 1 && this.parent.o.onCompleted(); }; return MergeAllObserver; }(AbstractObserver)); /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeAll = function () { return new MergeAllObservable(this); }; var SkipUntilObservable = (function(__super__) { inherits(SkipUntilObservable, __super__); function SkipUntilObservable(source, other) { this._s = source; this._o = isPromise(other) ? observableFromPromise(other) : other; this._open = false; __super__.call(this); } SkipUntilObservable.prototype.subscribeCore = function(o) { var leftSubscription = new SingleAssignmentDisposable(); leftSubscription.setDisposable(this._s.subscribe(new SkipUntilSourceObserver(o, this))); isPromise(this._o) && (this._o = observableFromPromise(this._o)); var rightSubscription = new SingleAssignmentDisposable(); rightSubscription.setDisposable(this._o.subscribe(new SkipUntilOtherObserver(o, this, rightSubscription))); return new BinaryDisposable(leftSubscription, rightSubscription); }; return SkipUntilObservable; }(ObservableBase)); var SkipUntilSourceObserver = (function(__super__) { inherits(SkipUntilSourceObserver, __super__); function SkipUntilSourceObserver(o, p) { this._o = o; this._p = p; __super__.call(this); } SkipUntilSourceObserver.prototype.next = function (x) { this._p._open && this._o.onNext(x); }; SkipUntilSourceObserver.prototype.error = function (err) { this._o.onError(err); }; SkipUntilSourceObserver.prototype.onCompleted = function () { this._p._open && this._o.onCompleted(); }; return SkipUntilSourceObserver; }(AbstractObserver)); var SkipUntilOtherObserver = (function(__super__) { inherits(SkipUntilOtherObserver, __super__); function SkipUntilOtherObserver(o, p, r) { this._o = o; this._p = p; this._r = r; __super__.call(this); } SkipUntilOtherObserver.prototype.next = function () { this._p._open = true; this._r.dispose(); }; SkipUntilOtherObserver.prototype.error = function (err) { this._o.onError(err); }; SkipUntilOtherObserver.prototype.onCompleted = function () { this._r.dispose(); }; return SkipUntilOtherObserver; }(AbstractObserver)); /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { return new SkipUntilObservable(this, other); }; var SwitchObservable = (function(__super__) { inherits(SwitchObservable, __super__); function SwitchObservable(source) { this.source = source; __super__.call(this); } SwitchObservable.prototype.subscribeCore = function (o) { var inner = new SerialDisposable(), s = this.source.subscribe(new SwitchObserver(o, inner)); return new BinaryDisposable(s, inner); }; inherits(SwitchObserver, AbstractObserver); function SwitchObserver(o, inner) { this.o = o; this.inner = inner; this.stopped = false; this.latest = 0; this.hasLatest = false; AbstractObserver.call(this); } SwitchObserver.prototype.next = function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++this.latest; this.hasLatest = true; this.inner.setDisposable(d); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); d.setDisposable(innerSource.subscribe(new InnerObserver(this, id))); }; SwitchObserver.prototype.error = function (e) { this.o.onError(e); }; SwitchObserver.prototype.completed = function () { this.stopped = true; !this.hasLatest && this.o.onCompleted(); }; inherits(InnerObserver, AbstractObserver); function InnerObserver(parent, id) { this.parent = parent; this.id = id; AbstractObserver.call(this); } InnerObserver.prototype.next = function (x) { this.parent.latest === this.id && this.parent.o.onNext(x); }; InnerObserver.prototype.error = function (e) { this.parent.latest === this.id && this.parent.o.onError(e); }; InnerObserver.prototype.completed = function () { if (this.parent.latest === this.id) { this.parent.hasLatest = false; this.parent.stopped && this.parent.o.onCompleted(); } }; return SwitchObservable; }(ObservableBase)); /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { return new SwitchObservable(this); }; var TakeUntilObservable = (function(__super__) { inherits(TakeUntilObservable, __super__); function TakeUntilObservable(source, other) { this.source = source; this.other = isPromise(other) ? observableFromPromise(other) : other; __super__.call(this); } TakeUntilObservable.prototype.subscribeCore = function(o) { return new BinaryDisposable( this.source.subscribe(o), this.other.subscribe(new TakeUntilObserver(o)) ); }; return TakeUntilObservable; }(ObservableBase)); var TakeUntilObserver = (function(__super__) { inherits(TakeUntilObserver, __super__); function TakeUntilObserver(o) { this._o = o; __super__.call(this); } TakeUntilObserver.prototype.next = function () { this._o.onCompleted(); }; TakeUntilObserver.prototype.error = function (err) { this._o.onError(err); }; TakeUntilObserver.prototype.onCompleted = noop; return TakeUntilObserver; }(AbstractObserver)); /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { return new TakeUntilObservable(this, other); }; function falseFactory() { return false; } function argumentsToArray() { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return args; } var WithLatestFromObservable = (function(__super__) { inherits(WithLatestFromObservable, __super__); function WithLatestFromObservable(source, sources, resultSelector) { this._s = source; this._ss = sources; this._cb = resultSelector; __super__.call(this); } WithLatestFromObservable.prototype.subscribeCore = function (o) { var len = this._ss.length; var state = { hasValue: arrayInitialize(len, falseFactory), hasValueAll: false, values: new Array(len) }; var n = this._ss.length, subscriptions = new Array(n + 1); for (var i = 0; i < n; i++) { var other = this._ss[i], sad = new SingleAssignmentDisposable(); isPromise(other) && (other = observableFromPromise(other)); sad.setDisposable(other.subscribe(new WithLatestFromOtherObserver(o, i, state))); subscriptions[i] = sad; } var outerSad = new SingleAssignmentDisposable(); outerSad.setDisposable(this._s.subscribe(new WithLatestFromSourceObserver(o, this._cb, state))); subscriptions[n] = outerSad; return new NAryDisposable(subscriptions); }; return WithLatestFromObservable; }(ObservableBase)); var WithLatestFromOtherObserver = (function (__super__) { inherits(WithLatestFromOtherObserver, __super__); function WithLatestFromOtherObserver(o, i, state) { this._o = o; this._i = i; this._state = state; __super__.call(this); } WithLatestFromOtherObserver.prototype.next = function (x) { this._state.values[this._i] = x; this._state.hasValue[this._i] = true; this._state.hasValueAll = this._state.hasValue.every(identity); }; WithLatestFromOtherObserver.prototype.error = function (e) { this._o.onError(e); }; WithLatestFromOtherObserver.prototype.completed = noop; return WithLatestFromOtherObserver; }(AbstractObserver)); var WithLatestFromSourceObserver = (function (__super__) { inherits(WithLatestFromSourceObserver, __super__); function WithLatestFromSourceObserver(o, cb, state) { this._o = o; this._cb = cb; this._state = state; __super__.call(this); } WithLatestFromSourceObserver.prototype.next = function (x) { var allValues = [x].concat(this._state.values); if (!this._state.hasValueAll) { return; } var res = tryCatch(this._cb).apply(null, allValues); if (res === errorObj) { return this._o.onError(res.e); } this._o.onNext(res); }; WithLatestFromSourceObserver.prototype.error = function (e) { this._o.onError(e); }; WithLatestFromSourceObserver.prototype.completed = function () { this._o.onCompleted(); }; return WithLatestFromSourceObserver; }(AbstractObserver)); /** * Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.withLatestFrom = function () { if (arguments.length === 0) { throw new Error('invalid arguments'); } var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray; Array.isArray(args[0]) && (args = args[0]); return new WithLatestFromObservable(this, args, resultSelector); }; function falseFactory() { return false; } function emptyArrayFactory() { return []; } var ZipObservable = (function(__super__) { inherits(ZipObservable, __super__); function ZipObservable(sources, resultSelector) { this._s = sources; this._cb = resultSelector; __super__.call(this); } ZipObservable.prototype.subscribeCore = function(observer) { var n = this._s.length, subscriptions = new Array(n), done = arrayInitialize(n, falseFactory), q = arrayInitialize(n, emptyArrayFactory); for (var i = 0; i < n; i++) { var source = this._s[i], sad = new SingleAssignmentDisposable(); subscriptions[i] = sad; isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(new ZipObserver(observer, i, this, q, done))); } return new NAryDisposable(subscriptions); }; return ZipObservable; }(ObservableBase)); var ZipObserver = (function (__super__) { inherits(ZipObserver, __super__); function ZipObserver(o, i, p, q, d) { this._o = o; this._i = i; this._p = p; this._q = q; this._d = d; __super__.call(this); } function notEmpty(x) { return x.length > 0; } function shiftEach(x) { return x.shift(); } function notTheSame(i) { return function (x, j) { return j !== i; }; } ZipObserver.prototype.next = function (x) { this._q[this._i].push(x); if (this._q.every(notEmpty)) { var queuedValues = this._q.map(shiftEach); var res = tryCatch(this._p._cb).apply(null, queuedValues); if (res === errorObj) { return this._o.onError(res.e); } this._o.onNext(res); } else if (this._d.filter(notTheSame(this._i)).every(identity)) { this._o.onCompleted(); } }; ZipObserver.prototype.error = function (e) { this._o.onError(e); }; ZipObserver.prototype.completed = function () { this._d[this._i] = true; this._d.every(identity) && this._o.onCompleted(); }; return ZipObserver; }(AbstractObserver)); /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args. * @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function. */ observableProto.zip = function () { if (arguments.length === 0) { throw new Error('invalid arguments'); } var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray; Array.isArray(args[0]) && (args = args[0]); var parent = this; args.unshift(parent); return new ZipObservable(args, resultSelector); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } if (Array.isArray(args[0])) { args = isFunction(args[1]) ? args[0].concat(args[1]) : args[0]; } var first = args.shift(); return first.zip.apply(first, args); }; function falseFactory() { return false; } function emptyArrayFactory() { return []; } function argumentsToArray() { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return args; } var ZipIterableObservable = (function(__super__) { inherits(ZipIterableObservable, __super__); function ZipIterableObservable(sources, cb) { this.sources = sources; this._cb = cb; __super__.call(this); } ZipIterableObservable.prototype.subscribeCore = function (o) { var sources = this.sources, len = sources.length, subscriptions = new Array(len); var state = { q: arrayInitialize(len, emptyArrayFactory), done: arrayInitialize(len, falseFactory), cb: this._cb, o: o }; for (var i = 0; i < len; i++) { (function (i) { var source = sources[i], sad = new SingleAssignmentDisposable(); (isArrayLike(source) || isIterable(source)) && (source = observableFrom(source)); subscriptions[i] = sad; sad.setDisposable(source.subscribe(new ZipIterableObserver(state, i))); }(i)); } return new NAryDisposable(subscriptions); }; return ZipIterableObservable; }(ObservableBase)); var ZipIterableObserver = (function (__super__) { inherits(ZipIterableObserver, __super__); function ZipIterableObserver(s, i) { this._s = s; this._i = i; __super__.call(this); } function notEmpty(x) { return x.length > 0; } function shiftEach(x) { return x.shift(); } function notTheSame(i) { return function (x, j) { return j !== i; }; } ZipIterableObserver.prototype.next = function (x) { this._s.q[this._i].push(x); if (this._s.q.every(notEmpty)) { var queuedValues = this._s.q.map(shiftEach), res = tryCatch(this._s.cb).apply(null, queuedValues); if (res === errorObj) { return this._s.o.onError(res.e); } this._s.o.onNext(res); } else if (this._s.done.filter(notTheSame(this._i)).every(identity)) { this._s.o.onCompleted(); } }; ZipIterableObserver.prototype.error = function (e) { this._s.o.onError(e); }; ZipIterableObserver.prototype.completed = function () { this._s.done[this._i] = true; this._s.done.every(identity) && this._s.o.onCompleted(); }; return ZipIterableObserver; }(AbstractObserver)); /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args. * @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function. */ observableProto.zipIterable = function () { if (arguments.length === 0) { throw new Error('invalid arguments'); } var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray; var parent = this; args.unshift(parent); return new ZipIterableObservable(args, resultSelector); }; function asObservable(source) { return function subscribe(o) { return source.subscribe(o); }; } /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { return new AnonymousObservable(asObservable(this), this); }; var DematerializeObservable = (function (__super__) { inherits(DematerializeObservable, __super__); function DematerializeObservable(source) { this.source = source; __super__.call(this); } DematerializeObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new DematerializeObserver(o)); }; return DematerializeObservable; }(ObservableBase)); var DematerializeObserver = (function (__super__) { inherits(DematerializeObserver, __super__); function DematerializeObserver(o) { this._o = o; __super__.call(this); } DematerializeObserver.prototype.next = function (x) { x.accept(this._o); }; DematerializeObserver.prototype.error = function (e) { this._o.onError(e); }; DematerializeObserver.prototype.completed = function () { this._o.onCompleted(); }; return DematerializeObserver; }(AbstractObserver)); /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { return new DematerializeObservable(this); }; var DistinctUntilChangedObservable = (function(__super__) { inherits(DistinctUntilChangedObservable, __super__); function DistinctUntilChangedObservable(source, keyFn, comparer) { this.source = source; this.keyFn = keyFn; this.comparer = comparer; __super__.call(this); } DistinctUntilChangedObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new DistinctUntilChangedObserver(o, this.keyFn, this.comparer)); }; return DistinctUntilChangedObservable; }(ObservableBase)); var DistinctUntilChangedObserver = (function(__super__) { inherits(DistinctUntilChangedObserver, __super__); function DistinctUntilChangedObserver(o, keyFn, comparer) { this.o = o; this.keyFn = keyFn; this.comparer = comparer; this.hasCurrentKey = false; this.currentKey = null; __super__.call(this); } DistinctUntilChangedObserver.prototype.next = function (x) { var key = x, comparerEquals; if (isFunction(this.keyFn)) { key = tryCatch(this.keyFn)(x); if (key === errorObj) { return this.o.onError(key.e); } } if (this.hasCurrentKey) { comparerEquals = tryCatch(this.comparer)(this.currentKey, key); if (comparerEquals === errorObj) { return this.o.onError(comparerEquals.e); } } if (!this.hasCurrentKey || !comparerEquals) { this.hasCurrentKey = true; this.currentKey = key; this.o.onNext(x); } }; DistinctUntilChangedObserver.prototype.error = function(e) { this.o.onError(e); }; DistinctUntilChangedObserver.prototype.completed = function () { this.o.onCompleted(); }; return DistinctUntilChangedObserver; }(AbstractObserver)); /** * Returns an observable sequence that contains only distinct contiguous elements according to the keyFn and the comparer. * @param {Function} [keyFn] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keyFn, comparer) { comparer || (comparer = defaultComparer); return new DistinctUntilChangedObservable(this, keyFn, comparer); }; var TapObservable = (function(__super__) { inherits(TapObservable,__super__); function TapObservable(source, observerOrOnNext, onError, onCompleted) { this.source = source; this._oN = observerOrOnNext; this._oE = onError; this._oC = onCompleted; __super__.call(this); } TapObservable.prototype.subscribeCore = function(o) { return this.source.subscribe(new InnerObserver(o, this)); }; inherits(InnerObserver, AbstractObserver); function InnerObserver(o, p) { this.o = o; this.t = !p._oN || isFunction(p._oN) ? observerCreate(p._oN || noop, p._oE || noop, p._oC || noop) : p._oN; this.isStopped = false; AbstractObserver.call(this); } InnerObserver.prototype.next = function(x) { var res = tryCatch(this.t.onNext).call(this.t, x); if (res === errorObj) { this.o.onError(res.e); } this.o.onNext(x); }; InnerObserver.prototype.error = function(err) { var res = tryCatch(this.t.onError).call(this.t, err); if (res === errorObj) { return this.o.onError(res.e); } this.o.onError(err); }; InnerObserver.prototype.completed = function() { var res = tryCatch(this.t.onCompleted).call(this.t); if (res === errorObj) { return this.o.onError(res.e); } this.o.onCompleted(); }; return TapObservable; }(ObservableBase)); /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an o. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { return new TapObservable(this, observerOrOnNext, onError, onCompleted); }; /** * Invokes an action for each element in the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onNext Action to invoke for each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) { return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext); }; /** * Invokes an action upon exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onError Action to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) { return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError); }; /** * Invokes an action upon graceful termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) { return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted); }; var FinallyObservable = (function (__super__) { inherits(FinallyObservable, __super__); function FinallyObservable(source, fn, thisArg) { this.source = source; this._fn = bindCallback(fn, thisArg, 0); __super__.call(this); } FinallyObservable.prototype.subscribeCore = function (o) { var d = tryCatch(this.source.subscribe).call(this.source, o); if (d === errorObj) { this._fn(); thrower(d.e); } return new FinallyDisposable(d, this._fn); }; function FinallyDisposable(s, fn) { this.isDisposed = false; this._s = s; this._fn = fn; } FinallyDisposable.prototype.dispose = function () { if (!this.isDisposed) { var res = tryCatch(this._s.dispose).call(this._s); this._fn(); res === errorObj && thrower(res.e); } }; return FinallyObservable; }(ObservableBase)); /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = function (action, thisArg) { return new FinallyObservable(this, action, thisArg); }; var IgnoreElementsObservable = (function(__super__) { inherits(IgnoreElementsObservable, __super__); function IgnoreElementsObservable(source) { this.source = source; __super__.call(this); } IgnoreElementsObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new InnerObserver(o)); }; function InnerObserver(o) { this.o = o; this.isStopped = false; } InnerObserver.prototype.onNext = noop; InnerObserver.prototype.onError = function (err) { if(!this.isStopped) { this.isStopped = true; this.o.onError(err); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.o.onCompleted(); } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; return IgnoreElementsObservable; }(ObservableBase)); /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { return new IgnoreElementsObservable(this); }; var MaterializeObservable = (function (__super__) { inherits(MaterializeObservable, __super__); function MaterializeObservable(source, fn) { this.source = source; __super__.call(this); } MaterializeObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new MaterializeObserver(o)); }; return MaterializeObservable; }(ObservableBase)); var MaterializeObserver = (function (__super__) { inherits(MaterializeObserver, __super__); function MaterializeObserver(o) { this._o = o; __super__.call(this); } MaterializeObserver.prototype.next = function (x) { this._o.onNext(notificationCreateOnNext(x)) }; MaterializeObserver.prototype.error = function (e) { this._o.onNext(notificationCreateOnError(e)); this._o.onCompleted(); }; MaterializeObserver.prototype.completed = function () { this._o.onNext(notificationCreateOnCompleted()); this._o.onCompleted(); }; return MaterializeObserver; }(AbstractObserver)); /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { return new MaterializeObservable(this); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * Note if you encounter an error and want it to retry once, then you must use .retry(2); * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(2); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchError(); }; function repeat(value) { return { '@@iterator': function () { return { next: function () { return { done: false, value: value }; } }; } }; } var RetryWhenObservable = (function(__super__) { function createDisposable(state) { return { isDisposed: false, dispose: function () { if (!this.isDisposed) { this.isDisposed = true; state.isDisposed = true; } } }; } function RetryWhenObservable(source, notifier) { this.source = source; this._notifier = notifier; __super__.call(this); } inherits(RetryWhenObservable, __super__); RetryWhenObservable.prototype.subscribeCore = function (o) { var exceptions = new Subject(), notifier = new Subject(), handled = this._notifier(exceptions), notificationDisposable = handled.subscribe(notifier); var e = this.source['@@iterator'](); var state = { isDisposed: false }, lastError, subscription = new SerialDisposable(); var cancelable = currentThreadScheduler.scheduleRecursive(null, function (_, recurse) { if (state.isDisposed) { return; } var currentItem = e.next(); if (currentItem.done) { if (lastError) { o.onError(lastError); } else { o.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var outer = new SingleAssignmentDisposable(); var inner = new SingleAssignmentDisposable(); subscription.setDisposable(new BinaryDisposable(inner, outer)); outer.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, function (exn) { inner.setDisposable(notifier.subscribe(recurse, function(ex) { o.onError(ex); }, function() { o.onCompleted(); })); exceptions.onNext(exn); outer.dispose(); }, function() { o.onCompleted(); })); }); return new NAryDisposable([notificationDisposable, subscription, cancelable, createDisposable(state)]); }; return RetryWhenObservable; }(ObservableBase)); observableProto.retryWhen = function (notifier) { return new RetryWhenObservable(repeat(this), notifier); }; function repeat(value) { return { '@@iterator': function () { return { next: function () { return { done: false, value: value }; } }; } }; } var RepeatWhenObservable = (function(__super__) { function createDisposable(state) { return { isDisposed: false, dispose: function () { if (!this.isDisposed) { this.isDisposed = true; state.isDisposed = true; } } }; } function RepeatWhenObservable(source, notifier) { this.source = source; this._notifier = notifier; __super__.call(this); } inherits(RepeatWhenObservable, __super__); RepeatWhenObservable.prototype.subscribeCore = function (o) { var completions = new Subject(), notifier = new Subject(), handled = this._notifier(completions), notificationDisposable = handled.subscribe(notifier); var e = this.source['@@iterator'](); var state = { isDisposed: false }, lastError, subscription = new SerialDisposable(); var cancelable = currentThreadScheduler.scheduleRecursive(null, function (_, recurse) { if (state.isDisposed) { return; } var currentItem = e.next(); if (currentItem.done) { if (lastError) { o.onError(lastError); } else { o.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var outer = new SingleAssignmentDisposable(); var inner = new SingleAssignmentDisposable(); subscription.setDisposable(new BinaryDisposable(inner, outer)); outer.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, function (exn) { o.onError(exn); }, function() { inner.setDisposable(notifier.subscribe(recurse, function(ex) { o.onError(ex); }, function() { o.onCompleted(); })); completions.onNext(null); outer.dispose(); })); }); return new NAryDisposable([notificationDisposable, subscription, cancelable, createDisposable(state)]); }; return RepeatWhenObservable; }(ObservableBase)); observableProto.repeatWhen = function (notifier) { return new RepeatWhenObservable(repeat(this), notifier); }; var ScanObservable = (function(__super__) { inherits(ScanObservable, __super__); function ScanObservable(source, accumulator, hasSeed, seed) { this.source = source; this.accumulator = accumulator; this.hasSeed = hasSeed; this.seed = seed; __super__.call(this); } ScanObservable.prototype.subscribeCore = function(o) { return this.source.subscribe(new ScanObserver(o,this)); }; return ScanObservable; }(ObservableBase)); var ScanObserver = (function (__super__) { inherits(ScanObserver, __super__); function ScanObserver(o, parent) { this._o = o; this._p = parent; this._fn = parent.accumulator; this._hs = parent.hasSeed; this._s = parent.seed; this._ha = false; this._a = null; this._hv = false; this._i = 0; __super__.call(this); } ScanObserver.prototype.next = function (x) { !this._hv && (this._hv = true); if (this._ha) { this._a = tryCatch(this._fn)(this._a, x, this._i, this._p); } else { this._a = this._hs ? tryCatch(this._fn)(this._s, x, this._i, this._p) : x; this._ha = true; } if (this._a === errorObj) { return this._o.onError(this._a.e); } this._o.onNext(this._a); this._i++; }; ScanObserver.prototype.error = function (e) { this._o.onError(e); }; ScanObserver.prototype.completed = function () { !this._hv && this._hs && this._o.onNext(this._s); this._o.onCompleted(); }; return ScanObserver; }(AbstractObserver)); /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator = arguments[0]; if (arguments.length === 2) { hasSeed = true; seed = arguments[1]; } return new ScanObservable(this, accumulator, hasSeed, seed); }; var SkipLastObservable = (function (__super__) { inherits(SkipLastObservable, __super__); function SkipLastObservable(source, c) { this.source = source; this._c = c; __super__.call(this); } SkipLastObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new SkipLastObserver(o, this._c)); }; return SkipLastObservable; }(ObservableBase)); var SkipLastObserver = (function (__super__) { inherits(SkipLastObserver, __super__); function SkipLastObserver(o, c) { this._o = o; this._c = c; this._q = []; __super__.call(this); } SkipLastObserver.prototype.next = function (x) { this._q.push(x); this._q.length > this._c && this._o.onNext(this._q.shift()); }; SkipLastObserver.prototype.error = function (e) { this._o.onError(e); }; SkipLastObserver.prototype.completed = function () { this._o.onCompleted(); }; return SkipLastObserver; }(AbstractObserver)); /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } return new SkipLastObservable(this, count); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * @example * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * @param {Arguments} args The specified values to prepend to the observable sequence * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && isScheduler(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); } return observableConcat.apply(null, [observableFromArray(args, scheduler), this]); }; var TakeLastObserver = (function (__super__) { inherits(TakeLastObserver, __super__); function TakeLastObserver(o, c) { this._o = o; this._c = c; this._q = []; __super__.call(this); } TakeLastObserver.prototype.next = function (x) { this._q.push(x); this._q.length > this._c && this._q.shift(); }; TakeLastObserver.prototype.error = function (e) { this._o.onError(e); }; TakeLastObserver.prototype.completed = function () { while (this._q.length > 0) { this._o.onNext(this._q.shift()); } this._o.onCompleted(); }; return TakeLastObserver; }(AbstractObserver)); /** * Returns a specified number of contiguous elements from the end of an observable sequence. * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { return source.subscribe(new TakeLastObserver(o, count)); }, source); }; observableProto.flatMapConcat = observableProto.concatMap = function(selector, resultSelector, thisArg) { return new FlatMapObservable(this, selector, resultSelector, thisArg).merge(1); }; var MapObservable = (function (__super__) { inherits(MapObservable, __super__); function MapObservable(source, selector, thisArg) { this.source = source; this.selector = bindCallback(selector, thisArg, 3); __super__.call(this); } function innerMap(selector, self) { return function (x, i, o) { return selector.call(this, self.selector(x, i, o), i, o); }; } MapObservable.prototype.internalMap = function (selector, thisArg) { return new MapObservable(this.source, innerMap(selector, this), thisArg); }; MapObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new InnerObserver(o, this.selector, this)); }; inherits(InnerObserver, AbstractObserver); function InnerObserver(o, selector, source) { this.o = o; this.selector = selector; this.source = source; this.i = 0; AbstractObserver.call(this); } InnerObserver.prototype.next = function(x) { var result = tryCatch(this.selector)(x, this.i++, this.source); if (result === errorObj) { return this.o.onError(result.e); } this.o.onNext(result); }; InnerObserver.prototype.error = function (e) { this.o.onError(e); }; InnerObserver.prototype.completed = function () { this.o.onCompleted(); }; return MapObservable; }(ObservableBase)); /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.map = observableProto.select = function (selector, thisArg) { var selectorFn = typeof selector === 'function' ? selector : function () { return selector; }; return this instanceof MapObservable ? this.internalMap(selectorFn, thisArg) : new MapObservable(this, selectorFn, thisArg); }; function plucker(args, len) { return function mapper(x) { var currentProp = x; for (var i = 0; i < len; i++) { var p = currentProp[args[i]]; if (typeof p !== 'undefined') { currentProp = p; } else { return undefined; } } return currentProp; }; } /** * Retrieves the value of a specified nested property from all elements in * the Observable sequence. * @param {Arguments} arguments The nested properties to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function () { var len = arguments.length, args = new Array(len); if (len === 0) { throw new Error('List of properties cannot be empty.'); } for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return this.map(plucker(args, len)); }; observableProto.flatMap = observableProto.selectMany = observableProto.mergeMap = function(selector, resultSelector, thisArg) { return new FlatMapObservable(this, selector, resultSelector, thisArg).mergeAll(); }; observableProto.flatMapLatest = observableProto.switchMap = function(selector, resultSelector, thisArg) { return new FlatMapObservable(this, selector, resultSelector, thisArg).switchLatest(); }; var SkipObservable = (function(__super__) { inherits(SkipObservable, __super__); function SkipObservable(source, count) { this.source = source; this._count = count; __super__.call(this); } SkipObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new SkipObserver(o, this._count)); }; function SkipObserver(o, c) { this._o = o; this._r = c; AbstractObserver.call(this); } inherits(SkipObserver, AbstractObserver); SkipObserver.prototype.next = function (x) { if (this._r <= 0) { this._o.onNext(x); } else { this._r--; } }; SkipObserver.prototype.error = function(e) { this._o.onError(e); }; SkipObserver.prototype.completed = function() { this._o.onCompleted(); }; return SkipObservable; }(ObservableBase)); /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } return new SkipObservable(this, count); }; var SkipWhileObservable = (function (__super__) { inherits(SkipWhileObservable, __super__); function SkipWhileObservable(source, fn) { this.source = source; this._fn = fn; __super__.call(this); } SkipWhileObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new SkipWhileObserver(o, this)); }; return SkipWhileObservable; }(ObservableBase)); var SkipWhileObserver = (function (__super__) { inherits(SkipWhileObserver, __super__); function SkipWhileObserver(o, p) { this._o = o; this._p = p; this._i = 0; this._r = false; __super__.call(this); } SkipWhileObserver.prototype.next = function (x) { if (!this._r) { var res = tryCatch(this._p._fn)(x, this._i++, this._p); if (res === errorObj) { return this._o.onError(res.e); } this._r = !res; } this._r && this._o.onNext(x); }; SkipWhileObserver.prototype.error = function (e) { this._o.onError(e); }; SkipWhileObserver.prototype.completed = function () { this._o.onCompleted(); }; return SkipWhileObserver; }(AbstractObserver)); /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var fn = bindCallback(predicate, thisArg, 3); return new SkipWhileObservable(this, fn); }; var TakeObservable = (function(__super__) { inherits(TakeObservable, __super__); function TakeObservable(source, count) { this.source = source; this._count = count; __super__.call(this); } TakeObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new TakeObserver(o, this._count)); }; function TakeObserver(o, c) { this._o = o; this._c = c; this._r = c; AbstractObserver.call(this); } inherits(TakeObserver, AbstractObserver); TakeObserver.prototype.next = function (x) { if (this._r-- > 0) { this._o.onNext(x); this._r <= 0 && this._o.onCompleted(); } }; TakeObserver.prototype.error = function (e) { this._o.onError(e); }; TakeObserver.prototype.completed = function () { this._o.onCompleted(); }; return TakeObservable; }(ObservableBase)); /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new ArgumentOutOfRangeError(); } if (count === 0) { return observableEmpty(scheduler); } return new TakeObservable(this, count); }; var TakeWhileObservable = (function (__super__) { inherits(TakeWhileObservable, __super__); function TakeWhileObservable(source, fn) { this.source = source; this._fn = fn; __super__.call(this); } TakeWhileObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new TakeWhileObserver(o, this)); }; return TakeWhileObservable; }(ObservableBase)); var TakeWhileObserver = (function (__super__) { inherits(TakeWhileObserver, __super__); function TakeWhileObserver(o, p) { this._o = o; this._p = p; this._i = 0; this._r = true; __super__.call(this); } TakeWhileObserver.prototype.next = function (x) { if (this._r) { this._r = tryCatch(this._p._fn)(x, this._i++, this._p); if (this._r === errorObj) { return this._o.onError(this._r.e); } } if (this._r) { this._o.onNext(x); } else { this._o.onCompleted(); } }; TakeWhileObserver.prototype.error = function (e) { this._o.onError(e); }; TakeWhileObserver.prototype.completed = function () { this._o.onCompleted(); }; return TakeWhileObserver; }(AbstractObserver)); /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var fn = bindCallback(predicate, thisArg, 3); return new TakeWhileObservable(this, fn); }; var FilterObservable = (function (__super__) { inherits(FilterObservable, __super__); function FilterObservable(source, predicate, thisArg) { this.source = source; this.predicate = bindCallback(predicate, thisArg, 3); __super__.call(this); } FilterObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new InnerObserver(o, this.predicate, this)); }; function innerPredicate(predicate, self) { return function(x, i, o) { return self.predicate(x, i, o) && predicate.call(this, x, i, o); } } FilterObservable.prototype.internalFilter = function(predicate, thisArg) { return new FilterObservable(this.source, innerPredicate(predicate, this), thisArg); }; inherits(InnerObserver, AbstractObserver); function InnerObserver(o, predicate, source) { this.o = o; this.predicate = predicate; this.source = source; this.i = 0; AbstractObserver.call(this); } InnerObserver.prototype.next = function(x) { var shouldYield = tryCatch(this.predicate)(x, this.i++, this.source); if (shouldYield === errorObj) { return this.o.onError(shouldYield.e); } shouldYield && this.o.onNext(x); }; InnerObserver.prototype.error = function (e) { this.o.onError(e); }; InnerObserver.prototype.completed = function () { this.o.onCompleted(); }; return FilterObservable; }(ObservableBase)); /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.filter = observableProto.where = function (predicate, thisArg) { return this instanceof FilterObservable ? this.internalFilter(predicate, thisArg) : new FilterObservable(this, predicate, thisArg); }; function createCbObservable(fn, ctx, selector, args) { var o = new AsyncSubject(); args.push(createCbHandler(o, ctx, selector)); fn.apply(ctx, args); return o.asObservable(); } function createCbHandler(o, ctx, selector) { return function handler () { var len = arguments.length, results = new Array(len); for(var i = 0; i < len; i++) { results[i] = arguments[i]; } if (isFunction(selector)) { results = tryCatch(selector).apply(ctx, results); if (results === errorObj) { return o.onError(results.e); } o.onNext(results); } else { if (results.length <= 1) { o.onNext(results[0]); } else { o.onNext(results); } } o.onCompleted(); }; } /** * Converts a callback function to an observable sequence. * * @param {Function} fn Function with a callback as the last parameter to convert to an Observable sequence. * @param {Mixed} [ctx] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. */ Observable.fromCallback = function (fn, ctx, selector) { return function () { typeof ctx === 'undefined' && (ctx = this); var len = arguments.length, args = new Array(len) for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return createCbObservable(fn, ctx, selector, args); }; }; function createNodeObservable(fn, ctx, selector, args) { var o = new AsyncSubject(); args.push(createNodeHandler(o, ctx, selector)); fn.apply(ctx, args); return o.asObservable(); } function createNodeHandler(o, ctx, selector) { return function handler () { var err = arguments[0]; if (err) { return o.onError(err); } var len = arguments.length, results = []; for(var i = 1; i < len; i++) { results[i - 1] = arguments[i]; } if (isFunction(selector)) { var results = tryCatch(selector).apply(ctx, results); if (results === errorObj) { return o.onError(results.e); } o.onNext(results); } else { if (results.length <= 1) { o.onNext(results[0]); } else { o.onNext(results); } } o.onCompleted(); }; } /** * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. * @param {Function} fn The function to call * @param {Mixed} [ctx] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. */ Observable.fromNodeCallback = function (fn, ctx, selector) { return function () { typeof ctx === 'undefined' && (ctx = this); var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return createNodeObservable(fn, ctx, selector, args); }; }; function isNodeList(el) { if (root.StaticNodeList) { // IE8 Specific // instanceof is slower than Object#toString, but Object#toString will not work as intended in IE8 return el instanceof root.StaticNodeList || el instanceof root.NodeList; } else { return Object.prototype.toString.call(el) === '[object NodeList]'; } } function ListenDisposable(e, n, fn) { this._e = e; this._n = n; this._fn = fn; this._e.addEventListener(this._n, this._fn, false); this.isDisposed = false; } ListenDisposable.prototype.dispose = function () { if (!this.isDisposed) { this._e.removeEventListener(this._n, this._fn, false); this.isDisposed = true; } }; function createEventListener (el, eventName, handler) { var disposables = new CompositeDisposable(); // Asume NodeList or HTMLCollection var elemToString = Object.prototype.toString.call(el); if (isNodeList(el) || elemToString === '[object HTMLCollection]') { for (var i = 0, len = el.length; i < len; i++) { disposables.add(createEventListener(el.item(i), eventName, handler)); } } else if (el) { disposables.add(new ListenDisposable(el, eventName, handler)); } return disposables; } /** * Configuration option to determine whether to use native events only */ Rx.config.useNativeEvents = false; var EventObservable = (function(__super__) { inherits(EventObservable, __super__); function EventObservable(el, name, fn) { this._el = el; this._n = name; this._fn = fn; __super__.call(this); } function createHandler(o, fn) { return function handler () { var results = arguments[0]; if (isFunction(fn)) { results = tryCatch(fn).apply(null, arguments); if (results === errorObj) { return o.onError(results.e); } } o.onNext(results); }; } EventObservable.prototype.subscribeCore = function (o) { return createEventListener( this._el, this._n, createHandler(o, this._fn)); }; return EventObservable; }(ObservableBase)); /** * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. * @param {Object} element The DOMElement or NodeList to attach a listener. * @param {String} eventName The event name to attach the observable sequence. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence of events from the specified element and the specified event. */ Observable.fromEvent = function (element, eventName, selector) { // Node.js specific if (element.addListener) { return fromEventPattern( function (h) { element.addListener(eventName, h); }, function (h) { element.removeListener(eventName, h); }, selector); } // Use only if non-native events are allowed if (!Rx.config.useNativeEvents) { // Handles jq, Angular.js, Zepto, Marionette, Ember.js if (typeof element.on === 'function' && typeof element.off === 'function') { return fromEventPattern( function (h) { element.on(eventName, h); }, function (h) { element.off(eventName, h); }, selector); } } return new EventObservable(element, eventName, selector).publish().refCount(); }; var EventPatternObservable = (function(__super__) { inherits(EventPatternObservable, __super__); function EventPatternObservable(add, del, fn) { this._add = add; this._del = del; this._fn = fn; __super__.call(this); } function createHandler(o, fn) { return function handler () { var results = arguments[0]; if (isFunction(fn)) { results = tryCatch(fn).apply(null, arguments); if (results === errorObj) { return o.onError(results.e); } } o.onNext(results); }; } EventPatternObservable.prototype.subscribeCore = function (o) { var fn = createHandler(o, this._fn); var returnValue = this._add(fn); return new EventPatternDisposable(this._del, fn, returnValue); }; function EventPatternDisposable(del, fn, ret) { this._del = del; this._fn = fn; this._ret = ret; this.isDisposed = false; } EventPatternDisposable.prototype.dispose = function () { if(!this.isDisposed) { isFunction(this._del) && this._del(this._fn, this._ret); this.isDisposed = true; } }; return EventPatternObservable; }(ObservableBase)); /** * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. * @param {Function} addHandler The function to add a handler to the emitter. * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence which wraps an event from an event emitter */ var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) { return new EventPatternObservable(addHandler, removeHandler, selector).publish().refCount(); }; var FromPromiseObservable = (function(__super__) { inherits(FromPromiseObservable, __super__); function FromPromiseObservable(p, s) { this._p = p; this._s = s; __super__.call(this); } function scheduleNext(s, state) { var o = state[0], data = state[1]; o.onNext(data); o.onCompleted(); } function scheduleError(s, state) { var o = state[0], err = state[1]; o.onError(err); } FromPromiseObservable.prototype.subscribeCore = function(o) { var sad = new SingleAssignmentDisposable(), self = this, p = this._p; if (isFunction(p)) { p = tryCatch(p)(); if (p === errorObj) { o.onError(p.e); return sad; } } p .then(function (data) { sad.setDisposable(self._s.schedule([o, data], scheduleNext)); }, function (err) { sad.setDisposable(self._s.schedule([o, err], scheduleError)); }); return sad; }; return FromPromiseObservable; }(ObservableBase)); /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise, scheduler) { scheduler || (scheduler = defaultScheduler); return new FromPromiseObservable(promise, scheduler); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new NotSupportedError('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value; source.subscribe(function (v) { value = v; }, reject, function () { resolve(value); }); }); }; /** * Invokes the asynchronous function, surfacing the result through an observable sequence. * @param {Function} functionAsync Asynchronous function which returns a Promise to run. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. */ Observable.startAsync = function (functionAsync) { var promise = tryCatch(functionAsync)(); if (promise === errorObj) { return observableThrow(promise.e); } return observableFromPromise(promise); }; var MulticastObservable = (function (__super__) { inherits(MulticastObservable, __super__); function MulticastObservable(source, fn1, fn2) { this.source = source; this._fn1 = fn1; this._fn2 = fn2; __super__.call(this); } MulticastObservable.prototype.subscribeCore = function (o) { var connectable = this.source.multicast(this._fn1()); return new BinaryDisposable(this._fn2(connectable).subscribe(o), connectable.connect()); }; return MulticastObservable; }(ObservableBase)); /** * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. * * @example * 1 - res = source.multicast(observable); * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); * * @param {Function|Subject} subjectOrSubjectSelector * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. * Or: * Subject to push source elements into. * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.multicast = function (subjectOrSubjectSelector, selector) { return isFunction(subjectOrSubjectSelector) ? new MulticastObservable(this, subjectOrSubjectSelector, selector) : new ConnectableObservable(this, subjectOrSubjectSelector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of Multicast using a regular Subject. * * @example * var resres = source.publish(); * var res = source.publish(function (x) { return x; }); * * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publish = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new Subject(); }, selector) : this.multicast(new Subject()); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.share = function () { return this.publish().refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification. * This operator is a specialization of Multicast using a AsyncSubject. * * @example * var res = source.publishLast(); * var res = source.publishLast(function (x) { return x; }); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishLast = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new AsyncSubject(); }, selector) : this.multicast(new AsyncSubject()); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue. * This operator is a specialization of Multicast using a BehaviorSubject. * * @example * var res = source.publishValue(42); * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42); * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishValue = function (initialValueOrSelector, initialValue) { return arguments.length === 2 ? this.multicast(function () { return new BehaviorSubject(initialValue); }, initialValueOrSelector) : this.multicast(new BehaviorSubject(initialValueOrSelector)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareValue = function (initialValue) { return this.publishValue(initialValue).refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of Multicast using a ReplaySubject. * * @example * var res = source.replay(null, 3); * var res = source.replay(null, 3, 500); * var res = source.replay(null, 3, 500, scheduler); * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy. * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param windowSize [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.replay = function (selector, bufferSize, windowSize, scheduler) { return selector && isFunction(selector) ? this.multicast(function () { return new ReplaySubject(bufferSize, windowSize, scheduler); }, selector) : this.multicast(new ReplaySubject(bufferSize, windowSize, scheduler)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareReplay(3); * var res = source.shareReplay(3, 500); * var res = source.shareReplay(3, 500, scheduler); * * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareReplay = function (bufferSize, windowSize, scheduler) { return this.replay(null, bufferSize, windowSize, scheduler).refCount(); }; var RefCountObservable = (function (__super__) { inherits(RefCountObservable, __super__); function RefCountObservable(source) { this.source = source; this._count = 0; this._connectableSubscription = null; __super__.call(this); } RefCountObservable.prototype.subscribeCore = function (o) { var subscription = this.source.subscribe(o); ++this._count === 1 && (this._connectableSubscription = this.source.connect()); return new RefCountDisposable(this, subscription); }; function RefCountDisposable(p, s) { this._p = p; this._s = s; this.isDisposed = false; } RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; this._s.dispose(); --this._p._count === 0 && this._p._connectableSubscription.dispose(); } }; return RefCountObservable; }(ObservableBase)); var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { inherits(ConnectableObservable, __super__); function ConnectableObservable(source, subject) { this.source = source; this._connection = null; this._source = source.asObservable(); this._subject = subject; __super__.call(this); } function ConnectDisposable(parent, subscription) { this._p = parent; this._s = subscription; } ConnectDisposable.prototype.dispose = function () { if (this._s) { this._s.dispose(); this._s = null; this._p._connection = null; } }; ConnectableObservable.prototype.connect = function () { if (!this._connection) { if (this._subject.isStopped) { return disposableEmpty; } var subscription = this._source.subscribe(this._subject); this._connection = new ConnectDisposable(this, subscription); } return this._connection; }; ConnectableObservable.prototype._subscribe = function (o) { return this._subject.subscribe(o); }; ConnectableObservable.prototype.refCount = function () { return new RefCountObservable(this); }; return ConnectableObservable; }(Observable)); var TimerObservable = (function(__super__) { inherits(TimerObservable, __super__); function TimerObservable(dt, s) { this._dt = dt; this._s = s; __super__.call(this); } TimerObservable.prototype.subscribeCore = function (o) { return this._s.scheduleFuture(o, this._dt, scheduleMethod); }; function scheduleMethod(s, o) { o.onNext(0); o.onCompleted(); } return TimerObservable; }(ObservableBase)); function _observableTimer(dueTime, scheduler) { return new TimerObservable(dueTime, scheduler); } function observableTimerDateAndPeriod(dueTime, period, scheduler) { return new AnonymousObservable(function (observer) { var d = dueTime, p = normalizeTime(period); return scheduler.scheduleRecursiveFuture(0, d, function (count, self) { if (p > 0) { var now = scheduler.now(); d = new Date(d.getTime() + p); d.getTime() <= now && (d = new Date(now + p)); } observer.onNext(count); self(count + 1, new Date(d)); }); }); } function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { return dueTime === period ? new AnonymousObservable(function (observer) { return scheduler.schedulePeriodic(0, period, function (count) { observer.onNext(count); return count + 1; }); }) : observableDefer(function () { return observableTimerDateAndPeriod(new Date(scheduler.now() + dueTime), period, scheduler); }); } /** * Returns an observable sequence that produces a value after each period. * * @example * 1 - res = Rx.Observable.interval(1000); * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); * * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. * @returns {Observable} An observable sequence that produces a value after each period. */ var observableinterval = Observable.interval = function (period, scheduler) { return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : defaultScheduler); }; /** * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. */ var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { var period; isScheduler(scheduler) || (scheduler = defaultScheduler); if (periodOrScheduler != null && typeof periodOrScheduler === 'number') { period = periodOrScheduler; } else if (isScheduler(periodOrScheduler)) { scheduler = periodOrScheduler; } if ((dueTime instanceof Date || typeof dueTime === 'number') && period === undefined) { return _observableTimer(dueTime, scheduler); } if (dueTime instanceof Date && period !== undefined) { return observableTimerDateAndPeriod(dueTime, periodOrScheduler, scheduler); } return observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); }; function observableDelayRelative(source, dueTime, scheduler) { return new AnonymousObservable(function (o) { var active = false, cancelable = new SerialDisposable(), exception = null, q = [], running = false, subscription; subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { var d, shouldRun; if (notification.value.kind === 'E') { q = []; q.push(notification); exception = notification.value.error; shouldRun = !running; } else { q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); shouldRun = !active; active = true; } if (shouldRun) { if (exception !== null) { o.onError(exception); } else { d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleRecursiveFuture(null, dueTime, function (_, self) { var e, recurseDueTime, result, shouldRecurse; if (exception !== null) { return; } running = true; do { result = null; if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { result = q.shift().value; } if (result !== null) { result.accept(o); } } while (result !== null); shouldRecurse = false; recurseDueTime = 0; if (q.length > 0) { shouldRecurse = true; recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); } else { active = false; } e = exception; running = false; if (e !== null) { o.onError(e); } else if (shouldRecurse) { self(null, recurseDueTime); } })); } } }); return new BinaryDisposable(subscription, cancelable); }, source); } function observableDelayAbsolute(source, dueTime, scheduler) { return observableDefer(function () { return observableDelayRelative(source, dueTime - scheduler.now(), scheduler); }); } function delayWithSelector(source, subscriptionDelay, delayDurationSelector) { var subDelay, selector; if (isFunction(subscriptionDelay)) { selector = subscriptionDelay; } else { subDelay = subscriptionDelay; selector = delayDurationSelector; } return new AnonymousObservable(function (o) { var delays = new CompositeDisposable(), atEnd = false, subscription = new SerialDisposable(); function start() { subscription.setDisposable(source.subscribe( function (x) { var delay = tryCatch(selector)(x); if (delay === errorObj) { return o.onError(delay.e); } var d = new SingleAssignmentDisposable(); delays.add(d); d.setDisposable(delay.subscribe( function () { o.onNext(x); delays.remove(d); done(); }, function (e) { o.onError(e); }, function () { o.onNext(x); delays.remove(d); done(); } )); }, function (e) { o.onError(e); }, function () { atEnd = true; subscription.dispose(); done(); } )); } function done () { atEnd && delays.length === 0 && o.onCompleted(); } if (!subDelay) { start(); } else { subscription.setDisposable(subDelay.subscribe(start, function (e) { o.onError(e); }, start)); } return new BinaryDisposable(subscription, delays); }, source); } /** * Time shifts the observable sequence by dueTime. * The relative time intervals between the values are preserved. * * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delay = function () { var firstArg = arguments[0]; if (typeof firstArg === 'number' || firstArg instanceof Date) { var dueTime = firstArg, scheduler = arguments[1]; isScheduler(scheduler) || (scheduler = defaultScheduler); return dueTime instanceof Date ? observableDelayAbsolute(this, dueTime, scheduler) : observableDelayRelative(this, dueTime, scheduler); } else if (Observable.isObservable(firstArg) || isFunction(firstArg)) { return delayWithSelector(this, firstArg, arguments[1]); } else { throw new Error('Invalid arguments'); } }; var DebounceObservable = (function (__super__) { inherits(DebounceObservable, __super__); function DebounceObservable(source, dt, s) { isScheduler(s) || (s = defaultScheduler); this.source = source; this._dt = dt; this._s = s; __super__.call(this); } DebounceObservable.prototype.subscribeCore = function (o) { var cancelable = new SerialDisposable(); return new BinaryDisposable( this.source.subscribe(new DebounceObserver(o, this._dt, this._s, cancelable)), cancelable); }; return DebounceObservable; }(ObservableBase)); var DebounceObserver = (function (__super__) { inherits(DebounceObserver, __super__); function DebounceObserver(observer, dueTime, scheduler, cancelable) { this._o = observer; this._d = dueTime; this._scheduler = scheduler; this._c = cancelable; this._v = null; this._hv = false; this._id = 0; __super__.call(this); } function scheduleFuture(s, state) { state.self._hv && state.self._id === state.currentId && state.self._o.onNext(state.x); state.self._hv = false; } DebounceObserver.prototype.next = function (x) { this._hv = true; this._v = x; var currentId = ++this._id, d = new SingleAssignmentDisposable(); this._c.setDisposable(d); d.setDisposable(this._scheduler.scheduleFuture(this, this._d, function (_, self) { self._hv && self._id === currentId && self._o.onNext(x); self._hv = false; })); }; DebounceObserver.prototype.error = function (e) { this._c.dispose(); this._o.onError(e); this._hv = false; this._id++; }; DebounceObserver.prototype.completed = function () { this._c.dispose(); this._hv && this._o.onNext(this._v); this._o.onCompleted(); this._hv = false; this._id++; }; return DebounceObserver; }(AbstractObserver)); function debounceWithSelector(source, durationSelector) { return new AnonymousObservable(function (o) { var value, hasValue = false, cancelable = new SerialDisposable(), id = 0; var subscription = source.subscribe( function (x) { var throttle = tryCatch(durationSelector)(x); if (throttle === errorObj) { return o.onError(throttle.e); } isPromise(throttle) && (throttle = observableFromPromise(throttle)); hasValue = true; value = x; id++; var currentid = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(throttle.subscribe( function () { hasValue && id === currentid && o.onNext(value); hasValue = false; d.dispose(); }, function (e) { o.onError(e); }, function () { hasValue && id === currentid && o.onNext(value); hasValue = false; d.dispose(); } )); }, function (e) { cancelable.dispose(); o.onError(e); hasValue = false; id++; }, function () { cancelable.dispose(); hasValue && o.onNext(value); o.onCompleted(); hasValue = false; id++; } ); return new BinaryDisposable(subscription, cancelable); }, source); } observableProto.debounce = function () { if (isFunction (arguments[0])) { return debounceWithSelector(this, arguments[0]); } else if (typeof arguments[0] === 'number') { return new DebounceObservable(this, arguments[0], arguments[1]); } else { throw new Error('Invalid arguments'); } }; var TimestampObservable = (function (__super__) { inherits(TimestampObservable, __super__); function TimestampObservable(source, s) { this.source = source; this._s = s; __super__.call(this); } TimestampObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new TimestampObserver(o, this._s)); }; return TimestampObservable; }(ObservableBase)); var TimestampObserver = (function (__super__) { inherits(TimestampObserver, __super__); function TimestampObserver(o, s) { this._o = o; this._s = s; __super__.call(this); } TimestampObserver.prototype.next = function (x) { this._o.onNext({ value: x, timestamp: this._s.now() }); }; TimestampObserver.prototype.error = function (e) { this._o.onError(e); }; TimestampObserver.prototype.completed = function () { this._o.onCompleted(); }; return TimestampObserver; }(AbstractObserver)); /** * Records the timestamp for each value in an observable sequence. * * @example * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } * 2 - res = source.timestamp(Rx.Scheduler.default); * * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the default scheduler is used. * @returns {Observable} An observable sequence with timestamp information on values. */ observableProto.timestamp = function (scheduler) { isScheduler(scheduler) || (scheduler = defaultScheduler); return new TimestampObservable(this, scheduler); }; var SampleObservable = (function(__super__) { inherits(SampleObservable, __super__); function SampleObservable(source, sampler) { this.source = source; this._sampler = sampler; __super__.call(this); } SampleObservable.prototype.subscribeCore = function (o) { var state = { o: o, atEnd: false, value: null, hasValue: false, sourceSubscription: new SingleAssignmentDisposable() }; state.sourceSubscription.setDisposable(this.source.subscribe(new SampleSourceObserver(state))); return new BinaryDisposable( state.sourceSubscription, this._sampler.subscribe(new SamplerObserver(state)) ); }; return SampleObservable; }(ObservableBase)); var SamplerObserver = (function(__super__) { inherits(SamplerObserver, __super__); function SamplerObserver(s) { this._s = s; __super__.call(this); } SamplerObserver.prototype._handleMessage = function () { if (this._s.hasValue) { this._s.hasValue = false; this._s.o.onNext(this._s.value); } this._s.atEnd && this._s.o.onCompleted(); }; SamplerObserver.prototype.next = function () { this._handleMessage(); }; SamplerObserver.prototype.error = function (e) { this._s.onError(e); }; SamplerObserver.prototype.completed = function () { this._handleMessage(); }; return SamplerObserver; }(AbstractObserver)); var SampleSourceObserver = (function(__super__) { inherits(SampleSourceObserver, __super__); function SampleSourceObserver(s) { this._s = s; __super__.call(this); } SampleSourceObserver.prototype.next = function (x) { this._s.hasValue = true; this._s.value = x; }; SampleSourceObserver.prototype.error = function (e) { this._s.o.onError(e); }; SampleSourceObserver.prototype.completed = function () { this._s.atEnd = true; this._s.sourceSubscription.dispose(); }; return SampleSourceObserver; }(AbstractObserver)); /** * Samples the observable sequence at each interval. * * @example * 1 - res = source.sample(sampleObservable); // Sampler tick sequence * 2 - res = source.sample(5000); // 5 seconds * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Sampled observable sequence. */ observableProto.sample = function (intervalOrSampler, scheduler) { isScheduler(scheduler) || (scheduler = defaultScheduler); return typeof intervalOrSampler === 'number' ? new SampleObservable(this, observableinterval(intervalOrSampler, scheduler)) : new SampleObservable(this, intervalOrSampler); }; var TimeoutError = Rx.TimeoutError = function(message) { this.message = message || 'Timeout has occurred'; this.name = 'TimeoutError'; Error.call(this); }; TimeoutError.prototype = Object.create(Error.prototype); function timeoutWithSelector(source, firstTimeout, timeoutDurationSelector, other) { if (isFunction(firstTimeout)) { other = timeoutDurationSelector; timeoutDurationSelector = firstTimeout; firstTimeout = observableNever(); } Observable.isObservable(other) || (other = observableThrow(new TimeoutError())); return new AnonymousObservable(function (o) { var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); subscription.setDisposable(original); var id = 0, switched = false; function setTimer(timeout) { var myId = id, d = new SingleAssignmentDisposable(); function timerWins() { switched = (myId === id); return switched; } timer.setDisposable(d); d.setDisposable(timeout.subscribe(function () { timerWins() && subscription.setDisposable(other.subscribe(o)); d.dispose(); }, function (e) { timerWins() && o.onError(e); }, function () { timerWins() && subscription.setDisposable(other.subscribe(o)); })); }; setTimer(firstTimeout); function oWins() { var res = !switched; if (res) { id++; } return res; } original.setDisposable(source.subscribe(function (x) { if (oWins()) { o.onNext(x); var timeout = tryCatch(timeoutDurationSelector)(x); if (timeout === errorObj) { return o.onError(timeout.e); } setTimer(isPromise(timeout) ? observableFromPromise(timeout) : timeout); } }, function (e) { oWins() && o.onError(e); }, function () { oWins() && o.onCompleted(); })); return new BinaryDisposable(subscription, timer); }, source); } function timeout(source, dueTime, other, scheduler) { if (isScheduler(other)) { scheduler = other; other = observableThrow(new TimeoutError()); } if (other instanceof Error) { other = observableThrow(other); } isScheduler(scheduler) || (scheduler = defaultScheduler); Observable.isObservable(other) || (other = observableThrow(new TimeoutError())); return new AnonymousObservable(function (o) { var id = 0, original = new SingleAssignmentDisposable(), subscription = new SerialDisposable(), switched = false, timer = new SerialDisposable(); subscription.setDisposable(original); function createTimer() { var myId = id; timer.setDisposable(scheduler.scheduleFuture(null, dueTime, function () { switched = id === myId; if (switched) { isPromise(other) && (other = observableFromPromise(other)); subscription.setDisposable(other.subscribe(o)); } })); } createTimer(); original.setDisposable(source.subscribe(function (x) { if (!switched) { id++; o.onNext(x); createTimer(); } }, function (e) { if (!switched) { id++; o.onError(e); } }, function () { if (!switched) { id++; o.onCompleted(); } })); return new BinaryDisposable(subscription, timer); }, source); } observableProto.timeout = function () { var firstArg = arguments[0]; if (firstArg instanceof Date || typeof firstArg === 'number') { return timeout(this, firstArg, arguments[1], arguments[2]); } else if (Observable.isObservable(firstArg) || isFunction(firstArg)) { return timeoutWithSelector(this, firstArg, arguments[1], arguments[2]); } else { throw new Error('Invalid arguments'); } }; /** * Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration. * @param {Number} windowDuration time to wait before emitting another item after emitting the last item * @param {Scheduler} [scheduler] the Scheduler to use internally to manage the timers that handle timeout for each item. If not provided, defaults to Scheduler.timeout. * @returns {Observable} An Observable that performs the throttle operation. */ observableProto.throttle = function (windowDuration, scheduler) { isScheduler(scheduler) || (scheduler = defaultScheduler); var duration = +windowDuration || 0; if (duration <= 0) { throw new RangeError('windowDuration cannot be less or equal zero.'); } var source = this; return new AnonymousObservable(function (o) { var lastOnNext = 0; return source.subscribe( function (x) { var now = scheduler.now(); if (lastOnNext === 0 || now - lastOnNext >= duration) { lastOnNext = now; o.onNext(x); } },function (e) { o.onError(e); }, function () { o.onCompleted(); } ); }, source); }; var PausableObservable = (function (__super__) { inherits(PausableObservable, __super__); function PausableObservable(source, pauser) { this.source = source; this.controller = new Subject(); this.paused = true; if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } __super__.call(this); } PausableObservable.prototype._subscribe = function (o) { var conn = this.source.publish(), subscription = conn.subscribe(o), connection = disposableEmpty; var pausable = this.pauser.startWith(!this.paused).distinctUntilChanged().subscribe(function (b) { if (b) { connection = conn.connect(); } else { connection.dispose(); connection = disposableEmpty; } }); return new NAryDisposable([subscription, connection, pausable]); }; PausableObservable.prototype.pause = function () { this.paused = true; this.controller.onNext(false); }; PausableObservable.prototype.resume = function () { this.paused = false; this.controller.onNext(true); }; return PausableObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausable(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausable = function (pauser) { return new PausableObservable(this, pauser); }; function combineLatestSource(source, subject, resultSelector) { return new AnonymousObservable(function (o) { var hasValue = [false, false], hasValueAll = false, isDone = false, values = new Array(2), err; function next(x, i) { values[i] = x; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { if (err) { return o.onError(err); } var res = tryCatch(resultSelector).apply(null, values); if (res === errorObj) { return o.onError(res.e); } o.onNext(res); } isDone && values[1] && o.onCompleted(); } return new BinaryDisposable( source.subscribe( function (x) { next(x, 0); }, function (e) { if (values[1]) { o.onError(e); } else { err = e; } }, function () { isDone = true; values[1] && o.onCompleted(); }), subject.subscribe( function (x) { next(x, 1); }, function (e) { o.onError(e); }, function () { isDone = true; next(true, 1); }) ); }, source); } var PausableBufferedObservable = (function (__super__) { inherits(PausableBufferedObservable, __super__); function PausableBufferedObservable(source, pauser) { this.source = source; this.controller = new Subject(); this.paused = true; if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } __super__.call(this); } PausableBufferedObservable.prototype._subscribe = function (o) { var q = [], previousShouldFire; function drainQueue() { while (q.length > 0) { o.onNext(q.shift()); } } var subscription = combineLatestSource( this.source, this.pauser.startWith(!this.paused).distinctUntilChanged(), function (data, shouldFire) { return { data: data, shouldFire: shouldFire }; }) .subscribe( function (results) { if (previousShouldFire !== undefined && results.shouldFire !== previousShouldFire) { previousShouldFire = results.shouldFire; // change in shouldFire if (results.shouldFire) { drainQueue(); } } else { previousShouldFire = results.shouldFire; // new data if (results.shouldFire) { o.onNext(results.data); } else { q.push(results.data); } } }, function (err) { drainQueue(); o.onError(err); }, function () { drainQueue(); o.onCompleted(); } ); return subscription; }; PausableBufferedObservable.prototype.pause = function () { this.paused = true; this.controller.onNext(false); }; PausableBufferedObservable.prototype.resume = function () { this.paused = false; this.controller.onNext(true); }; return PausableBufferedObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, * and yields the values that were buffered while paused. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausableBuffered(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausableBuffered = function (pauser) { return new PausableBufferedObservable(this, pauser); }; var ControlledObservable = (function (__super__) { inherits(ControlledObservable, __super__); function ControlledObservable (source, enableQueue, scheduler) { __super__.call(this); this.subject = new ControlledSubject(enableQueue, scheduler); this.source = source.multicast(this.subject).refCount(); } ControlledObservable.prototype._subscribe = function (o) { return this.source.subscribe(o); }; ControlledObservable.prototype.request = function (numberOfItems) { return this.subject.request(numberOfItems == null ? -1 : numberOfItems); }; return ControlledObservable; }(Observable)); var ControlledSubject = (function (__super__) { inherits(ControlledSubject, __super__); function ControlledSubject(enableQueue, scheduler) { enableQueue == null && (enableQueue = true); __super__.call(this); this.subject = new Subject(); this.enableQueue = enableQueue; this.queue = enableQueue ? [] : null; this.requestedCount = 0; this.requestedDisposable = null; this.error = null; this.hasFailed = false; this.hasCompleted = false; this.scheduler = scheduler || currentThreadScheduler; } addProperties(ControlledSubject.prototype, Observer, { _subscribe: function (o) { return this.subject.subscribe(o); }, onCompleted: function () { this.hasCompleted = true; if (!this.enableQueue || this.queue.length === 0) { this.subject.onCompleted(); this.disposeCurrentRequest(); } else { this.queue.push(Notification.createOnCompleted()); } }, onError: function (error) { this.hasFailed = true; this.error = error; if (!this.enableQueue || this.queue.length === 0) { this.subject.onError(error); this.disposeCurrentRequest(); } else { this.queue.push(Notification.createOnError(error)); } }, onNext: function (value) { if (this.requestedCount <= 0) { this.enableQueue && this.queue.push(Notification.createOnNext(value)); } else { (this.requestedCount-- === 0) && this.disposeCurrentRequest(); this.subject.onNext(value); } }, _processRequest: function (numberOfItems) { if (this.enableQueue) { while (this.queue.length > 0 && (numberOfItems > 0 || this.queue[0].kind !== 'N')) { var first = this.queue.shift(); first.accept(this.subject); if (first.kind === 'N') { numberOfItems--; } else { this.disposeCurrentRequest(); this.queue = []; } } } return numberOfItems; }, request: function (number) { this.disposeCurrentRequest(); var self = this; this.requestedDisposable = this.scheduler.schedule(number, function(s, i) { var remaining = self._processRequest(i); var stopped = self.hasCompleted || self.hasFailed; if (!stopped && remaining > 0) { self.requestedCount = remaining; return disposableCreate(function () { self.requestedCount = 0; }); // Scheduled item is still in progress. Return a new // disposable to allow the request to be interrupted // via dispose. } }); return this.requestedDisposable; }, disposeCurrentRequest: function () { if (this.requestedDisposable) { this.requestedDisposable.dispose(); this.requestedDisposable = null; } } }); return ControlledSubject; }(Observable)); /** * Attaches a controller to the observable sequence with the ability to queue. * @example * var source = Rx.Observable.interval(100).controlled(); * source.request(3); // Reads 3 values * @param {bool} enableQueue truthy value to determine if values should be queued pending the next request * @param {Scheduler} scheduler determines how the requests will be scheduled * @returns {Observable} The observable sequence which only propagates values on request. */ observableProto.controlled = function (enableQueue, scheduler) { if (enableQueue && isScheduler(enableQueue)) { scheduler = enableQueue; enableQueue = true; } if (enableQueue == null) { enableQueue = true; } return new ControlledObservable(this, enableQueue, scheduler); }; /** * Pipes the existing Observable sequence into a Node.js Stream. * @param {Stream} dest The destination Node.js stream. * @returns {Stream} The destination stream. */ observableProto.pipe = function (dest) { var source = this.pausableBuffered(); function onDrain() { source.resume(); } dest.addListener('drain', onDrain); source.subscribe( function (x) { !dest.write(x) && source.pause(); }, function (err) { dest.emit('error', err); }, function () { // Hack check because STDIO is not closable !dest._isStdio && dest.end(); dest.removeListener('drain', onDrain); }); source.resume(); return dest; }; var TransduceObserver = (function (__super__) { inherits(TransduceObserver, __super__); function TransduceObserver(o, xform) { this._o = o; this._xform = xform; __super__.call(this); } TransduceObserver.prototype.next = function (x) { var res = tryCatch(this._xform['@@transducer/step']).call(this._xform, this._o, x); if (res === errorObj) { this._o.onError(res.e); } }; TransduceObserver.prototype.error = function (e) { this._o.onError(e); }; TransduceObserver.prototype.completed = function () { this._xform['@@transducer/result'](this._o); }; return TransduceObserver; }(AbstractObserver)); function transformForObserver(o) { return { '@@transducer/init': function() { return o; }, '@@transducer/step': function(obs, input) { return obs.onNext(input); }, '@@transducer/result': function(obs) { return obs.onCompleted(); } }; } /** * Executes a transducer to transform the observable sequence * @param {Transducer} transducer A transducer to execute * @returns {Observable} An Observable sequence containing the results from the transducer. */ observableProto.transduce = function(transducer) { var source = this; return new AnonymousObservable(function(o) { var xform = transducer(transformForObserver(o)); return source.subscribe(new TransduceObserver(o, xform)); }, source); }; var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { return subscriber && isFunction(subscriber.dispose) ? subscriber : isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; } function setDisposable(s, state) { var ado = state[0], self = state[1]; var sub = tryCatch(self.__subscribe).call(self, ado); if (sub === errorObj && !ado.fail(errorObj.e)) { thrower(errorObj.e); } ado.setDisposable(fixSubscriber(sub)); } function AnonymousObservable(subscribe, parent) { this.source = parent; this.__subscribe = subscribe; __super__.call(this); } AnonymousObservable.prototype._subscribe = function (o) { var ado = new AutoDetachObserver(o), state = [ado, this]; if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(state, setDisposable); } else { setDisposable(null, state); } return ado; }; return AnonymousObservable; }(Observable)); var AutoDetachObserver = (function (__super__) { inherits(AutoDetachObserver, __super__); function AutoDetachObserver(observer) { __super__.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var result = tryCatch(this.observer.onNext).call(this.observer, value); if (result === errorObj) { this.dispose(); thrower(result.e); } }; AutoDetachObserverPrototype.error = function (err) { var result = tryCatch(this.observer.onError).call(this.observer, err); this.dispose(); result === errorObj && thrower(result.e); }; AutoDetachObserverPrototype.completed = function () { var result = tryCatch(this.observer.onCompleted).call(this.observer); this.dispose(); result === errorObj && thrower(result.e); }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); }; AutoDetachObserverPrototype.dispose = function () { __super__.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); var InnerSubscription = function (s, o) { this._s = s; this._o = o; }; InnerSubscription.prototype.dispose = function () { if (!this._s.isDisposed && this._o !== null) { var idx = this._s.observers.indexOf(this._o); this._s.observers.splice(idx, 1); this._o = null; } }; /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (__super__) { inherits(Subject, __super__); function Subject() { __super__.call(this); this.isDisposed = false; this.isStopped = false; this.observers = []; this.hasError = false; } addProperties(Subject.prototype, Observer.prototype, { _subscribe: function (o) { checkDisposed(this); if (!this.isStopped) { this.observers.push(o); return new InnerSubscription(this, o); } if (this.hasError) { o.onError(this.error); return disposableEmpty; } o.onCompleted(); return disposableEmpty; }, /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; this.error = error; this.hasError = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed(this); if (!this.isStopped) { for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (__super__) { inherits(AsyncSubject, __super__); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { __super__.call(this); this.isDisposed = false; this.isStopped = false; this.hasValue = false; this.observers = []; this.hasError = false; } addProperties(AsyncSubject.prototype, Observer.prototype, { _subscribe: function (o) { checkDisposed(this); if (!this.isStopped) { this.observers.push(o); return new InnerSubscription(this, o); } if (this.hasError) { o.onError(this.error); } else if (this.hasValue) { o.onNext(this.value); o.onCompleted(); } else { o.onCompleted(); } return disposableEmpty; }, /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var i, len; checkDisposed(this); if (!this.isStopped) { this.isStopped = true; var os = cloneArray(this.observers), len = os.length; if (this.hasValue) { for (i = 0; i < len; i++) { var o = os[i]; o.onNext(this.value); o.onCompleted(); } } else { for (i = 0; i < len; i++) { os[i].onCompleted(); } } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the error. * @param {Mixed} error The Error to send to all observers. */ onError: function (error) { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; this.hasError = true; this.error = error; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed(this); if (this.isStopped) { return; } this.value = value; this.hasValue = true; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.error = null; this.value = null; } }); return AsyncSubject; }(Observable)); var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { inherits(AnonymousSubject, __super__); function AnonymousSubject(observer, observable) { this.observer = observer; this.observable = observable; __super__.call(this); } addProperties(AnonymousSubject.prototype, Observer.prototype, { _subscribe: function (o) { return this.observable.subscribe(o); }, onCompleted: function () { this.observer.onCompleted(); }, onError: function (error) { this.observer.onError(error); }, onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); /** * Represents a value that changes over time. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */ var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) { inherits(BehaviorSubject, __super__); function BehaviorSubject(value) { __super__.call(this); this.value = value; this.observers = []; this.isDisposed = false; this.isStopped = false; this.hasError = false; } addProperties(BehaviorSubject.prototype, Observer.prototype, { _subscribe: function (o) { checkDisposed(this); if (!this.isStopped) { this.observers.push(o); o.onNext(this.value); return new InnerSubscription(this, o); } if (this.hasError) { o.onError(this.error); } else { o.onCompleted(); } return disposableEmpty; }, /** * Gets the current value or throws an exception. * Value is frozen after onCompleted is called. * After onError is called always throws the specified exception. * An exception is always thrown after dispose is called. * @returns {Mixed} The initial value passed to the constructor until onNext is called; after which, the last value passed to onNext. */ getValue: function () { checkDisposed(this); if (this.hasError) { thrower(this.error); } return this.value; }, /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; this.hasError = true; this.error = error; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed(this); if (this.isStopped) { return; } this.value = value; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onNext(value); } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.value = null; this.error = null; } }); return BehaviorSubject; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. */ var ReplaySubject = Rx.ReplaySubject = (function (__super__) { var maxSafeInteger = Math.pow(2, 53) - 1; function createRemovableDisposable(subject, observer) { return disposableCreate(function () { observer.dispose(); !subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1); }); } inherits(ReplaySubject, __super__); /** * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. * @param {Number} [bufferSize] Maximum element count of the replay buffer. * @param {Number} [windowSize] Maximum time length of the replay buffer. * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. */ function ReplaySubject(bufferSize, windowSize, scheduler) { this.bufferSize = bufferSize == null ? maxSafeInteger : bufferSize; this.windowSize = windowSize == null ? maxSafeInteger : windowSize; this.scheduler = scheduler || currentThreadScheduler; this.q = []; this.observers = []; this.isStopped = false; this.isDisposed = false; this.hasError = false; this.error = null; __super__.call(this); } addProperties(ReplaySubject.prototype, Observer.prototype, { _subscribe: function (o) { checkDisposed(this); var so = new ScheduledObserver(this.scheduler, o), subscription = createRemovableDisposable(this, so); this._trim(this.scheduler.now()); this.observers.push(so); for (var i = 0, len = this.q.length; i < len; i++) { so.onNext(this.q[i].value); } if (this.hasError) { so.onError(this.error); } else if (this.isStopped) { so.onCompleted(); } so.ensureActive(); return subscription; }, /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed(this); return this.observers.length > 0; }, _trim: function (now) { while (this.q.length > this.bufferSize) { this.q.shift(); } while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { this.q.shift(); } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed(this); if (this.isStopped) { return; } var now = this.scheduler.now(); this.q.push({ interval: now, value: value }); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onNext(value); observer.ensureActive(); } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; this.error = error; this.hasError = true; var now = this.scheduler.now(); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onError(error); observer.ensureActive(); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; var now = this.scheduler.now(); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onCompleted(); observer.ensureActive(); } this.observers.length = 0; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); return ReplaySubject; }(Observable)); /** * Used to pause and resume streams. */ Rx.Pauser = (function (__super__) { inherits(Pauser, __super__); function Pauser() { __super__.call(this); } /** * Pauses the underlying sequence. */ Pauser.prototype.pause = function () { this.onNext(false); }; /** * Resumes the underlying sequence. */ Pauser.prototype.resume = function () { this.onNext(true); }; return Pauser; }(Subject)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } // All code before this point will be filtered from stack traces. var rEndingLine = captureLine(); }.call(this));
ajax/libs/mini-meteor/1.0.0/mini-meteor.min.js
artch/cdnjs
(function(){var a=this,b=a._,d=Array.prototype,f=Object.prototype,l=d.push,k=d.slice,n=d.concat,p=f.toString,C=f.hasOwnProperty,f=Array.isArray,D=Object.keys,w=Function.prototype.bind,c=function(e){return e instanceof c?e:this instanceof c?void(this._wrapped=e):new c(e)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=c),exports._=c):a._=c;c.VERSION="1.7.0";var t=function(e,a,c){if(void 0===a)return e;switch(null==c?3:c){case 1:return function(c){return e.call(a, c)};case 2:return function(c,g){return e.call(a,c,g)};case 3:return function(c,g,b){return e.call(a,c,g,b)};case 4:return function(c,g,b,d){return e.call(a,c,g,b,d)}}return function(){return e.apply(a,arguments)}};c.iteratee=function(e,a,g){return null==e?c.identity:c.isFunction(e)?t(e,a,g):c.isObject(e)?c.matches(e):c.property(e)};c.each=c.forEach=function(e,a,g){if(null==e)return e;a=t(a,g);var q=e.length;if(q===+q)for(g=0;q>g;g++)a(e[g],g,e);else{var b=c.keys(e);g=0;for(q=b.length;q>g;g++)a(e[b[g]], b[g],e)}return e};c.map=c.collect=function(e,a,g){if(null==e)return[];a=c.iteratee(a,g);for(var q=e.length!==+e.length&&c.keys(e),b=(q||e).length,d=Array(b),m=0;b>m;m++)g=q?q[m]:m,d[m]=a(e[g],g,e);return d};c.reduce=c.foldl=c.inject=function(e,a,g,q){null==e&&(e=[]);a=t(a,q,4);var b,d=e.length!==+e.length&&c.keys(e),m=(d||e).length,f=0;if(3>arguments.length){if(!m)throw new TypeError("Reduce of empty array with no initial value");g=e[d?d[f++]:f++]}for(;m>f;f++)b=d?d[f]:f,g=a(g,e[b],b,e);return g}; c.reduceRight=c.foldr=function(e,a,g,b){null==e&&(e=[]);a=t(a,b,4);var h,d=e.length!==+e.length&&c.keys(e),f=(d||e).length;if(3>arguments.length){if(!f)throw new TypeError("Reduce of empty array with no initial value");g=e[d?d[--f]:--f]}for(;f--;)h=d?d[f]:f,g=a(g,e[h],h,e);return g};c.find=c.detect=function(e,a,g){var b;return a=c.iteratee(a,g),c.some(e,function(e,c,g){return a(e,c,g)?(b=e,!0):void 0}),b};c.filter=c.select=function(e,a,g){var b=[];return null==e?b:(a=c.iteratee(a,g),c.each(e,function(e, c,g){a(e,c,g)&&b.push(e)}),b)};c.reject=function(e,a,g){return c.filter(e,c.negate(c.iteratee(a)),g)};c.every=c.all=function(e,a,g){if(null==e)return!0;a=c.iteratee(a,g);var b,h=e.length!==+e.length&&c.keys(e),d=(h||e).length;for(g=0;d>g;g++)if(b=h?h[g]:g,!a(e[b],b,e))return!1;return!0};c.some=c.any=function(e,a,g){if(null==e)return!1;a=c.iteratee(a,g);var b,h=e.length!==+e.length&&c.keys(e),d=(h||e).length;for(g=0;d>g;g++)if(b=h?h[g]:g,a(e[b],b,e))return!0;return!1};c.contains=c.include=function(e, a){return null==e?!1:(e.length!==+e.length&&(e=c.values(e)),0<=c.indexOf(e,a))};c.invoke=function(e,a){var g=k.call(arguments,2),b=c.isFunction(a);return c.map(e,function(e){return(b?a:e[a]).apply(e,g)})};c.pluck=function(e,a){return c.map(e,c.property(a))};c.where=function(e,a){return c.filter(e,c.matches(a))};c.findWhere=function(e,a){return c.find(e,c.matches(a))};c.max=function(e,a,g){var b,h=-1/0,d=-1/0;if(null==a&&null!=e){e=e.length===+e.length?e:c.values(e);for(var f=0,r=e.length;r>f;f++)g= e[f],g>h&&(h=g)}else a=c.iteratee(a,g),c.each(e,function(e,c,g){b=a(e,c,g);(b>d||b===-1/0&&h===-1/0)&&(h=e,d=b)});return h};c.min=function(e,a,g){var b,h=1/0,d=1/0;if(null==a&&null!=e){e=e.length===+e.length?e:c.values(e);for(var f=0,r=e.length;r>f;f++)g=e[f],h>g&&(h=g)}else a=c.iteratee(a,g),c.each(e,function(e,c,g){b=a(e,c,g);(d>b||1/0===b&&1/0===h)&&(h=e,d=b)});return h};c.shuffle=function(e){for(var a=e&&e.length===+e.length?e:c.values(e),g=a.length,b=Array(g),h=0;g>h;h++)e=c.random(0,h),e!== h&&(b[h]=b[e]),b[e]=a[h];return b};c.sample=function(e,a,g){return null==a||g?(e.length!==+e.length&&(e=c.values(e)),e[c.random(e.length-1)]):c.shuffle(e).slice(0,Math.max(0,a))};c.sortBy=function(e,a,g){return a=c.iteratee(a,g),c.pluck(c.map(e,function(e,c,g){return{value:e,index:c,criteria:a(e,c,g)}}).sort(function(e,a){var c=e.criteria,g=a.criteria;if(c!==g){if(c>g||void 0===c)return 1;if(g>c||void 0===g)return-1}return e.index-a.index}),"value")};var u=function(e){return function(a,g,b){var d= {};return g=c.iteratee(g,b),c.each(a,function(c,b){var q=g(c,b,a);e(d,c,q)}),d}};c.groupBy=u(function(e,a,g){c.has(e,g)?e[g].push(a):e[g]=[a]});c.indexBy=u(function(e,a,c){e[c]=a});c.countBy=u(function(e,a,g){c.has(e,g)?e[g]++:e[g]=1});c.sortedIndex=function(e,a,g,b){g=c.iteratee(g,b,1);a=g(a);b=0;for(var d=e.length;d>b;){var f=b+d>>>1;g(e[f])<a?b=f+1:d=f}return b};c.toArray=function(e){return e?c.isArray(e)?k.call(e):e.length===+e.length?c.map(e,c.identity):c.values(e):[]};c.size=function(e){return null== e?0:e.length===+e.length?e.length:c.keys(e).length};c.partition=function(e,a,g){a=c.iteratee(a,g);var b=[],d=[];return c.each(e,function(e,c,g){(a(e,c,g)?b:d).push(e)}),[b,d]};c.first=c.head=c.take=function(e,a,c){return null==e?void 0:null==a||c?e[0]:0>a?[]:k.call(e,0,a)};c.initial=function(e,a,c){return k.call(e,0,Math.max(0,e.length-(null==a||c?1:a)))};c.last=function(e,a,c){return null==e?void 0:null==a||c?e[e.length-1]:k.call(e,Math.max(e.length-a,0))};c.rest=c.tail=c.drop=function(e,a,c){return k.call(e, null==a||c?1:a)};c.compact=function(e){return c.filter(e,c.identity)};var v=function(e,a,g,b){if(a&&c.every(e,c.isArray))return n.apply(b,e);for(var d=0,f=e.length;f>d;d++){var m=e[d];c.isArray(m)||c.isArguments(m)?a?l.apply(b,m):v(m,a,g,b):g||b.push(m)}return b};c.flatten=function(e,a){return v(e,a,!1,[])};c.without=function(e){return c.difference(e,k.call(arguments,1))};c.uniq=c.unique=function(e,a,b,d){if(null==e)return[];c.isBoolean(a)||(d=b,b=a,a=!1);null!=b&&(b=c.iteratee(b,d));d=[];for(var h= [],f=0,m=e.length;m>f;f++){var r=e[f];if(a)f&&h===r||d.push(r),h=r;else if(b){var k=b(r,f,e);0>c.indexOf(h,k)&&(h.push(k),d.push(r))}else 0>c.indexOf(d,r)&&d.push(r)}return d};c.union=function(){return c.uniq(v(arguments,!0,!0,[]))};c.intersection=function(e){if(null==e)return[];for(var a=[],b=arguments.length,d=0,h=e.length;h>d;d++){var f=e[d];if(!c.contains(a,f)){for(var m=1;b>m&&c.contains(arguments[m],f);m++);m===b&&a.push(f)}}return a};c.difference=function(e){var a=v(k.call(arguments,1),!0, !0,[]);return c.filter(e,function(e){return!c.contains(a,e)})};c.zip=function(e){if(null==e)return[];for(var a=c.max(arguments,"length").length,b=Array(a),d=0;a>d;d++)b[d]=c.pluck(arguments,d);return b};c.object=function(a,c){if(null==a)return{};for(var b={},d=0,h=a.length;h>d;d++)c?b[a[d]]=c[d]:b[a[d][0]]=a[d][1];return b};c.indexOf=function(a,b,g){if(null==a)return-1;var d=0,h=a.length;if(g){if("number"!=typeof g)return d=c.sortedIndex(a,b),a[d]===b?d:-1;d=0>g?Math.max(0,h+g):g}for(;h>d;d++)if(a[d]=== b)return d;return-1};c.lastIndexOf=function(a,c,b){if(null==a)return-1;var d=a.length;for("number"==typeof b&&(d=0>b?d+b+1:Math.min(d,b+1));0<=--d;)if(a[d]===c)return d;return-1};c.range=function(a,c,b){1>=arguments.length&&(c=a||0,a=0);b=b||1;for(var d=Math.max(Math.ceil((c-a)/b),0),h=Array(d),f=0;d>f;f++,a+=b)h[f]=a;return h};var y=function(){};c.bind=function(a,b){var g,d;if(w&&a.bind===w)return w.apply(a,k.call(arguments,1));if(!c.isFunction(a))throw new TypeError("Bind must be called on a function"); return g=k.call(arguments,2),d=function(){if(!(this instanceof d))return a.apply(b,g.concat(k.call(arguments)));y.prototype=a.prototype;var h=new y;y.prototype=null;var f=a.apply(h,g.concat(k.call(arguments)));return c.isObject(f)?f:h}};c.partial=function(a){var b=k.call(arguments,1);return function(){for(var g=0,d=b.slice(),h=0,f=d.length;f>h;h++)d[h]===c&&(d[h]=arguments[g++]);for(;g<arguments.length;)d.push(arguments[g++]);return a.apply(this,d)}};c.bindAll=function(a){var b,g,d=arguments.length; if(1>=d)throw Error("bindAll must be passed function names");for(b=1;d>b;b++)g=arguments[b],a[g]=c.bind(a[g],a);return a};c.memoize=function(a,b){var g=function(d){var h=g.cache,f=b?b.apply(this,arguments):d;return c.has(h,f)||(h[f]=a.apply(this,arguments)),h[f]};return g.cache={},g};c.delay=function(a,c){var b=k.call(arguments,2);return setTimeout(function(){return a.apply(null,b)},c)};c.defer=function(a){return c.delay.apply(c,[a,1].concat(k.call(arguments,1)))};c.throttle=function(a,b,d){var f, h,x,m=null,k=0;d||(d={});var l=function(){k=!1===d.leading?0:c.now();m=null;x=a.apply(f,h);m||(f=h=null)};return function(){var p=c.now();k||!1!==d.leading||(k=p);var n=b-(p-k);return f=this,h=arguments,0>=n||n>b?(clearTimeout(m),m=null,k=p,x=a.apply(f,h),m||(f=h=null)):m||!1===d.trailing||(m=setTimeout(l,n)),x}};c.debounce=function(a,b,d){var f,h,k,m,l,p=function(){var n=c.now()-m;b>n&&0<n?f=setTimeout(p,b-n):(f=null,d||(l=a.apply(k,h),f||(k=h=null)))};return function(){k=this;h=arguments;m=c.now(); var n=d&&!f;return f||(f=setTimeout(p,b)),n&&(l=a.apply(k,h),k=h=null),l}};c.wrap=function(a,b){return c.partial(b,a)};c.negate=function(a){return function(){return!a.apply(this,arguments)}};c.compose=function(){var a=arguments,c=a.length-1;return function(){for(var b=c,d=a[c].apply(this,arguments);b--;)d=a[b].call(this,d);return d}};c.after=function(a,c){return function(){return 1>--a?c.apply(this,arguments):void 0}};c.before=function(a,c){var b;return function(){return 0<--a?b=c.apply(this,arguments): c=null,b}};c.once=c.partial(c.before,2);c.keys=function(a){if(!c.isObject(a))return[];if(D)return D(a);var b=[],d;for(d in a)c.has(a,d)&&b.push(d);return b};c.values=function(a){for(var b=c.keys(a),d=b.length,f=Array(d),h=0;d>h;h++)f[h]=a[b[h]];return f};c.pairs=function(a){for(var b=c.keys(a),d=b.length,f=Array(d),h=0;d>h;h++)f[h]=[b[h],a[b[h]]];return f};c.invert=function(a){for(var b={},d=c.keys(a),f=0,h=d.length;h>f;f++)b[a[d[f]]]=d[f];return b};c.functions=c.methods=function(a){var b=[],d;for(d in a)c.isFunction(a[d])&& b.push(d);return b.sort()};c.extend=function(a){if(!c.isObject(a))return a;for(var b,d,f=1,h=arguments.length;h>f;f++)for(d in b=arguments[f],b)C.call(b,d)&&(a[d]=b[d]);return a};c.pick=function(a,b,d){var f,h={};if(null==a)return h;if(c.isFunction(b))for(f in b=t(b,d),a){var l=a[f];b(l,f,a)&&(h[f]=l)}else{l=n.apply([],k.call(arguments,1));a=Object(a);for(var m=0,p=l.length;p>m;m++)f=l[m],f in a&&(h[f]=a[f])}return h};c.omit=function(a,b,d){if(c.isFunction(b))b=c.negate(b);else{var f=c.map(n.apply([], k.call(arguments,1)),String);b=function(a,e){return!c.contains(f,e)}}return c.pick(a,b,d)};c.defaults=function(a){if(!c.isObject(a))return a;for(var b=1,d=arguments.length;d>b;b++){var f=arguments[b],h;for(h in f)void 0===a[h]&&(a[h]=f[h])}return a};c.clone=function(a){return c.isObject(a)?c.isArray(a)?a.slice():c.extend({},a):a};c.tap=function(a,b){return b(a),a};var z=function(a,b,d,f){if(a===b)return 0!==a||1/a===1/b;if(null==a||null==b)return a===b;a instanceof c&&(a=a._wrapped);b instanceof c&& (b=b._wrapped);var h=p.call(a);if(h!==p.call(b))return!1;switch(h){case "[object RegExp]":case "[object String]":return""+a==""+b;case "[object Number]":return+a!==+a?+b!==+b:0===+a?1/+a===1/b:+a===+b;case "[object Date]":case "[object Boolean]":return+a===+b}if("object"!=typeof a||"object"!=typeof b)return!1;for(var k=d.length;k--;)if(d[k]===a)return f[k]===b;var k=a.constructor,m=b.constructor;if(k!==m&&"constructor"in a&&"constructor"in b&&!(c.isFunction(k)&&k instanceof k&&c.isFunction(m)&&m instanceof m))return!1;d.push(a);f.push(b);var l;if("[object Array]"===h){if(l=a.length,h=l===b.length)for(;l--&&(h=z(a[l],b[l],d,f)););}else{var n,k=c.keys(a);if(l=k.length,h=c.keys(b).length===l)for(;l--&&(n=k[l],h=c.has(b,n)&&z(a[n],b[n],d,f)););}return d.pop(),f.pop(),h};c.isEqual=function(a,b){return z(a,b,[],[])};c.isEmpty=function(a){if(null==a)return!0;if(c.isArray(a)||c.isString(a)||c.isArguments(a))return 0===a.length;for(var b in a)if(c.has(a,b))return!1;return!0};c.isElement=function(a){return!(!a|| 1!==a.nodeType)};c.isArray=f||function(a){return"[object Array]"===p.call(a)};c.isObject=function(a){var b=typeof a;return"function"===b||"object"===b&&!!a};c.each("Arguments Function String Number Date RegExp".split(" "),function(a){c["is"+a]=function(b){return p.call(b)==="[object "+a+"]"}});c.isArguments(arguments)||(c.isArguments=function(a){return c.has(a,"callee")});"function"!=typeof/./&&(c.isFunction=function(a){return"function"==typeof a||!1});c.isFinite=function(a){return isFinite(a)&&!isNaN(parseFloat(a))}; c.isNaN=function(a){return c.isNumber(a)&&a!==+a};c.isBoolean=function(a){return!0===a||!1===a||"[object Boolean]"===p.call(a)};c.isNull=function(a){return null===a};c.isUndefined=function(a){return void 0===a};c.has=function(a,b){return null!=a&&C.call(a,b)};c.noConflict=function(){return a._=b,this};c.identity=function(a){return a};c.constant=function(a){return function(){return a}};c.noop=function(){};c.property=function(a){return function(b){return b[a]}};c.matches=function(a){var b=c.pairs(a), d=b.length;return function(a){if(null==a)return!d;a=Object(a);for(var c=0;d>c;c++){var e=b[c],f=e[0];if(e[1]!==a[f]||!(f in a))return!1}return!0}};c.times=function(a,b,c){var d=Array(Math.max(0,a));b=t(b,c,1);for(c=0;a>c;c++)d[c]=b(c);return d};c.random=function(a,b){return null==b&&(b=a,a=0),a+Math.floor(Math.random()*(b-a+1))};c.now=Date.now||function(){return(new Date).getTime()};var f={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;"},u=c.invert(f),E=function(a){var b= function(b){return a[b]},d="(?:"+c.keys(a).join("|")+")",f=RegExp(d),h=RegExp(d,"g");return function(a){return a=null==a?"":""+a,f.test(a)?a.replace(h,b):a}};c.escape=E(f);c.unescape=E(u);c.result=function(a,b){if(null!=a){var d=a[b];return c.isFunction(d)?a[b]():d}};var F=0;c.uniqueId=function(a){var b=++F+"";return a?a+b:b};c.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var A=/(.)^/,G={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028", "\u2029":"u2029"},H=/\\|'|\r|\n|\u2028|\u2029/g,I=function(a){return"\\"+G[a]};c.template=function(a,b,d){!b&&d&&(b=d);b=c.defaults({},b,c.templateSettings);d=RegExp([(b.escape||A).source,(b.interpolate||A).source,(b.evaluate||A).source].join("|")+"|$","g");var f=0,h="__p+='";a.replace(d,function(b,c,d,g,k){return h+=a.slice(f,k).replace(H,I),f=k+b.length,c?h+="'+\n((__t=("+c+"))==null?'':_.escape(__t))+\n'":d?h+="'+\n((__t=("+d+"))==null?'':__t)+\n'":g&&(h+="';\n"+g+"\n__p+='"),b});h+="';\n";b.variable|| (h="with(obj||{}){\n"+h+"}\n");h="var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};\n"+h+"return __p;\n";try{var k=new Function(b.variable||"obj","_",h)}catch(l){throw l.source=h,l;}d=function(a){return k.call(this,a,c)};return d.source="function("+(b.variable||"obj")+"){\n"+h+"}",d};c.chain=function(a){a=c(a);return a._chain=!0,a};var B=function(a){return this._chain?c(a).chain():a};c.mixin=function(a){c.each(c.functions(a),function(b){var d=c[b]=a[b];c.prototype[b]= function(){var a=[this._wrapped];return l.apply(a,arguments),B.call(this,d.apply(c,a))}})};c.mixin(c);c.each("pop push reverse shift sort splice unshift".split(" "),function(a){var b=d[a];c.prototype[a]=function(){var c=this._wrapped;return b.apply(c,arguments),"shift"!==a&&"splice"!==a||0!==c.length||delete c[0],B.call(this,c)}});c.each(["concat","join","slice"],function(a){var b=d[a];c.prototype[a]=function(){return B.call(this,b.apply(this._wrapped,arguments))}});c.prototype.value=function(){return this._wrapped}; "function"==typeof define&&define.amd&&define("underscore",[],function(){return c})}).call(this);for(var BASE_64_CHARS="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",BASE_64_VALS={},i=0;i<BASE_64_CHARS.length;i++)BASE_64_VALS[BASE_64_CHARS.charAt(i)]=i; Base64={encode:function(a){if("string"===typeof a){var b=a;a=Base64.newBinary(b.length);for(var d=0;d<b.length;d++){var f=b.charCodeAt(d);if(255<f)throw Error("Not ascii. Base64.encode can only take ascii strings.");a[d]=f}}for(var b=[],l=f=null,k=null,n=null,d=0;d<a.length;d++)switch(d%3){case 0:f=a[d]>>2&63;l=(a[d]&3)<<4;break;case 1:l|=a[d]>>4&15;k=(a[d]&15)<<2;break;case 2:k|=a[d]>>6&3,n=a[d]&63,b.push(getChar(f)),b.push(getChar(l)),b.push(getChar(k)),b.push(getChar(n)),n=k=l=f=null}null!=f&& (b.push(getChar(f)),b.push(getChar(l)),null==k?b.push("="):b.push(getChar(k)),null==n&&b.push("="));return b.join("")}};var getChar=function(a){return BASE_64_CHARS.charAt(a)},getVal=function(a){return"="===a?-1:BASE_64_VALS[a]};Base64.newBinary=function(a){if("undefined"===typeof Uint8Array||"undefined"===typeof ArrayBuffer){for(var b=[],d=0;d<a;d++)b.push(0);b.$Uint8ArrayPolyfill=!0;return b}return new Uint8Array(new ArrayBuffer(a))}; Base64.decode=function(a){var b=Math.floor(3*a.length/4);"="==a.charAt(a.length-1)&&(b--,"="==a.charAt(a.length-2)&&b--);for(var b=Base64.newBinary(b),d=null,f=null,l=null,k=0,n=0;n<a.length;n++){var p=a.charAt(n),p=getVal(p);switch(n%4){case 0:if(0>p)throw Error("invalid base64 string");d=p<<2;break;case 1:if(0>p)throw Error("invalid base64 string");d|=p>>4;b[k++]=d;f=(p&15)<<4;break;case 2:0<=p&&(f|=p>>2,b[k++]=f,l=(p&3)<<6);break;case 3:0<=p&&(b[k++]=l|p)}}return b};EJSON={};EJSONTest={}; var customTypes={};EJSON.addType=function(a,b){if(_.has(customTypes,a))throw Error("Type "+a+" already present");customTypes[a]=b}; var isInfOrNan=function(a){return _.isNaN(a)||Infinity===a||-Infinity===a},builtinConverters=[{matchJSONValue:function(a){return _.has(a,"$date")&&1===_.size(a)},matchObject:function(a){return a instanceof Date},toJSONValue:function(a){return{$date:a.getTime()}},fromJSONValue:function(a){return new Date(a.$date)}},{matchJSONValue:function(a){return _.has(a,"$InfNaN")&&1===_.size(a)},matchObject:isInfOrNan,toJSONValue:function(a){return{$InfNaN:_.isNaN(a)?0:Infinity===a?1:-1}},fromJSONValue:function(a){return a.$InfNaN/ 0}},{matchJSONValue:function(a){return _.has(a,"$binary")&&1===_.size(a)},matchObject:function(a){return"undefined"!==typeof Uint8Array&&a instanceof Uint8Array||a&&_.has(a,"$Uint8ArrayPolyfill")},toJSONValue:function(a){return{$binary:Base64.encode(a)}},fromJSONValue:function(a){return Base64.decode(a.$binary)}},{matchJSONValue:function(a){return _.has(a,"$escape")&&1===_.size(a)},matchObject:function(a){return _.isEmpty(a)||2<_.size(a)?!1:_.any(builtinConverters,function(b){return b.matchJSONValue(a)})}, toJSONValue:function(a){var b={};_.each(a,function(a,f){b[f]=EJSON.toJSONValue(a)});return{$escape:b}},fromJSONValue:function(a){var b={};_.each(a.$escape,function(a,f){b[f]=EJSON.fromJSONValue(a)});return b}},{matchJSONValue:function(a){return _.has(a,"$type")&&_.has(a,"$value")&&2===_.size(a)},matchObject:function(a){return EJSON._isCustomType(a)},toJSONValue:function(a){var b=Meteor._noYieldsAllowed(function(){return a.toJSONValue()});return{$type:a.typeName(),$value:b}},fromJSONValue:function(a){var b= a.$type;if(!_.has(customTypes,b))throw Error("Custom EJSON type "+b+" is not defined");var d=customTypes[b];return Meteor._noYieldsAllowed(function(){return d(a.$value)})}}];EJSON._isCustomType=function(a){return a&&"function"===typeof a.toJSONValue&&"function"===typeof a.typeName&&_.has(customTypes,a.typeName())}; var adjustTypesToJSONValue=EJSON._adjustTypesToJSONValue=function(a){if(null===a)return null;var b=toJSONValueHelper(a);if(void 0!==b)return b;if("object"!==typeof a)return a;_.each(a,function(b,f){if("object"===typeof b||void 0===b||isInfOrNan(b)){var l=toJSONValueHelper(b);l?a[f]=l:adjustTypesToJSONValue(b)}});return a},toJSONValueHelper=function(a){for(var b=0;b<builtinConverters.length;b++){var d=builtinConverters[b];if(d.matchObject(a))return d.toJSONValue(a)}}; EJSON.toJSONValue=function(a){var b=toJSONValueHelper(a);if(void 0!==b)return b;"object"===typeof a&&(a=EJSON.clone(a),adjustTypesToJSONValue(a));return a}; var adjustTypesFromJSONValue=EJSON._adjustTypesFromJSONValue=function(a){if(null===a)return null;var b=fromJSONValueHelper(a);if(b!==a)return b;if("object"!==typeof a)return a;_.each(a,function(b,f){if("object"===typeof b){var l=fromJSONValueHelper(b);b!==l?a[f]=l:adjustTypesFromJSONValue(b)}});return a},fromJSONValueHelper=function(a){if("object"===typeof a&&null!==a&&2>=_.size(a)&&_.all(a,function(a,b){return"string"===typeof b&&"$"===b.substr(0,1)}))for(var b=0;b<builtinConverters.length;b++){var d= builtinConverters[b];if(d.matchJSONValue(a))return d.fromJSONValue(a)}return a};EJSON.fromJSONValue=function(a){var b=fromJSONValueHelper(a);return b===a&&"object"===typeof a?(a=EJSON.clone(a),adjustTypesFromJSONValue(a),a):b};EJSON.stringify=function(a,b){var d=EJSON.toJSONValue(a);return b&&(b.canonical||b.indent)?EJSON._canonicalStringify(d,b):JSON.stringify(d)};EJSON.parse=function(a){if("string"!==typeof a)throw Error("EJSON.parse argument should be a string");return EJSON.fromJSONValue(JSON.parse(a))}; EJSON.isBinary=function(a){return!!("undefined"!==typeof Uint8Array&&a instanceof Uint8Array||a&&a.$Uint8ArrayPolyfill)}; EJSON.equals=function(a,b,d){var f,l=!(!d||!d.keyOrderSensitive);if(a===b||_.isNaN(a)&&_.isNaN(b))return!0;if(!a||!b||"object"!==typeof a||"object"!==typeof b)return!1;if(a instanceof Date&&b instanceof Date)return a.valueOf()===b.valueOf();if(EJSON.isBinary(a)&&EJSON.isBinary(b)){if(a.length!==b.length)return!1;for(f=0;f<a.length;f++)if(a[f]!==b[f])return!1;return!0}if("function"===typeof a.equals)return a.equals(b,d);if("function"===typeof b.equals)return b.equals(a,d);if(a instanceof Array){if(!(b instanceof Array)||a.length!==b.length)return!1;for(f=0;f<a.length;f++)if(!EJSON.equals(a[f],b[f],d))return!1;return!0}switch(EJSON._isCustomType(a)+EJSON._isCustomType(b)){case 1:return!1;case 2:return EJSON.equals(EJSON.toJSONValue(a),EJSON.toJSONValue(b))}if(l){var k=[];_.each(b,function(a,b){k.push(b)});f=0;return(a=_.all(a,function(a,l){if(f>=k.length||l!==k[f]||!EJSON.equals(a,b[k[f]],d))return!1;f++;return!0}))&&f===k.length}f=0;return(a=_.all(a,function(a,k){if(!_.has(b,k)||!EJSON.equals(a,b[k],d))return!1; f++;return!0}))&&_.size(b)===f}; EJSON.clone=function(a){var b;if("object"!==typeof a)return a;if(null===a)return null;if(a instanceof Date)return new Date(a.getTime());if(a instanceof RegExp)return a;if(EJSON.isBinary(a)){b=EJSON.newBinary(a.length);for(var d=0;d<a.length;d++)b[d]=a[d];return b}if(_.isArray(a)||_.isArguments(a)){b=[];for(d=0;d<a.length;d++)b[d]=EJSON.clone(a[d]);return b}if("function"===typeof a.clone)return a.clone();if(EJSON._isCustomType(a))return EJSON.fromJSONValue(EJSON.clone(EJSON.toJSONValue(a)),!0);b={}; _.each(a,function(a,d){b[d]=EJSON.clone(a)});return b};EJSON.newBinary=Base64.newBinary;Meteor={active:!1,currentComputation:null}; var setCurrentComputation=function(a){Meteor.currentComputation=a;Meteor.active=!!a},_debugFunc=function(){return"undefined"!==typeof Meteor?Meteor._debug:"undefined"!==typeof console&&console.log?function(){console.log.apply(console,arguments)}:function(){}},_throwOrLog=function(a,b){if(throwFirstError)throw b;var d;b.stack&&b.message?(d=b.stack.indexOf(b.message),d=0<=d&&10>=d?b.stack:b.message+("\n"===b.stack.charAt(0)?"":"\n")+b.stack):d=b.stack||b.message;_debugFunc()("Exception from Meteor "+ a+" function:",d)},withNoYieldsAllowed=function(a){return"undefined"===typeof Meteor||Meteor.isClient?a:function(){var b=arguments;Meteor._noYieldsAllowed(function(){a.apply(null,b)})}},nextId=1,pendingComputations=[],willFlush=!1,inFlush=!1,inCompute=!1,throwFirstError=!1,afterFlushCallbacks=[],requireFlush=function(){willFlush||(setTimeout(Meteor.flush,0),willFlush=!0)},constructingComputation=!1; Meteor.Computation=function(a,b){if(!constructingComputation)throw Error("Meteor.Computation constructor is private; use Meteor.run");this.invalidated=this.stopped=constructingComputation=!1;this.firstRun=!0;this._id=nextId++;this._onInvalidateCallbacks=[];this._parent=b;this._func=a;this._recomputing=!1;var d=!0;try{this._compute(),d=!1}finally{this.firstRun=!1,d&&this.stop()}}; Meteor.Computation.prototype.onInvalidate=function(a){var b=this;if("function"!==typeof a)throw Error("onInvalidate requires a function");b.invalidated?Meteor.nonreactive(function(){withNoYieldsAllowed(a)(b)}):b._onInvalidateCallbacks.push(a)}; Meteor.Computation.prototype.invalidate=function(){var a=this;if(!a.invalidated){a._recomputing||a.stopped||(requireFlush(),pendingComputations.push(this));a.invalidated=!0;for(var b=0,d;d=a._onInvalidateCallbacks[b];b++)Meteor.nonreactive(function(){withNoYieldsAllowed(d)(a)});a._onInvalidateCallbacks=[]}};Meteor.Computation.prototype.stop=function(){this.stopped||(this.stopped=!0,this.invalidate())}; Meteor.Computation.prototype._compute=function(){this.invalidated=!1;var a=Meteor.currentComputation;setCurrentComputation(this);inCompute=!0;try{withNoYieldsAllowed(this._func)(this)}finally{setCurrentComputation(a),inCompute=!1}};Meteor.Computation.prototype._recompute=function(){this._recomputing=!0;try{for(;this.invalidated&&!this.stopped;)try{this._compute()}catch(a){_throwOrLog("recompute",a)}}finally{this._recomputing=!1}};Meteor.Dependency=function(){this._dependentsById={}}; Meteor.Dependency.prototype.depend=function(a){if(!a){if(!Meteor.active)return!1;a=Meteor.currentComputation}var b=this,d=a._id;return d in b._dependentsById?!1:(b._dependentsById[d]=a,a.onInvalidate(function(){delete b._dependentsById[d]}),!0)};Meteor.Dependency.prototype.changed=function(){for(var a in this._dependentsById)this._dependentsById[a].invalidate()};Meteor.Dependency.prototype.hasDependents=function(){for(var a in this._dependentsById)return!0;return!1}; Meteor.flush=function(a){if(inFlush)throw Error("Can't call Meteor.flush while flushing");if(inCompute)throw Error("Can't flush inside Meteor.run");willFlush=inFlush=!0;throwFirstError=!(!a||!a._throwFirstError);a=!1;try{for(;pendingComputations.length||afterFlushCallbacks.length;){for(;pendingComputations.length;)pendingComputations.shift()._recompute();if(afterFlushCallbacks.length){var b=afterFlushCallbacks.shift();try{b()}catch(d){_throwOrLog("afterFlush",d)}}}a=!0}finally{a||(inFlush= !1,Meteor.flush({_throwFirstError:!1})),inFlush=willFlush=!1}};Meteor.run=function(a){if("function"!==typeof a)throw Error("Meteor.run requires a function argument");constructingComputation=!0;var b=new Meteor.Computation(a,Meteor.currentComputation);if(Meteor.active)Meteor.onInvalidate(function(){b.stop()});return b};Meteor.nonreactive=function(a){var b=Meteor.currentComputation;setCurrentComputation(null);try{return a()}finally{setCurrentComputation(b)}}; Meteor.onInvalidate=function(a){if(!Meteor.active)throw Error("Meteor.onInvalidate requires a currentComputation");Meteor.currentComputation.onInvalidate(a)};Meteor.afterFlush=function(a){afterFlushCallbacks.push(a);requireFlush()};var stringify=function(a){return void 0===a?"undefined":EJSON.stringify(a)},parse=function(a){return void 0===a||"undefined"===a?void 0:EJSON.parse(a)};ReactiveMap=function(a){this.keys=a||{};this.keyDeps={};this.keyValueDeps={}}; _.extend(ReactiveMap.prototype,{set:function(a,b){b=stringify(b);var d="undefined";_.has(this.keys,a)&&(d=this.keys[a]);if(b!==d){this.keys[a]=b;var f=this.keyDeps[a];f&&f.changed();this.keyValueDeps[a]&&((d=this.keyValueDeps[a][d])&&d.changed(),(d=this.keyValueDeps[a][b])&&d.changed())}},setDefault:function(a,b){void 0===this.keys[a]&&this.set(a,b)},get:function(a){this._ensureKey(a);this.keyDeps[a].depend();return parse(this.keys[a])},equals:function(a,b){var d=this,f=Package["mongo-livedata"]&& Meteor.Collection.ObjectID;if(!("string"===typeof b||"number"===typeof b||"boolean"===typeof b||"undefined"===typeof b||b instanceof Date||f&&b instanceof f)&&null!==b)throw Error("ReactiveMap.equals: value must be scalar");var l=stringify(b);if(Meteor.active&&(d._ensureKey(a),_.has(d.keyValueDeps[a],l)||(d.keyValueDeps[a][l]=new Meteor.Dependency),d.keyValueDeps[a][l].depend()))Meteor.onInvalidate(function(){d.keyValueDeps[a][l].hasDependents()||delete d.keyValueDeps[a][l]});f=void 0;_.has(d.keys, a)&&(f=parse(d.keys[a]));return EJSON.equals(f,b)},_ensureKey:function(a){a in this.keyDeps||(this.keyDeps[a]=new Meteor.Dependency,this.keyValueDeps[a]={})},getMigrationData:function(){return this.keys}});ReactiveVar=function(a,b){if(!(this instanceof ReactiveVar))return new ReactiveVar(a,b);this.curValue=a;this.equalsFunc=b;this.dep=new Meteor.Dependency};ReactiveVar._isEqual=function(a,b){return a!==b?!1:!a||"number"===typeof a||"boolean"===typeof a||"string"===typeof a}; ReactiveVar.prototype.get=function(){Meteor.active&&this.dep.depend();return this.curValue};ReactiveVar.prototype.set=function(a){(this.equalsFunc||ReactiveVar._isEqual)(this.curValue,a)||(this.curValue=a,this.dep.changed())};ReactiveVar.prototype.toString=function(){return"ReactiveVar{"+this.get()+"}"};ReactiveVar.prototype._numListeners=function(){var a=0,b;for(b in this.dep._dependentsById)a++;return a}; ReactiveObject=function(a){var b;this._definePrivateProperty("_items",{});this._definePrivateProperty("_itemsMeteor",{});b=this;_.isArray(a)&&_.each(a,function(a){return b.defineProperty(a,void 0)});_.isObject(a)&&_.each(a,function(a,f){return b.defineProperty(f,a)})}; ReactiveObject.prototype.wrapArrayMethods=function(a,b){var d=this;_.each("pop push reverse shift sort slice unshift splice".split(" "),function(f){b[f]=function(){d._itemsMeteor[a].changed();return Array.prototype[f].apply(this,arguments)}});b.clean=function(){return _.filter(this,function(a){return!Match.test(a,Function)})};return b}; ReactiveObject.prototype.defineProperty=function(a,b){Object.defineProperty(this,a,{configurable:!0,enumerable:!0,get:_.bind(this._propertyGet,this,a),set:_.bind(this._propertySet,this,a)});this[a]=b;return this};ReactiveObject.prototype.undefineProperty=function(a){var b;b=this._itemsMeteor[a];delete this[a];delete this._items[a];delete this._itemsMeteor[a];b&&b.changed();return this};ReactiveObject.prototype.clone=function(){return new ReactiveObject(_.clone(this._items))}; ReactiveObject.prototype.equals=function(a){return null!=a&&a instanceof ReactiveObject&&_.isEqual(a._items,this._items)};ReactiveObject.prototype.typeName=function(){return"reactive-object"};ReactiveObject.prototype.toJSONValue=function(){return EJSON.toJSONValue(this._items)}; ReactiveObject.prototype._propertySet=function(a,b){var d,f;_.isArray(b)&&(b=this.wrapArrayMethods(a,b));this._items[a]=b;null==(d=this._itemsMeteor)[a]&&(d[a]=new Meteor.Dependency);null!=(f=this._itemsMeteor[a])&&f.changed();return this._items[a]};ReactiveObject.prototype._propertyGet=function(a){this._itemsMeteor[a].depend();return this._items[a]}; ReactiveObject.prototype._definePrivateProperty=function(a,b){return Object.defineProperty(this,a,{configurable:!0,enumerable:!1,writable:!0,value:b})};EJSON.addType("reactive-object",function(a){return new ReactiveObject(a)});
node_modules/flow-interfaces/interfaces/react-router.d.js
rekyyang/ArtificalLiverCloud
declare module 'react-router' { declare interface ReactRouter extends ReactClass { IndexRoute: ReactClass; Link: ReactClass; Redirect: ReactClass; Route: ReactClass; Router: ReactClass; browserHistory: any; match: Function; RouterContext: ReactClass; } declare var exports: ReactRouter; } declare module 'react-router/lib/PatternUtils' { declare var exports: any; } declare module 'history/lib/createBrowserHistory' { declare var exports: any; }
src/components/ProductData.js
nopphawitKar/petMarket
import React, { Component } from 'react'; class ProductBox extends Component { render() { return ( <div> <div><a>Name:</a> {this.props.data.name}</div> <div><a>Price:</a> {this.props.data.price} $</div> <div><a>Description:</a> <div>{this.props.data.description}</div></div> </div> ); } } export default ProductBox;
packages/lore-hook-dialog-material-ui/src/index.js
lore/lore-forms
/* eslint no-param-reassign: "off" */ import React from 'react'; import _ from 'lodash'; import defaultConfig from './config'; export default { defaults: { dialog: defaultConfig }, load: function(lore) { const { muiTheme, domElementId, buildDialogContainer, renderDialogToDom } = lore.config.dialog; if (!muiTheme) { throw new Error('Must provide muiTheme in config/dialog.js in order to use lore-hook-dialog-material-ui'); } lore.dialog = {}; lore.dialog.show = function(component, options = {}) { const dialog = _.isFunction(component) ? component() : component; if (!dialog) { throw new Error('Must provide a component to lore.dialog.show'); } const DialogContainer = buildDialogContainer(lore, options); // Find the proper DOM element and mount the dialog to it renderDialogToDom(options.domElementId || domElementId, ( <DialogContainer dialog={dialog} /> )); } } };
index.js
arnef/ligatool-hamburg
import React, { Component } from 'react'; import { AppRegistry, Platform, StatusBar } from 'react-native'; import App from './app/App'; class androidapp extends Component { componentWillMount() { if (Platform.OS === 'android' && Platform.Version >= 21) { StatusBar.setTranslucent(true); StatusBar.setBackgroundColor('rgba(0,0,0,.3)'); } else if (Platform.OS === 'ios') { StatusBar.setBarStyle('dark-content'); } } render() { return <App />; } } AppRegistry.registerComponent('arnefeilligatool', () => androidapp);
src/Parser/Priest/Holy/Modules/PriestCore/Divinity.js
hasseboulen/WoWAnalyzer
import React from 'react'; import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox'; import SpellIcon from 'common/SpellIcon'; import { formatPercentage, formatNumber, formatThousands } from 'common/format'; // dependencies import Combatants from 'Parser/Core/Modules/Combatants'; import SPELLS from 'common/SPELLS'; import Analyzer from 'Parser/Core/Analyzer'; import calculateEffectiveHealing from 'Parser/Core/calculateEffectiveHealing'; import { ABILITIES_AFFECTED_BY_HEALING_INCREASES } from '../../Constants'; const DIVINITY_HEALING_INCREASE = 0.15; class Divinity extends Analyzer { static dependencies = { combatants: Combatants, } healing = 0; on_initialized() { this.active = this.combatants.selected.hasTalent(SPELLS.DIVINITY_TALENT.id); } on_byPlayer_heal(event) { this.parseHeal(event); } on_byPlayer_absorbed(event) { this.parseHeal(event); } parseHeal(event) { const spellId = event.ability.guid; if (ABILITIES_AFFECTED_BY_HEALING_INCREASES.indexOf(spellId) === -1) { return; } if (!this.combatants.selected.hasBuff(SPELLS.DIVINITY_BUFF.id, event.timestamp)) { return; } this.healing += calculateEffectiveHealing(event, DIVINITY_HEALING_INCREASE); } statistic() { // return this.active && ( <StatisticBox icon={<SpellIcon id={SPELLS.DIVINITY_TALENT.id} />} value={`${((this.combatants.selected.getBuffUptime(SPELLS.DIVINITY_BUFF.id) / this.owner.fightDuration) * 100).toFixed(1)} %`} label={( <dfn data-tip={`The effective healing contributed by Divinity was ${formatThousands(this.healing)} / ${formatPercentage(this.owner.getPercentageOfTotalHealingDone(this.healing))} % / ${formatNumber(this.healing / this.owner.fightDuration * 1000)} HPS.`}> Divinity uptime </dfn> )} /> ); // } statisticOrder = STATISTIC_ORDER.OPTIONAL(); } export default Divinity;
source/setup/reducers/routing.js
buttercup-pw/buttercup-browser-extension
import { routerReducer } from "react-router-redux"; export default routerReducer;
src/routes/watson/Utterance/Utterance.js
hmeinertrita/MyPlanetGirlGuides
import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Utterance.css'; // import { Tweet } from 'react-twitter-widgets'; // var TweetWidget = require('react-twitter-widgets').Tweet; class Utterance extends React.Component { constructor(props) { super(props); this.state = {}; } render() { let utterance = this.props.utterance; console.log('utterance', utterance); let utteranceTone = utterance.tones[0] let utteranceTones = utterance.tones.map(function(tone, i){ return ( <li key={i}> <span>Score: {tone.score}</span> <br></br> <span>Tone: {tone.tone_id}</span> </li> ) }); // console.log(utteranceTones) // console.log('utterance', utterance.tones); return ( <li style={{ "padding": '5px' }}> <div>Text: {utterance.utterance_text}</div> <ul>{utteranceTones}</ul> </li> ); } } export default withStyles(s)(Utterance);
node_modules/react-icons/io/android-list.js
bairrada97/festival
import React from 'react' import Icon from 'react-icon-base' const IoAndroidList = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m31.9 5c1.7 0 3.1 1.4 3.1 3.1v23.8c0 1.7-1.4 3.1-3.1 3.1h-23.8c-1.7 0-3.1-1.4-3.1-3.1v-23.8c0-1.7 1.4-3.1 3.1-3.1h23.8z m-8.1 23.8v-3.8h-12.5v3.8h12.5z m5-6.9v-3.8h-17.5v3.8h17.5z m0-6.9v-3.7h-17.5v3.7h17.5z"/></g> </Icon> ) export default IoAndroidList
src/app/components/Main.js
arraqib/react-weather
import React from 'react'; import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; import Paper from 'material-ui/Paper' import AppBar from 'material-ui/AppBar'; import IconButton from 'material-ui/IconButton'; import IconMenu from 'material-ui/IconMenu'; import MenuItem from 'material-ui/MenuItem'; import NavigationMenus from 'material-ui/svg-icons/navigation/menu'; import injectTapEventPlugin from 'react-tap-event-plugin'; import Nav from './Nav'; // Needed for onTouchTap // http://stackoverflow.com/a/34015469/988941 injectTapEventPlugin(); const Main = (props) => { let paperStyle = { width: "90%", minHeight: 600, margin: '0 auto', textAlign: 'center' } let navLink = ( <IconMenu iconButtonElement={<IconButton iconStyle={{color: '#ffffff'}}><NavigationMenus /></IconButton>}> <Nav /> </IconMenu>) return ( <MuiThemeProvider style={{paddingTop: 0}}> <div> <Paper style={paperStyle}> <AppBar style={{textAlign: 'left'}} title="Weather App" iconElementLeft={navLink}/> {props.children} </Paper> </div> </MuiThemeProvider> ) } export default Main;
local-cli/templates/HelloWorld/__tests__/index.ios.js
callstack-io/react-native
import 'react-native'; import React from 'react'; import Index from '../index.ios.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
tests/react/useCallback_hook.js
gabelevi/flow
// @flow import React from 'react'; { React.useCallback(); // Error: function requires another argument. } { const callback = React.useCallback(() => 123); const num: number = callback(); const str: string = callback();// Error: number is incompatible with string. } { const callback = React.useCallback((num: number, str: string) => { (num: number); (str: string); }); callback(123, 'abc'); // Ok callback(true); // Error: function requires another argument. callback('123', 'abc'); // Error: string is incompatible with number. }
docs/app/Examples/elements/Input/Variations/InputExampleIconChild.js
aabustamante/Semantic-UI-React
import React from 'react' import { Icon, Input } from 'semantic-ui-react' const InputExampleIconChild = () => ( <div> <Input icon placeholder='Search...'> <input /> <Icon name='search' /> </Input> <br /> <br /> <Input iconPosition='left' placeholder='Email'> <Icon name='at' /> <input /> </Input> </div> ) export default InputExampleIconChild
packages/material-ui-icons/src/DragHandleSharp.js
Kagami/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M20 9H4v2h16V9zM4 15h16v-2H4v2z" /></React.Fragment> , 'DragHandleSharp');
app/javascript/mastodon/features/compose/components/character_counter.js
im-in-space/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { length } from 'stringz'; export default class CharacterCounter extends React.PureComponent { static propTypes = { text: PropTypes.string.isRequired, max: PropTypes.number.isRequired, }; checkRemainingText (diff) { if (diff < 0) { return <span className='character-counter character-counter--over'>{diff}</span>; } return <span className='character-counter'>{diff}</span>; } render () { const diff = this.props.max - length(this.props.text); return this.checkRemainingText(diff); } }
src/svg-icons/device/access-alarm.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceAccessAlarm = (props) => ( <SvgIcon {...props}> <path d="M22 5.72l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM7.88 3.39L6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM12.5 8H11v6l4.75 2.85.75-1.23-4-2.37V8zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9c4.97 0 9-4.03 9-9s-4.03-9-9-9zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z"/> </SvgIcon> ); DeviceAccessAlarm = pure(DeviceAccessAlarm); DeviceAccessAlarm.displayName = 'DeviceAccessAlarm'; DeviceAccessAlarm.muiName = 'SvgIcon'; export default DeviceAccessAlarm;
ajax/libs/cyclejs-core/0.20.0/cycle.min.js
emijrp/cdnjs
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Cycle=f()}})(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){(function(global){"use strict";if(global._babelPolyfill){throw new Error("only one instance of babel/polyfill is allowed")}global._babelPolyfill=true;require("core-js/shim");require("regenerator-babel/runtime")}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"core-js/shim":2,"regenerator-babel/runtime":3}],2:[function(require,module,exports){!function(global,framework,undefined){"use strict";var OBJECT="Object",FUNCTION="Function",ARRAY="Array",STRING="String",NUMBER="Number",REGEXP="RegExp",DATE="Date",MAP="Map",SET="Set",WEAKMAP="WeakMap",WEAKSET="WeakSet",SYMBOL="Symbol",PROMISE="Promise",MATH="Math",ARGUMENTS="Arguments",PROTOTYPE="prototype",CONSTRUCTOR="constructor",TO_STRING="toString",TO_STRING_TAG=TO_STRING+"Tag",TO_LOCALE="toLocaleString",HAS_OWN="hasOwnProperty",FOR_EACH="forEach",ITERATOR="iterator",FF_ITERATOR="@@"+ITERATOR,PROCESS="process",CREATE_ELEMENT="createElement",Function=global[FUNCTION],Object=global[OBJECT],Array=global[ARRAY],String=global[STRING],Number=global[NUMBER],RegExp=global[REGEXP],Date=global[DATE],Map=global[MAP],Set=global[SET],WeakMap=global[WEAKMAP],WeakSet=global[WEAKSET],Symbol=global[SYMBOL],Math=global[MATH],TypeError=global.TypeError,RangeError=global.RangeError,setTimeout=global.setTimeout,setImmediate=global.setImmediate,clearImmediate=global.clearImmediate,parseInt=global.parseInt,isFinite=global.isFinite,process=global[PROCESS],nextTick=process&&process.nextTick,document=global.document,html=document&&document.documentElement,navigator=global.navigator,define=global.define,console=global.console||{},ArrayProto=Array[PROTOTYPE],ObjectProto=Object[PROTOTYPE],FunctionProto=Function[PROTOTYPE],Infinity=1/0,DOT=".";function isObject(it){return it!==null&&(typeof it=="object"||typeof it=="function")}function isFunction(it){return typeof it=="function"}var isNative=ctx(/./.test,/\[native code\]\s*\}\s*$/,1);var toString=ObjectProto[TO_STRING];function setToStringTag(it,tag,stat){if(it&&!has(it=stat?it:it[PROTOTYPE],SYMBOL_TAG))hidden(it,SYMBOL_TAG,tag)}function cof(it){return toString.call(it).slice(8,-1)}function classof(it){var O,T;return it==undefined?it===undefined?"Undefined":"Null":typeof(T=(O=Object(it))[SYMBOL_TAG])=="string"?T:cof(O)}var call=FunctionProto.call,apply=FunctionProto.apply,REFERENCE_GET;function part(){var fn=assertFunction(this),length=arguments.length,args=Array(length),i=0,_=path._,holder=false;while(length>i)if((args[i]=arguments[i++])===_)holder=true;return function(){var that=this,_length=arguments.length,i=0,j=0,_args;if(!holder&&!_length)return invoke(fn,args,that);_args=args.slice();if(holder)for(;length>i;i++)if(_args[i]===_)_args[i]=arguments[j++];while(_length>j)_args.push(arguments[j++]);return invoke(fn,_args,that)}}function ctx(fn,that,length){assertFunction(fn);if(~length&&that===undefined)return fn;switch(length){case 1:return function(a){return fn.call(that,a)};case 2:return function(a,b){return fn.call(that,a,b)};case 3:return function(a,b,c){return fn.call(that,a,b,c)}}return function(){return fn.apply(that,arguments)}}function invoke(fn,args,that){var un=that===undefined;switch(args.length|0){case 0:return un?fn():fn.call(that);case 1:return un?fn(args[0]):fn.call(that,args[0]);case 2:return un?fn(args[0],args[1]):fn.call(that,args[0],args[1]);case 3:return un?fn(args[0],args[1],args[2]):fn.call(that,args[0],args[1],args[2]);case 4:return un?fn(args[0],args[1],args[2],args[3]):fn.call(that,args[0],args[1],args[2],args[3]);case 5:return un?fn(args[0],args[1],args[2],args[3],args[4]):fn.call(that,args[0],args[1],args[2],args[3],args[4])}return fn.apply(that,args)}var create=Object.create,getPrototypeOf=Object.getPrototypeOf,setPrototypeOf=Object.setPrototypeOf,defineProperty=Object.defineProperty,defineProperties=Object.defineProperties,getOwnDescriptor=Object.getOwnPropertyDescriptor,getKeys=Object.keys,getNames=Object.getOwnPropertyNames,getSymbols=Object.getOwnPropertySymbols,isFrozen=Object.isFrozen,has=ctx(call,ObjectProto[HAS_OWN],2),ES5Object=Object,Dict;function toObject(it){return ES5Object(assertDefined(it))}function returnIt(it){return it}function returnThis(){return this}function get(object,key){if(has(object,key))return object[key]}function ownKeys(it){assertObject(it);return getSymbols?getNames(it).concat(getSymbols(it)):getNames(it)}var assign=Object.assign||function(target,source){var T=Object(assertDefined(target)),l=arguments.length,i=1;while(l>i){var S=ES5Object(arguments[i++]),keys=getKeys(S),length=keys.length,j=0,key;while(length>j)T[key=keys[j++]]=S[key]}return T};function keyOf(object,el){var O=toObject(object),keys=getKeys(O),length=keys.length,index=0,key;while(length>index)if(O[key=keys[index++]]===el)return key}function array(it){return String(it).split(",")}var push=ArrayProto.push,unshift=ArrayProto.unshift,slice=ArrayProto.slice,splice=ArrayProto.splice,indexOf=ArrayProto.indexOf,forEach=ArrayProto[FOR_EACH];function createArrayMethod(type){var isMap=type==1,isFilter=type==2,isSome=type==3,isEvery=type==4,isFindIndex=type==6,noholes=type==5||isFindIndex;return function(callbackfn){var O=Object(assertDefined(this)),that=arguments[1],self=ES5Object(O),f=ctx(callbackfn,that,3),length=toLength(self.length),index=0,result=isMap?Array(length):isFilter?[]:undefined,val,res;for(;length>index;index++)if(noholes||index in self){val=self[index];res=f(val,index,O);if(type){if(isMap)result[index]=res;else if(res)switch(type){case 3:return true;case 5:return val;case 6:return index;case 2:result.push(val)}else if(isEvery)return false}}return isFindIndex?-1:isSome||isEvery?isEvery:result}}function createArrayContains(isContains){return function(el){var O=toObject(this),length=toLength(O.length),index=toIndex(arguments[1],length);if(isContains&&el!=el){for(;length>index;index++)if(sameNaN(O[index]))return isContains||index}else for(;length>index;index++)if(isContains||index in O){if(O[index]===el)return isContains||index}return!isContains&&-1}}function generic(A,B){return typeof A=="function"?A:B}var MAX_SAFE_INTEGER=9007199254740991,pow=Math.pow,abs=Math.abs,ceil=Math.ceil,floor=Math.floor,max=Math.max,min=Math.min,random=Math.random,trunc=Math.trunc||function(it){return(it>0?floor:ceil)(it)};function sameNaN(number){return number!=number}function toInteger(it){return isNaN(it)?0:trunc(it)}function toLength(it){return it>0?min(toInteger(it),MAX_SAFE_INTEGER):0}function toIndex(index,length){var index=toInteger(index);return index<0?max(index+length,0):min(index,length)}function lz(num){return num>9?num:"0"+num}function createReplacer(regExp,replace,isStatic){var replacer=isObject(replace)?function(part){return replace[part]}:replace;return function(it){return String(isStatic?it:this).replace(regExp,replacer)}}function createPointAt(toString){return function(pos){var s=String(assertDefined(this)),i=toInteger(pos),l=s.length,a,b;if(i<0||i>=l)return toString?"":undefined;a=s.charCodeAt(i);return a<55296||a>56319||i+1===l||(b=s.charCodeAt(i+1))<56320||b>57343?toString?s.charAt(i):a:toString?s.slice(i,i+2):(a-55296<<10)+(b-56320)+65536}}var REDUCE_ERROR="Reduce of empty object with no initial value";function assert(condition,msg1,msg2){if(!condition)throw TypeError(msg2?msg1+msg2:msg1)}function assertDefined(it){if(it==undefined)throw TypeError("Function called on null or undefined");return it}function assertFunction(it){assert(isFunction(it),it," is not a function!");return it}function assertObject(it){assert(isObject(it),it," is not an object!");return it}function assertInstance(it,Constructor,name){assert(it instanceof Constructor,name,": use the 'new' operator!")}function descriptor(bitmap,value){return{enumerable:!(bitmap&1),configurable:!(bitmap&2),writable:!(bitmap&4),value:value}}function simpleSet(object,key,value){object[key]=value;return object}function createDefiner(bitmap){return DESC?function(object,key,value){return defineProperty(object,key,descriptor(bitmap,value))}:simpleSet}function uid(key){return SYMBOL+"("+key+")_"+(++sid+random())[TO_STRING](36)}function getWellKnownSymbol(name,setter){return Symbol&&Symbol[name]||(setter?Symbol:safeSymbol)(SYMBOL+DOT+name)}var DESC=!!function(){try{return defineProperty({},"a",{get:function(){return 2}}).a==2}catch(e){}}(),sid=0,hidden=createDefiner(1),set=Symbol?simpleSet:hidden,safeSymbol=Symbol||uid;function assignHidden(target,src){for(var key in src)hidden(target,key,src[key]);return target}var SYMBOL_UNSCOPABLES=getWellKnownSymbol("unscopables"),ArrayUnscopables=ArrayProto[SYMBOL_UNSCOPABLES]||{},SYMBOL_TAG=getWellKnownSymbol(TO_STRING_TAG),SYMBOL_SPECIES=getWellKnownSymbol("species"),SYMBOL_ITERATOR;function setSpecies(C){if(DESC&&(framework||!isNative(C)))defineProperty(C,SYMBOL_SPECIES,{configurable:true,get:returnThis})}var NODE=cof(process)==PROCESS,core={},path=framework?global:core,old=global.core,exportGlobal,FORCED=1,GLOBAL=2,STATIC=4,PROTO=8,BIND=16,WRAP=32;function $define(type,name,source){var key,own,out,exp,isGlobal=type&GLOBAL,target=isGlobal?global:type&STATIC?global[name]:(global[name]||ObjectProto)[PROTOTYPE],exports=isGlobal?core:core[name]||(core[name]={});if(isGlobal)source=name;for(key in source){own=!(type&FORCED)&&target&&key in target&&(!isFunction(target[key])||isNative(target[key]));out=(own?target:source)[key];if(!framework&&isGlobal&&!isFunction(target[key]))exp=source[key];else if(type&BIND&&own)exp=ctx(out,global);else if(type&WRAP&&!framework&&target[key]==out){exp=function(param){return this instanceof out?new out(param):out(param)};exp[PROTOTYPE]=out[PROTOTYPE]}else exp=type&PROTO&&isFunction(out)?ctx(call,out):out;if(framework&&target&&!own){if(isGlobal)target[key]=out;else delete target[key]&&hidden(target,key,out)}if(exports[key]!=out)hidden(exports,key,exp)}}if(typeof module!="undefined"&&module.exports)module.exports=core;else if(isFunction(define)&&define.amd)define(function(){return core});else exportGlobal=true;if(exportGlobal||framework){core.noConflict=function(){global.core=old;return core};global.core=core}SYMBOL_ITERATOR=getWellKnownSymbol(ITERATOR);var ITER=safeSymbol("iter"),KEY=1,VALUE=2,Iterators={},IteratorPrototype={},BUGGY_ITERATORS="keys"in ArrayProto&&!("next"in[].keys());setIterator(IteratorPrototype,returnThis);function setIterator(O,value){hidden(O,SYMBOL_ITERATOR,value);FF_ITERATOR in ArrayProto&&hidden(O,FF_ITERATOR,value)}function createIterator(Constructor,NAME,next,proto){Constructor[PROTOTYPE]=create(proto||IteratorPrototype,{next:descriptor(1,next)});setToStringTag(Constructor,NAME+" Iterator")}function defineIterator(Constructor,NAME,value,DEFAULT){var proto=Constructor[PROTOTYPE],iter=get(proto,SYMBOL_ITERATOR)||get(proto,FF_ITERATOR)||DEFAULT&&get(proto,DEFAULT)||value;if(framework){setIterator(proto,iter);if(iter!==value){var iterProto=getPrototypeOf(iter.call(new Constructor));setToStringTag(iterProto,NAME+" Iterator",true);has(proto,FF_ITERATOR)&&setIterator(iterProto,returnThis)}}Iterators[NAME]=iter;Iterators[NAME+" Iterator"]=returnThis;return iter}function defineStdIterators(Base,NAME,Constructor,next,DEFAULT,IS_SET){function createIter(kind){return function(){return new Constructor(this,kind)}}createIterator(Constructor,NAME,next);var entries=createIter(KEY+VALUE),values=createIter(VALUE);if(DEFAULT==VALUE)values=defineIterator(Base,NAME,values,"values");else entries=defineIterator(Base,NAME,entries,"entries");if(DEFAULT){$define(PROTO+FORCED*BUGGY_ITERATORS,NAME,{entries:entries,keys:IS_SET?values:createIter(KEY),values:values})}}function iterResult(done,value){return{value:value,done:!!done}}function isIterable(it){var O=Object(it),Symbol=global[SYMBOL],hasExt=(Symbol&&Symbol[ITERATOR]||FF_ITERATOR)in O;return hasExt||SYMBOL_ITERATOR in O||has(Iterators,classof(O))}function getIterator(it){var Symbol=global[SYMBOL],ext=it[Symbol&&Symbol[ITERATOR]||FF_ITERATOR],getIter=ext||it[SYMBOL_ITERATOR]||Iterators[classof(it)];return assertObject(getIter.call(it))}function stepCall(fn,value,entries){return entries?invoke(fn,value):fn(value)}function checkDangerIterClosing(fn){var danger=true;var O={next:function(){throw 1},"return":function(){danger=false}};O[SYMBOL_ITERATOR]=returnThis;try{fn(O)}catch(e){}return danger}function closeIterator(iterator){var ret=iterator["return"];if(ret!==undefined)ret.call(iterator)}function safeIterClose(exec,iterator){try{exec(iterator)}catch(e){closeIterator(iterator);throw e}}function forOf(iterable,entries,fn,that){safeIterClose(function(iterator){var f=ctx(fn,that,entries?2:1),step;while(!(step=iterator.next()).done)if(stepCall(f,step.value,entries)===false){return closeIterator(iterator)}},getIterator(iterable))}!function(TAG,SymbolRegistry,AllSymbols,setter){if(!isNative(Symbol)){Symbol=function(description){assert(!(this instanceof Symbol),SYMBOL+" is not a "+CONSTRUCTOR);var tag=uid(description),sym=set(create(Symbol[PROTOTYPE]),TAG,tag);AllSymbols[tag]=sym;DESC&&setter&&defineProperty(ObjectProto,tag,{configurable:true,set:function(value){hidden(this,tag,value)}});return sym};hidden(Symbol[PROTOTYPE],TO_STRING,function(){return this[TAG]})}$define(GLOBAL+WRAP,{Symbol:Symbol});var symbolStatics={"for":function(key){return has(SymbolRegistry,key+="")?SymbolRegistry[key]:SymbolRegistry[key]=Symbol(key)},iterator:SYMBOL_ITERATOR||getWellKnownSymbol(ITERATOR),keyFor:part.call(keyOf,SymbolRegistry),species:SYMBOL_SPECIES,toStringTag:SYMBOL_TAG=getWellKnownSymbol(TO_STRING_TAG,true),unscopables:SYMBOL_UNSCOPABLES,pure:safeSymbol,set:set,useSetter:function(){setter=true},useSimple:function(){setter=false}};forEach.call(array("hasInstance,isConcatSpreadable,match,replace,search,split,toPrimitive"),function(it){symbolStatics[it]=getWellKnownSymbol(it)});$define(STATIC,SYMBOL,symbolStatics);setToStringTag(Symbol,SYMBOL);$define(STATIC+FORCED*!isNative(Symbol),OBJECT,{getOwnPropertyNames:function(it){var names=getNames(toObject(it)),result=[],key,i=0;while(names.length>i)has(AllSymbols,key=names[i++])||result.push(key);return result},getOwnPropertySymbols:function(it){var names=getNames(toObject(it)),result=[],key,i=0;while(names.length>i)has(AllSymbols,key=names[i++])&&result.push(AllSymbols[key]);return result}});setToStringTag(Math,MATH,true);setToStringTag(global.JSON,"JSON",true)}(safeSymbol("tag"),{},{},true);!function(){var objectStatic={assign:assign,is:function(x,y){return x===y?x!==0||1/x===1/y:x!=x&&y!=y}};"__proto__"in ObjectProto&&function(buggy,set){try{set=ctx(call,getOwnDescriptor(ObjectProto,"__proto__").set,2);set({},ArrayProto)}catch(e){buggy=true}objectStatic.setPrototypeOf=setPrototypeOf=setPrototypeOf||function(O,proto){assertObject(O);assert(proto===null||isObject(proto),proto,": can't set as prototype!");if(buggy)O.__proto__=proto;else set(O,proto);return O}}();$define(STATIC,OBJECT,objectStatic)}();!function(tmp){tmp[SYMBOL_TAG]=DOT;if(cof(tmp)!=DOT)hidden(ObjectProto,TO_STRING,function(){return"[object "+classof(this)+"]"})}({});!function(){function wrapObjectMethod(key,MODE){var fn=Object[key],exp=core[OBJECT][key],f=0,o={};if(!exp||isNative(exp)){o[key]=MODE==1?function(it){return isObject(it)?fn(it):it}:MODE==2?function(it){return isObject(it)?fn(it):true}:MODE==3?function(it){return isObject(it)?fn(it):false}:MODE==4?function(it,key){return fn(toObject(it),key)}:function(it){return fn(toObject(it))};try{fn(DOT)}catch(e){f=1}$define(STATIC+FORCED*f,OBJECT,o)}}wrapObjectMethod("freeze",1);wrapObjectMethod("seal",1);wrapObjectMethod("preventExtensions",1);wrapObjectMethod("isFrozen",2);wrapObjectMethod("isSealed",2);wrapObjectMethod("isExtensible",3);wrapObjectMethod("getOwnPropertyDescriptor",4);wrapObjectMethod("getPrototypeOf");wrapObjectMethod("keys");wrapObjectMethod("getOwnPropertyNames")}();!function(NAME){NAME in FunctionProto||DESC&&defineProperty(FunctionProto,NAME,{configurable:true,get:function(){var match=String(this).match(/^\s*function ([^ (]*)/),name=match?match[1]:"";has(this,NAME)||defineProperty(this,NAME,descriptor(5,name));return name},set:function(value){has(this,NAME)||defineProperty(this,NAME,descriptor(0,value))}})}("name");Number("0o1")&&Number("0b1")||function(_Number,NumberProto){function toNumber(it){if(isObject(it))it=toPrimitive(it);if(typeof it=="string"&&it.length>2&&it.charCodeAt(0)==48){var binary=false;switch(it.charCodeAt(1)){case 66:case 98:binary=true;case 79:case 111:return parseInt(it.slice(2),binary?2:8)}}return+it}function toPrimitive(it){var fn,val;if(isFunction(fn=it.valueOf)&&!isObject(val=fn.call(it)))return val;if(isFunction(fn=it[TO_STRING])&&!isObject(val=fn.call(it)))return val;throw TypeError("Can't convert object to number")}Number=function Number(it){return this instanceof Number?new _Number(toNumber(it)):toNumber(it)};forEach.call(DESC?getNames(_Number):array("MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY"),function(key){key in Number||defineProperty(Number,key,getOwnDescriptor(_Number,key))});Number[PROTOTYPE]=NumberProto;NumberProto[CONSTRUCTOR]=Number;hidden(global,NUMBER,Number)}(Number,Number[PROTOTYPE]);!function(isInteger){$define(STATIC,NUMBER,{EPSILON:pow(2,-52),isFinite:function(it){return typeof it=="number"&&isFinite(it)},isInteger:isInteger,isNaN:sameNaN,isSafeInteger:function(number){return isInteger(number)&&abs(number)<=MAX_SAFE_INTEGER},MAX_SAFE_INTEGER:MAX_SAFE_INTEGER,MIN_SAFE_INTEGER:-MAX_SAFE_INTEGER,parseFloat:parseFloat,parseInt:parseInt})}(Number.isInteger||function(it){return!isObject(it)&&isFinite(it)&&floor(it)===it});!function(){var E=Math.E,exp=Math.exp,log=Math.log,sqrt=Math.sqrt,sign=Math.sign||function(x){return(x=+x)==0||x!=x?x:x<0?-1:1};function asinh(x){return!isFinite(x=+x)||x==0?x:x<0?-asinh(-x):log(x+sqrt(x*x+1))}function expm1(x){return(x=+x)==0?x:x>-1e-6&&x<1e-6?x+x*x/2:exp(x)-1}$define(STATIC,MATH,{acosh:function(x){return(x=+x)<1?NaN:isFinite(x)?log(x/E+sqrt(x+1)*sqrt(x-1)/E)+1:x},asinh:asinh,atanh:function(x){return(x=+x)==0?x:log((1+x)/(1-x))/2},cbrt:function(x){return sign(x=+x)*pow(abs(x),1/3)},clz32:function(x){return(x>>>=0)?32-x[TO_STRING](2).length:32},cosh:function(x){return(exp(x=+x)+exp(-x))/2},expm1:expm1,fround:function(x){return new Float32Array([x])[0]},hypot:function(value1,value2){var sum=0,len1=arguments.length,len2=len1,args=Array(len1),larg=-Infinity,arg;while(len1--){arg=args[len1]=+arguments[len1];if(arg==Infinity||arg==-Infinity)return Infinity;if(arg>larg)larg=arg}larg=arg||1;while(len2--)sum+=pow(args[len2]/larg,2);return larg*sqrt(sum)},imul:function(x,y){var UInt16=65535,xn=+x,yn=+y,xl=UInt16&xn,yl=UInt16&yn;return 0|xl*yl+((UInt16&xn>>>16)*yl+xl*(UInt16&yn>>>16)<<16>>>0)},log1p:function(x){return(x=+x)>-1e-8&&x<1e-8?x-x*x/2:log(1+x)},log10:function(x){return log(x)/Math.LN10},log2:function(x){return log(x)/Math.LN2},sign:sign,sinh:function(x){return abs(x=+x)<1?(expm1(x)-expm1(-x))/2:(exp(x-1)-exp(-x-1))*(E/2)},tanh:function(x){var a=expm1(x=+x),b=expm1(-x);return a==Infinity?1:b==Infinity?-1:(a-b)/(exp(x)+exp(-x))},trunc:trunc})}();!function(fromCharCode){function assertNotRegExp(it){if(cof(it)==REGEXP)throw TypeError()}$define(STATIC,STRING,{fromCodePoint:function(x){var res=[],len=arguments.length,i=0,code;while(len>i){code=+arguments[i++];if(toIndex(code,1114111)!==code)throw RangeError(code+" is not a valid code point");res.push(code<65536?fromCharCode(code):fromCharCode(((code-=65536)>>10)+55296,code%1024+56320))}return res.join("")},raw:function(callSite){var raw=toObject(callSite.raw),len=toLength(raw.length),sln=arguments.length,res=[],i=0;while(len>i){res.push(String(raw[i++]));if(i<sln)res.push(String(arguments[i]))}return res.join("")}});$define(PROTO,STRING,{codePointAt:createPointAt(false),endsWith:function(searchString){assertNotRegExp(searchString);var that=String(assertDefined(this)),endPosition=arguments[1],len=toLength(that.length),end=endPosition===undefined?len:min(toLength(endPosition),len);searchString+="";return that.slice(end-searchString.length,end)===searchString},includes:function(searchString){assertNotRegExp(searchString);return!!~String(assertDefined(this)).indexOf(searchString,arguments[1])},repeat:function(count){var str=String(assertDefined(this)),res="",n=toInteger(count);if(0>n||n==Infinity)throw RangeError("Count can't be negative");for(;n>0;(n>>>=1)&&(str+=str))if(n&1)res+=str;return res},startsWith:function(searchString){assertNotRegExp(searchString);var that=String(assertDefined(this)),index=toLength(min(arguments[1],that.length));searchString+="";return that.slice(index,index+searchString.length)===searchString}})}(String.fromCharCode);!function(){$define(STATIC+FORCED*checkDangerIterClosing(Array.from),ARRAY,{from:function(arrayLike){var O=Object(assertDefined(arrayLike)),mapfn=arguments[1],mapping=mapfn!==undefined,f=mapping?ctx(mapfn,arguments[2],2):undefined,index=0,length,result,step;if(isIterable(O)){result=new(generic(this,Array));safeIterClose(function(iterator){for(;!(step=iterator.next()).done;index++){result[index]=mapping?f(step.value,index):step.value}},getIterator(O))}else{result=new(generic(this,Array))(length=toLength(O.length));for(;length>index;index++){result[index]=mapping?f(O[index],index):O[index]}}result.length=index;return result}});$define(STATIC,ARRAY,{of:function(){var index=0,length=arguments.length,result=new(generic(this,Array))(length);while(length>index)result[index]=arguments[index++];result.length=length;return result}});setSpecies(Array)}();!function(){$define(PROTO,ARRAY,{copyWithin:function(target,start){var O=Object(assertDefined(this)),len=toLength(O.length),to=toIndex(target,len),from=toIndex(start,len),end=arguments[2],fin=end===undefined?len:toIndex(end,len),count=min(fin-from,len-to),inc=1;if(from<to&&to<from+count){inc=-1;from=from+count-1;to=to+count-1}while(count-->0){if(from in O)O[to]=O[from];else delete O[to];to+=inc;from+=inc}return O},fill:function(value){var O=Object(assertDefined(this)),length=toLength(O.length),index=toIndex(arguments[1],length),end=arguments[2],endPos=end===undefined?length:toIndex(end,length);while(endPos>index)O[index++]=value;return O},find:createArrayMethod(5),findIndex:createArrayMethod(6)});if(framework){forEach.call(array("find,findIndex,fill,copyWithin,entries,keys,values"),function(it){ArrayUnscopables[it]=true});SYMBOL_UNSCOPABLES in ArrayProto||hidden(ArrayProto,SYMBOL_UNSCOPABLES,ArrayUnscopables)}}();!function(at){defineStdIterators(Array,ARRAY,function(iterated,kind){set(this,ITER,{o:toObject(iterated),i:0,k:kind})},function(){var iter=this[ITER],O=iter.o,kind=iter.k,index=iter.i++;if(!O||index>=O.length){iter.o=undefined;return iterResult(1)}if(kind==KEY)return iterResult(0,index);if(kind==VALUE)return iterResult(0,O[index]);return iterResult(0,[index,O[index]])},VALUE);Iterators[ARGUMENTS]=Iterators[ARRAY];defineStdIterators(String,STRING,function(iterated){set(this,ITER,{o:String(iterated),i:0})},function(){var iter=this[ITER],O=iter.o,index=iter.i,point;if(index>=O.length)return iterResult(1);point=at.call(O,index);iter.i+=point.length;return iterResult(0,point)})}(createPointAt(true));DESC&&!function(RegExpProto,_RegExp){if(!function(){try{return RegExp(/a/g,"i")=="/a/i"}catch(e){}}()){RegExp=function RegExp(pattern,flags){return new _RegExp(cof(pattern)==REGEXP&&flags!==undefined?pattern.source:pattern,flags)};forEach.call(getNames(_RegExp),function(key){key in RegExp||defineProperty(RegExp,key,{configurable:true,get:function(){return _RegExp[key]},set:function(it){_RegExp[key]=it}})});RegExpProto[CONSTRUCTOR]=RegExp;RegExp[PROTOTYPE]=RegExpProto;hidden(global,REGEXP,RegExp)}if(/./g.flags!="g")defineProperty(RegExpProto,"flags",{configurable:true,get:createReplacer(/^.*\/(\w*)$/,"$1")});setSpecies(RegExp)}(RegExp[PROTOTYPE],RegExp);isFunction(setImmediate)&&isFunction(clearImmediate)||function(ONREADYSTATECHANGE){var postMessage=global.postMessage,addEventListener=global.addEventListener,MessageChannel=global.MessageChannel,counter=0,queue={},defer,channel,port;setImmediate=function(fn){var args=[],i=1;while(arguments.length>i)args.push(arguments[i++]);queue[++counter]=function(){invoke(isFunction(fn)?fn:Function(fn),args)};defer(counter);return counter};clearImmediate=function(id){delete queue[id]};function run(id){if(has(queue,id)){var fn=queue[id];delete queue[id];fn()}}function listner(event){run(event.data)}if(NODE){defer=function(id){nextTick(part.call(run,id))}}else if(addEventListener&&isFunction(postMessage)&&!global.importScripts){defer=function(id){postMessage(id,"*")};addEventListener("message",listner,false)}else if(isFunction(MessageChannel)){channel=new MessageChannel;port=channel.port2;channel.port1.onmessage=listner;defer=ctx(port.postMessage,port,1)}else if(document&&ONREADYSTATECHANGE in document[CREATE_ELEMENT]("script")){defer=function(id){html.appendChild(document[CREATE_ELEMENT]("script"))[ONREADYSTATECHANGE]=function(){html.removeChild(this);run(id)}}}else{defer=function(id){setTimeout(run,0,id)}}}("onreadystatechange");$define(GLOBAL+BIND,{setImmediate:setImmediate,clearImmediate:clearImmediate});!function(Promise,test){isFunction(Promise)&&isFunction(Promise.resolve)&&Promise.resolve(test=new Promise(function(){}))==test||function(asap,RECORD){function isThenable(it){var then;if(isObject(it))then=it.then;return isFunction(then)?then:false}function handledRejectionOrHasOnRejected(promise){var record=promise[RECORD],chain=record.c,i=0,react;if(record.h)return true;while(chain.length>i){react=chain[i++];if(react.fail||handledRejectionOrHasOnRejected(react.P))return true}}function notify(record,reject){var chain=record.c;if(reject||chain.length)asap(function(){var promise=record.p,value=record.v,ok=record.s==1,i=0;if(reject&&!handledRejectionOrHasOnRejected(promise)){setTimeout(function(){if(!handledRejectionOrHasOnRejected(promise)){if(NODE){if(!process.emit("unhandledRejection",value,promise)){}}else if(isFunction(console.error)){console.error("Unhandled promise rejection",value)}}},1e3)}else while(chain.length>i)!function(react){var cb=ok?react.ok:react.fail,ret,then;try{if(cb){if(!ok)record.h=true;ret=cb===true?value:cb(value);if(ret===react.P){react.rej(TypeError(PROMISE+"-chain cycle"))}else if(then=isThenable(ret)){then.call(ret,react.res,react.rej)}else react.res(ret)}else react.rej(value)}catch(err){react.rej(err)}}(chain[i++]);chain.length=0})}function resolve(value){var record=this,then,wrapper;if(record.d)return;record.d=true;record=record.r||record;try{if(then=isThenable(value)){wrapper={r:record,d:false};then.call(value,ctx(resolve,wrapper,1),ctx(reject,wrapper,1))}else{record.v=value;record.s=1;notify(record)}}catch(err){reject.call(wrapper||{r:record,d:false},err)}}function reject(value){var record=this;if(record.d)return;record.d=true;record=record.r||record;record.v=value;record.s=2;notify(record,true)}function getConstructor(C){var S=assertObject(C)[SYMBOL_SPECIES];return S!=undefined?S:C}Promise=function(executor){assertFunction(executor);assertInstance(this,Promise,PROMISE);var record={p:this,c:[],s:0,d:false,v:undefined,h:false};hidden(this,RECORD,record);try{executor(ctx(resolve,record,1),ctx(reject,record,1))}catch(err){reject.call(record,err)}};assignHidden(Promise[PROTOTYPE],{then:function(onFulfilled,onRejected){var S=assertObject(assertObject(this)[CONSTRUCTOR])[SYMBOL_SPECIES];var react={ok:isFunction(onFulfilled)?onFulfilled:true,fail:isFunction(onRejected)?onRejected:false},P=react.P=new(S!=undefined?S:Promise)(function(resolve,reject){react.res=assertFunction(resolve);react.rej=assertFunction(reject)}),record=this[RECORD];record.c.push(react);record.s&&notify(record);return P},"catch":function(onRejected){return this.then(undefined,onRejected)}});assignHidden(Promise,{all:function(iterable){var Promise=getConstructor(this),values=[];return new Promise(function(resolve,reject){forOf(iterable,false,push,values);var remaining=values.length,results=Array(remaining);if(remaining)forEach.call(values,function(promise,index){Promise.resolve(promise).then(function(value){results[index]=value;--remaining||resolve(results)},reject)});else resolve(results)})},race:function(iterable){var Promise=getConstructor(this);return new Promise(function(resolve,reject){forOf(iterable,false,function(promise){Promise.resolve(promise).then(resolve,reject)})})},reject:function(r){return new(getConstructor(this))(function(resolve,reject){reject(r)})},resolve:function(x){return isObject(x)&&RECORD in x&&getPrototypeOf(x)===this[PROTOTYPE]?x:new(getConstructor(this))(function(resolve,reject){resolve(x)})}})}(nextTick||setImmediate,safeSymbol("record"));setToStringTag(Promise,PROMISE);setSpecies(Promise);$define(GLOBAL+FORCED*!isNative(Promise),{Promise:Promise})}(global[PROMISE]);!function(){var UID=safeSymbol("uid"),O1=safeSymbol("O1"),WEAK=safeSymbol("weak"),LEAK=safeSymbol("leak"),LAST=safeSymbol("last"),FIRST=safeSymbol("first"),SIZE=DESC?safeSymbol("size"):"size",uid=0,tmp={};function getCollection(C,NAME,methods,commonMethods,isMap,isWeak){var ADDER=isMap?"set":"add",proto=C&&C[PROTOTYPE],O={};function initFromIterable(that,iterable){if(iterable!=undefined)forOf(iterable,isMap,that[ADDER],that);return that}function fixSVZ(key,chain){var method=proto[key];if(framework)proto[key]=function(a,b){var result=method.call(this,a===0?0:a,b);return chain?this:result}}if(!isNative(C)||!(isWeak||!BUGGY_ITERATORS&&has(proto,FOR_EACH)&&has(proto,"entries"))){C=isWeak?function(iterable){assertInstance(this,C,NAME);set(this,UID,uid++);initFromIterable(this,iterable)}:function(iterable){var that=this;assertInstance(that,C,NAME);set(that,O1,create(null));set(that,SIZE,0);set(that,LAST,undefined);set(that,FIRST,undefined);initFromIterable(that,iterable)};assignHidden(assignHidden(C[PROTOTYPE],methods),commonMethods);isWeak||!DESC||defineProperty(C[PROTOTYPE],"size",{get:function(){return assertDefined(this[SIZE])}})}else{var Native=C,inst=new C,chain=inst[ADDER](isWeak?{}:-0,1),buggyZero;if(checkDangerIterClosing(function(O){new C(O)})){C=function(iterable){assertInstance(this,C,NAME);return initFromIterable(new Native,iterable)};C[PROTOTYPE]=proto;if(framework)proto[CONSTRUCTOR]=C}isWeak||inst[FOR_EACH](function(val,key){buggyZero=1/key===-Infinity});if(buggyZero){fixSVZ("delete");fixSVZ("has");isMap&&fixSVZ("get")}if(buggyZero||chain!==inst)fixSVZ(ADDER,true)}setToStringTag(C,NAME);setSpecies(C);O[NAME]=C;$define(GLOBAL+WRAP+FORCED*!isNative(C),O);isWeak||defineStdIterators(C,NAME,function(iterated,kind){set(this,ITER,{o:iterated,k:kind})},function(){var iter=this[ITER],kind=iter.k,entry=iter.l;while(entry&&entry.r)entry=entry.p;if(!iter.o||!(iter.l=entry=entry?entry.n:iter.o[FIRST])){iter.o=undefined;return iterResult(1)}if(kind==KEY)return iterResult(0,entry.k);if(kind==VALUE)return iterResult(0,entry.v);return iterResult(0,[entry.k,entry.v])},isMap?KEY+VALUE:VALUE,!isMap);return C}function fastKey(it,create){if(!isObject(it))return(typeof it=="string"?"S":"P")+it;if(isFrozen(it))return"F";if(!has(it,UID)){if(!create)return"E";hidden(it,UID,++uid)}return"O"+it[UID]}function getEntry(that,key){var index=fastKey(key),entry;if(index!="F")return that[O1][index];for(entry=that[FIRST];entry;entry=entry.n){if(entry.k==key)return entry; }}function def(that,key,value){var entry=getEntry(that,key),prev,index;if(entry)entry.v=value;else{that[LAST]=entry={i:index=fastKey(key,true),k:key,v:value,p:prev=that[LAST],n:undefined,r:false};if(!that[FIRST])that[FIRST]=entry;if(prev)prev.n=entry;that[SIZE]++;if(index!="F")that[O1][index]=entry}return that}var collectionMethods={clear:function(){for(var that=this,data=that[O1],entry=that[FIRST];entry;entry=entry.n){entry.r=true;if(entry.p)entry.p=entry.p.n=undefined;delete data[entry.i]}that[FIRST]=that[LAST]=undefined;that[SIZE]=0},"delete":function(key){var that=this,entry=getEntry(that,key);if(entry){var next=entry.n,prev=entry.p;delete that[O1][entry.i];entry.r=true;if(prev)prev.n=next;if(next)next.p=prev;if(that[FIRST]==entry)that[FIRST]=next;if(that[LAST]==entry)that[LAST]=prev;that[SIZE]--}return!!entry},forEach:function(callbackfn){var f=ctx(callbackfn,arguments[1],3),entry;while(entry=entry?entry.n:this[FIRST]){f(entry.v,entry.k,this);while(entry&&entry.r)entry=entry.p}},has:function(key){return!!getEntry(this,key)}};Map=getCollection(Map,MAP,{get:function(key){var entry=getEntry(this,key);return entry&&entry.v},set:function(key,value){return def(this,key===0?0:key,value)}},collectionMethods,true);Set=getCollection(Set,SET,{add:function(value){return def(this,value=value===0?0:value,value)}},collectionMethods);function defWeak(that,key,value){if(isFrozen(assertObject(key)))leakStore(that).set(key,value);else{has(key,WEAK)||hidden(key,WEAK,{});key[WEAK][that[UID]]=value}return that}function leakStore(that){return that[LEAK]||hidden(that,LEAK,new Map)[LEAK]}var weakMethods={"delete":function(key){if(!isObject(key))return false;if(isFrozen(key))return leakStore(this)["delete"](key);return has(key,WEAK)&&has(key[WEAK],this[UID])&&delete key[WEAK][this[UID]]},has:function(key){if(!isObject(key))return false;if(isFrozen(key))return leakStore(this).has(key);return has(key,WEAK)&&has(key[WEAK],this[UID])}};WeakMap=getCollection(WeakMap,WEAKMAP,{get:function(key){if(isObject(key)){if(isFrozen(key))return leakStore(this).get(key);if(has(key,WEAK))return key[WEAK][this[UID]]}},set:function(key,value){return defWeak(this,key,value)}},weakMethods,true,true);if(framework&&(new WeakMap).set(Object.freeze(tmp),7).get(tmp)!=7){forEach.call(array("delete,has,get,set"),function(key){var method=WeakMap[PROTOTYPE][key];WeakMap[PROTOTYPE][key]=function(a,b){if(isObject(a)&&isFrozen(a)){var result=leakStore(this)[key](a,b);return key=="set"?this:result}return method.call(this,a,b)}})}WeakSet=getCollection(WeakSet,WEAKSET,{add:function(value){return defWeak(this,value,true)}},weakMethods,false,true)}();!function(){function Enumerate(iterated){var keys=[],key;for(key in iterated)keys.push(key);set(this,ITER,{o:iterated,a:keys,i:0})}createIterator(Enumerate,OBJECT,function(){var iter=this[ITER],keys=iter.a,key;do{if(iter.i>=keys.length)return iterResult(1)}while(!((key=keys[iter.i++])in iter.o));return iterResult(0,key)});function wrap(fn){return function(it){assertObject(it);try{return fn.apply(undefined,arguments),true}catch(e){return false}}}function reflectGet(target,propertyKey){var receiver=arguments.length<3?target:arguments[2],desc=getOwnDescriptor(assertObject(target),propertyKey),proto;if(desc)return has(desc,"value")?desc.value:desc.get===undefined?undefined:desc.get.call(receiver);return isObject(proto=getPrototypeOf(target))?reflectGet(proto,propertyKey,receiver):undefined}function reflectSet(target,propertyKey,V){var receiver=arguments.length<4?target:arguments[3],ownDesc=getOwnDescriptor(assertObject(target),propertyKey),existingDescriptor,proto;if(!ownDesc){if(isObject(proto=getPrototypeOf(target))){return reflectSet(proto,propertyKey,V,receiver)}ownDesc=descriptor(0)}if(has(ownDesc,"value")){if(ownDesc.writable===false||!isObject(receiver))return false;existingDescriptor=getOwnDescriptor(receiver,propertyKey)||descriptor(0);existingDescriptor.value=V;return defineProperty(receiver,propertyKey,existingDescriptor),true}return ownDesc.set===undefined?false:(ownDesc.set.call(receiver,V),true)}var isExtensible=Object.isExtensible||returnIt;var reflect={apply:ctx(call,apply,3),construct:function(target,argumentsList){var proto=assertFunction(arguments.length<3?target:arguments[2])[PROTOTYPE],instance=create(isObject(proto)?proto:ObjectProto),result=apply.call(target,instance,argumentsList);return isObject(result)?result:instance},defineProperty:wrap(defineProperty),deleteProperty:function(target,propertyKey){var desc=getOwnDescriptor(assertObject(target),propertyKey);return desc&&!desc.configurable?false:delete target[propertyKey]},enumerate:function(target){return new Enumerate(assertObject(target))},get:reflectGet,getOwnPropertyDescriptor:function(target,propertyKey){return getOwnDescriptor(assertObject(target),propertyKey)},getPrototypeOf:function(target){return getPrototypeOf(assertObject(target))},has:function(target,propertyKey){return propertyKey in target},isExtensible:function(target){return!!isExtensible(assertObject(target))},ownKeys:ownKeys,preventExtensions:wrap(Object.preventExtensions||returnIt),set:reflectSet};if(setPrototypeOf)reflect.setPrototypeOf=function(target,proto){return setPrototypeOf(assertObject(target),proto),true};$define(GLOBAL,{Reflect:{}});$define(STATIC,"Reflect",reflect)}();!function(){$define(PROTO,ARRAY,{includes:createArrayContains(true)});$define(PROTO,STRING,{at:createPointAt(true)});function createObjectToArray(isEntries){return function(object){var O=toObject(object),keys=getKeys(object),length=keys.length,i=0,result=Array(length),key;if(isEntries)while(length>i)result[i]=[key=keys[i++],O[key]];else while(length>i)result[i]=O[keys[i++]];return result}}$define(STATIC,OBJECT,{getOwnPropertyDescriptors:function(object){var O=toObject(object),result={};forEach.call(ownKeys(O),function(key){defineProperty(result,key,descriptor(0,getOwnDescriptor(O,key)))});return result},values:createObjectToArray(false),entries:createObjectToArray(true)});$define(STATIC,REGEXP,{escape:createReplacer(/([\\\-[\]{}()*+?.,^$|])/g,"\\$1",true)})}();!function(REFERENCE){REFERENCE_GET=getWellKnownSymbol(REFERENCE+"Get",true);var REFERENCE_SET=getWellKnownSymbol(REFERENCE+SET,true),REFERENCE_DELETE=getWellKnownSymbol(REFERENCE+"Delete",true);$define(STATIC,SYMBOL,{referenceGet:REFERENCE_GET,referenceSet:REFERENCE_SET,referenceDelete:REFERENCE_DELETE});hidden(FunctionProto,REFERENCE_GET,returnThis);function setMapMethods(Constructor){if(Constructor){var MapProto=Constructor[PROTOTYPE];hidden(MapProto,REFERENCE_GET,MapProto.get);hidden(MapProto,REFERENCE_SET,MapProto.set);hidden(MapProto,REFERENCE_DELETE,MapProto["delete"])}}setMapMethods(Map);setMapMethods(WeakMap)}("reference");!function(arrayStatics){function setArrayStatics(keys,length){forEach.call(array(keys),function(key){if(key in ArrayProto)arrayStatics[key]=ctx(call,ArrayProto[key],length)})}setArrayStatics("pop,reverse,shift,keys,values,entries",1);setArrayStatics("indexOf,every,some,forEach,map,filter,find,findIndex,includes",3);setArrayStatics("join,slice,concat,push,splice,unshift,sort,lastIndexOf,"+"reduce,reduceRight,copyWithin,fill,turn");$define(STATIC,ARRAY,arrayStatics)}({});!function(NodeList){if(framework&&NodeList&&!(SYMBOL_ITERATOR in NodeList[PROTOTYPE])){hidden(NodeList[PROTOTYPE],SYMBOL_ITERATOR,Iterators[ARRAY])}Iterators.NodeList=Iterators[ARRAY]}(global.NodeList)}(typeof self!="undefined"&&self.Math===Math?self:Function("return this")(),true)},{}],3:[function(require,module,exports){(function(global){!function(global){"use strict";var hasOwn=Object.prototype.hasOwnProperty;var undefined;var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator||"@@iterator";var inModule=typeof module==="object";var runtime=global.regeneratorRuntime;if(runtime){if(inModule){module.exports=runtime}return}runtime=global.regeneratorRuntime=inModule?module.exports:{};function wrap(innerFn,outerFn,self,tryLocsList){return new Generator(innerFn,outerFn,self||null,tryLocsList||[])}runtime.wrap=wrap;function tryCatch(fn,obj,arg){try{return{type:"normal",arg:fn.call(obj,arg)}}catch(err){return{type:"throw",arg:err}}}var GenStateSuspendedStart="suspendedStart";var GenStateSuspendedYield="suspendedYield";var GenStateExecuting="executing";var GenStateCompleted="completed";var ContinueSentinel={};function GeneratorFunction(){}function GeneratorFunctionPrototype(){}var Gp=GeneratorFunctionPrototype.prototype=Generator.prototype;GeneratorFunction.prototype=Gp.constructor=GeneratorFunctionPrototype;GeneratorFunctionPrototype.constructor=GeneratorFunction;GeneratorFunction.displayName="GeneratorFunction";runtime.isGeneratorFunction=function(genFun){var ctor=typeof genFun==="function"&&genFun.constructor;return ctor?ctor===GeneratorFunction||(ctor.displayName||ctor.name)==="GeneratorFunction":false};runtime.mark=function(genFun){genFun.__proto__=GeneratorFunctionPrototype;genFun.prototype=Object.create(Gp);return genFun};runtime.async=function(innerFn,outerFn,self,tryLocsList){return new Promise(function(resolve,reject){var generator=wrap(innerFn,outerFn,self,tryLocsList);var callNext=step.bind(generator.next);var callThrow=step.bind(generator["throw"]);function step(arg){var record=tryCatch(this,null,arg);if(record.type==="throw"){reject(record.arg);return}var info=record.arg;if(info.done){resolve(info.value)}else{Promise.resolve(info.value).then(callNext,callThrow)}}callNext()})};function Generator(innerFn,outerFn,self,tryLocsList){var generator=outerFn?Object.create(outerFn.prototype):this;var context=new Context(tryLocsList);var state=GenStateSuspendedStart;function invoke(method,arg){if(state===GenStateExecuting){throw new Error("Generator is already running")}if(state===GenStateCompleted){return doneResult()}while(true){var delegate=context.delegate;if(delegate){var record=tryCatch(delegate.iterator[method],delegate.iterator,arg);if(record.type==="throw"){context.delegate=null;method="throw";arg=record.arg;continue}method="next";arg=undefined;var info=record.arg;if(info.done){context[delegate.resultName]=info.value;context.next=delegate.nextLoc}else{state=GenStateSuspendedYield;return info}context.delegate=null}if(method==="next"){if(state===GenStateSuspendedStart&&typeof arg!=="undefined"){throw new TypeError("attempt to send "+JSON.stringify(arg)+" to newborn generator")}if(state===GenStateSuspendedYield){context.sent=arg}else{delete context.sent}}else if(method==="throw"){if(state===GenStateSuspendedStart){state=GenStateCompleted;throw arg}if(context.dispatchException(arg)){method="next";arg=undefined}}else if(method==="return"){context.abrupt("return",arg)}state=GenStateExecuting;var record=tryCatch(innerFn,self,context);if(record.type==="normal"){state=context.done?GenStateCompleted:GenStateSuspendedYield;var info={value:record.arg,done:context.done};if(record.arg===ContinueSentinel){if(context.delegate&&method==="next"){arg=undefined}}else{return info}}else if(record.type==="throw"){state=GenStateCompleted;if(method==="next"){context.dispatchException(record.arg)}else{arg=record.arg}}}}generator.next=invoke.bind(generator,"next");generator["throw"]=invoke.bind(generator,"throw");generator["return"]=invoke.bind(generator,"return");return generator}Gp[iteratorSymbol]=function(){return this};Gp.toString=function(){return"[object Generator]"};function pushTryEntry(locs){var entry={tryLoc:locs[0]};if(1 in locs){entry.catchLoc=locs[1]}if(2 in locs){entry.finallyLoc=locs[2];entry.afterLoc=locs[3]}this.tryEntries.push(entry)}function resetTryEntry(entry){var record=entry.completion||{};record.type="normal";delete record.arg;entry.completion=record}function Context(tryLocsList){this.tryEntries=[{tryLoc:"root"}];tryLocsList.forEach(pushTryEntry,this);this.reset()}runtime.keys=function(object){var keys=[];for(var key in object){keys.push(key)}keys.reverse();return function next(){while(keys.length){var key=keys.pop();if(key in object){next.value=key;next.done=false;return next}}next.done=true;return next}};function values(iterable){if(iterable){var iteratorMethod=iterable[iteratorSymbol];if(iteratorMethod){return iteratorMethod.call(iterable)}if(typeof iterable.next==="function"){return iterable}if(!isNaN(iterable.length)){var i=-1,next=function next(){while(++i<iterable.length){if(hasOwn.call(iterable,i)){next.value=iterable[i];next.done=false;return next}}next.value=undefined;next.done=true;return next};return next.next=next}}return{next:doneResult}}runtime.values=values;function doneResult(){return{value:undefined,done:true}}Context.prototype={constructor:Context,reset:function(){this.prev=0;this.next=0;this.sent=undefined;this.done=false;this.delegate=null;this.tryEntries.forEach(resetTryEntry);for(var tempIndex=0,tempName;hasOwn.call(this,tempName="t"+tempIndex)||tempIndex<20;++tempIndex){this[tempName]=null}},stop:function(){this.done=true;var rootEntry=this.tryEntries[0];var rootRecord=rootEntry.completion;if(rootRecord.type==="throw"){throw rootRecord.arg}return this.rval},dispatchException:function(exception){if(this.done){throw exception}var context=this;function handle(loc,caught){record.type="throw";record.arg=exception;context.next=loc;return!!caught}for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];var record=entry.completion;if(entry.tryLoc==="root"){return handle("end")}if(entry.tryLoc<=this.prev){var hasCatch=hasOwn.call(entry,"catchLoc");var hasFinally=hasOwn.call(entry,"finallyLoc");if(hasCatch&&hasFinally){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}else if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else if(hasCatch){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}}else if(hasFinally){if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else{throw new Error("try statement without catch or finally")}}}},abrupt:function(type,arg){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc<=this.prev&&hasOwn.call(entry,"finallyLoc")&&this.prev<entry.finallyLoc){var finallyEntry=entry;break}}if(finallyEntry&&(type==="break"||type==="continue")&&finallyEntry.tryLoc<=arg&&arg<finallyEntry.finallyLoc){finallyEntry=null}var record=finallyEntry?finallyEntry.completion:{};record.type=type;record.arg=arg;if(finallyEntry){this.next=finallyEntry.finallyLoc}else{this.complete(record)}return ContinueSentinel},complete:function(record,afterLoc){if(record.type==="throw"){throw record.arg}if(record.type==="break"||record.type==="continue"){this.next=record.arg}else if(record.type==="return"){this.rval=record.arg;this.next="end"}else if(record.type==="normal"&&afterLoc){this.next=afterLoc}return ContinueSentinel},finish:function(finallyLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.finallyLoc===finallyLoc){return this.complete(entry.completion,entry.afterLoc)}}},"catch":function(tryLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc===tryLoc){var record=entry.completion;if(record.type==="throw"){var thrown=record.arg;resetTryEntry(entry)}return thrown}}throw new Error("illegal catch attempt")},delegateYield:function(iterable,resultName,nextLoc){this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc};return ContinueSentinel}}}(typeof global==="object"?global:typeof window==="object"?window:this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],4:[function(require,module,exports){module.exports=require("./lib/babel/polyfill")},{"./lib/babel/polyfill":1}],5:[function(require,module,exports){},{}],6:[function(require,module,exports){var process=module.exports={};var queue=[];var draining=false;function drainQueue(){if(draining){return}draining=true;var currentQueue;var len=queue.length;while(len){currentQueue=queue;queue=[];var i=-1;while(++i<len){currentQueue[i]()}len=queue.length}draining=false}process.nextTick=function(fun){queue.push(fun);if(!draining){setTimeout(drainQueue,0)}};process.title="browser";process.browser=true;process.env={};process.argv=[];process.version="";process.versions={};function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")};process.umask=function(){return 0}},{}],7:[function(require,module,exports){(function(process,global){(function(undefined){var objectTypes={"boolean":false,"function":true,object:true,number:false,string:false,undefined:false};var root=objectTypes[typeof window]&&window||this,freeExports=objectTypes[typeof exports]&&exports&&!exports.nodeType&&exports,freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports&&freeExports,freeGlobal=objectTypes[typeof global]&&global;if(freeGlobal&&(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal)){root=freeGlobal}var Rx={internals:{},config:{Promise:root.Promise},helpers:{}};var noop=Rx.helpers.noop=function(){},notDefined=Rx.helpers.notDefined=function(x){return typeof x==="undefined"},isScheduler=Rx.helpers.isScheduler=function(x){return x instanceof Rx.Scheduler},identity=Rx.helpers.identity=function(x){return x},pluck=Rx.helpers.pluck=function(property){return function(x){return x[property]}},just=Rx.helpers.just=function(value){return function(){return value}},defaultNow=Rx.helpers.defaultNow=Date.now,defaultComparer=Rx.helpers.defaultComparer=function(x,y){return isEqual(x,y)},defaultSubComparer=Rx.helpers.defaultSubComparer=function(x,y){return x>y?1:x<y?-1:0},defaultKeySerializer=Rx.helpers.defaultKeySerializer=function(x){return x.toString()},defaultError=Rx.helpers.defaultError=function(err){throw err},isPromise=Rx.helpers.isPromise=function(p){return!!p&&typeof p.then==="function"},asArray=Rx.helpers.asArray=function(){return Array.prototype.slice.call(arguments)},not=Rx.helpers.not=function(a){return!a},isFunction=Rx.helpers.isFunction=function(){var isFn=function(value){return typeof value=="function"||false};if(isFn(/x/)){isFn=function(value){return typeof value=="function"&&toString.call(value)=="[object Function]"}}return isFn}();function cloneArray(arr){for(var a=[],i=0,len=arr.length;i<len;i++){a.push(arr[i])}return a}Rx.config.longStackSupport=false;var hasStacks=false;try{throw new Error}catch(e){hasStacks=!!e.stack}var rStartingLine=captureLine(),rFileName;var STACK_JUMP_SEPARATOR="From previous event:";function makeStackTraceLong(error,observable){if(hasStacks&&observable.stack&&typeof error==="object"&&error!==null&&error.stack&&error.stack.indexOf(STACK_JUMP_SEPARATOR)===-1){var stacks=[];for(var o=observable;!!o;o=o.source){if(o.stack){stacks.unshift(o.stack)}}stacks.unshift(error.stack);var concatedStacks=stacks.join("\n"+STACK_JUMP_SEPARATOR+"\n");error.stack=filterStackString(concatedStacks)}}function filterStackString(stackString){var lines=stackString.split("\n"),desiredLines=[];for(var i=0,len=lines.length;i<len;i++){var line=lines[i];if(!isInternalFrame(line)&&!isNodeFrame(line)&&line){desiredLines.push(line)}}return desiredLines.join("\n")}function isInternalFrame(stackLine){var fileNameAndLineNumber=getFileNameAndLineNumber(stackLine);if(!fileNameAndLineNumber){return false}var fileName=fileNameAndLineNumber[0],lineNumber=fileNameAndLineNumber[1];return fileName===rFileName&&lineNumber>=rStartingLine&&lineNumber<=rEndingLine}function isNodeFrame(stackLine){return stackLine.indexOf("(module.js:")!==-1||stackLine.indexOf("(node.js:")!==-1}function captureLine(){if(!hasStacks){return}try{throw new Error}catch(e){var lines=e.stack.split("\n");var firstLine=lines[0].indexOf("@")>0?lines[1]:lines[2];var fileNameAndLineNumber=getFileNameAndLineNumber(firstLine);if(!fileNameAndLineNumber){return}rFileName=fileNameAndLineNumber[0];return fileNameAndLineNumber[1]}}function getFileNameAndLineNumber(stackLine){var attempt1=/at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);if(attempt1){return[attempt1[1],Number(attempt1[2])]}var attempt2=/at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);if(attempt2){return[attempt2[1],Number(attempt2[2])]}var attempt3=/.*@(.+):(\d+)$/.exec(stackLine);if(attempt3){return[attempt3[1],Number(attempt3[2])]}}var EmptyError=Rx.EmptyError=function(){this.message="Sequence contains no elements.";Error.call(this)};EmptyError.prototype=Error.prototype;var ObjectDisposedError=Rx.ObjectDisposedError=function(){this.message="Object has been disposed";Error.call(this)};ObjectDisposedError.prototype=Error.prototype;var ArgumentOutOfRangeError=Rx.ArgumentOutOfRangeError=function(){this.message="Argument out of range";Error.call(this)};ArgumentOutOfRangeError.prototype=Error.prototype;var NotSupportedError=Rx.NotSupportedError=function(message){this.message=message||"This operation is not supported";Error.call(this)};NotSupportedError.prototype=Error.prototype;var NotImplementedError=Rx.NotImplementedError=function(message){this.message=message||"This operation is not implemented";Error.call(this)};NotImplementedError.prototype=Error.prototype;var notImplemented=Rx.helpers.notImplemented=function(){throw new NotImplementedError};var notSupported=Rx.helpers.notSupported=function(){throw new NotSupportedError};var $iterator$=typeof Symbol==="function"&&Symbol.iterator||"_es6shim_iterator_";if(root.Set&&typeof(new root.Set)["@@iterator"]==="function"){$iterator$="@@iterator"}var doneEnumerator=Rx.doneEnumerator={done:true,value:undefined};var isIterable=Rx.helpers.isIterable=function(o){return o[$iterator$]!==undefined};var isArrayLike=Rx.helpers.isArrayLike=function(o){return o&&o.length!==undefined};Rx.helpers.iterator=$iterator$;var bindCallback=Rx.internals.bindCallback=function(func,thisArg,argCount){if(typeof thisArg==="undefined"){return func}switch(argCount){case 0:return function(){return func.call(thisArg)};case 1:return function(arg){return func.call(thisArg,arg)};case 2:return function(value,index){return func.call(thisArg,value,index)};case 3:return function(value,index,collection){return func.call(thisArg,value,index,collection)}}return function(){return func.apply(thisArg,arguments)}};var dontEnums=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],dontEnumsLength=dontEnums.length;var argsClass="[object Arguments]",arrayClass="[object Array]",boolClass="[object Boolean]",dateClass="[object Date]",errorClass="[object Error]",funcClass="[object Function]",numberClass="[object Number]",objectClass="[object Object]",regexpClass="[object RegExp]",stringClass="[object String]";var toString=Object.prototype.toString,hasOwnProperty=Object.prototype.hasOwnProperty,supportsArgsClass=toString.call(arguments)==argsClass,supportNodeClass,errorProto=Error.prototype,objectProto=Object.prototype,stringProto=String.prototype,propertyIsEnumerable=objectProto.propertyIsEnumerable;try{supportNodeClass=!(toString.call(document)==objectClass&&!({toString:0}+""))}catch(e){supportNodeClass=true}var nonEnumProps={};nonEnumProps[arrayClass]=nonEnumProps[dateClass]=nonEnumProps[numberClass]={constructor:true,toLocaleString:true,toString:true,valueOf:true};nonEnumProps[boolClass]=nonEnumProps[stringClass]={constructor:true,toString:true,valueOf:true};nonEnumProps[errorClass]=nonEnumProps[funcClass]=nonEnumProps[regexpClass]={constructor:true,toString:true};nonEnumProps[objectClass]={constructor:true};var support={};(function(){var ctor=function(){this.x=1},props=[];ctor.prototype={valueOf:1,y:1};for(var key in new ctor){props.push(key)}for(key in arguments){}support.enumErrorProps=propertyIsEnumerable.call(errorProto,"message")||propertyIsEnumerable.call(errorProto,"name");support.enumPrototypes=propertyIsEnumerable.call(ctor,"prototype");support.nonEnumArgs=key!=0;support.nonEnumShadows=!/valueOf/.test(props)})(1);var isObject=Rx.internals.isObject=function(value){var type=typeof value;return value&&(type=="function"||type=="object")||false};function keysIn(object){var result=[];if(!isObject(object)){return result}if(support.nonEnumArgs&&object.length&&isArguments(object)){object=slice.call(object)}var skipProto=support.enumPrototypes&&typeof object=="function",skipErrorProps=support.enumErrorProps&&(object===errorProto||object instanceof Error);for(var key in object){if(!(skipProto&&key=="prototype")&&!(skipErrorProps&&(key=="message"||key=="name"))){result.push(key)}}if(support.nonEnumShadows&&object!==objectProto){var ctor=object.constructor,index=-1,length=dontEnumsLength;if(object===(ctor&&ctor.prototype)){var className=object===stringProto?stringClass:object===errorProto?errorClass:toString.call(object),nonEnum=nonEnumProps[className]}while(++index<length){key=dontEnums[index];if(!(nonEnum&&nonEnum[key])&&hasOwnProperty.call(object,key)){result.push(key)}}}return result}function internalFor(object,callback,keysFunc){var index=-1,props=keysFunc(object),length=props.length;while(++index<length){var key=props[index];if(callback(object[key],key,object)===false){break}}return object}function internalForIn(object,callback){return internalFor(object,callback,keysIn)}function isNode(value){return typeof value.toString!="function"&&typeof(value+"")=="string"}var isArguments=function(value){return value&&typeof value=="object"?toString.call(value)==argsClass:false};if(!supportsArgsClass){isArguments=function(value){return value&&typeof value=="object"?hasOwnProperty.call(value,"callee"):false}}var isEqual=Rx.internals.isEqual=function(x,y){return deepEquals(x,y,[],[])};function deepEquals(a,b,stackA,stackB){if(a===b){return a!==0||1/a==1/b}var type=typeof a,otherType=typeof b;if(a===a&&(a==null||b==null||type!="function"&&type!="object"&&otherType!="function"&&otherType!="object")){return false}var className=toString.call(a),otherClass=toString.call(b);if(className==argsClass){className=objectClass}if(otherClass==argsClass){otherClass=objectClass}if(className!=otherClass){return false}switch(className){case boolClass:case dateClass:return+a==+b;case numberClass:return a!=+a?b!=+b:a==0?1/a==1/b:a==+b;case regexpClass:case stringClass:return a==String(b)}var isArr=className==arrayClass;if(!isArr){if(className!=objectClass||!support.nodeClass&&(isNode(a)||isNode(b))){return false}var ctorA=!support.argsObject&&isArguments(a)?Object:a.constructor,ctorB=!support.argsObject&&isArguments(b)?Object:b.constructor;if(ctorA!=ctorB&&!(hasOwnProperty.call(a,"constructor")&&hasOwnProperty.call(b,"constructor"))&&!(isFunction(ctorA)&&ctorA instanceof ctorA&&isFunction(ctorB)&&ctorB instanceof ctorB)&&("constructor"in a&&"constructor"in b)){return false}}var initedStack=!stackA;stackA||(stackA=[]);stackB||(stackB=[]);var length=stackA.length;while(length--){if(stackA[length]==a){return stackB[length]==b}}var size=0;var result=true;stackA.push(a);stackB.push(b);if(isArr){length=a.length;size=b.length;result=size==length;if(result){while(size--){var index=length,value=b[size];if(!(result=deepEquals(a[size],value,stackA,stackB))){break}}}}else{internalForIn(b,function(value,key,b){if(hasOwnProperty.call(b,key)){size++;return result=hasOwnProperty.call(a,key)&&deepEquals(a[key],value,stackA,stackB)}});if(result){internalForIn(a,function(value,key,a){if(hasOwnProperty.call(a,key)){return result=--size>-1}})}}stackA.pop();stackB.pop();return result}var hasProp={}.hasOwnProperty,slice=Array.prototype.slice;var inherits=this.inherits=Rx.internals.inherits=function(child,parent){function __(){this.constructor=child}__.prototype=parent.prototype;child.prototype=new __};var addProperties=Rx.internals.addProperties=function(obj){for(var sources=[],i=1,len=arguments.length;i<len;i++){sources.push(arguments[i])}for(var idx=0,ln=sources.length;idx<ln;idx++){var source=sources[idx];for(var prop in source){obj[prop]=source[prop]}}};var addRef=Rx.internals.addRef=function(xs,r){return new AnonymousObservable(function(observer){return new CompositeDisposable(r.getDisposable(),xs.subscribe(observer))})};function arrayInitialize(count,factory){var a=new Array(count);for(var i=0;i<count;i++){a[i]=factory()}return a}var errorObj={e:{}};var tryCatchTarget;function tryCatcher(){try{return tryCatchTarget.apply(this,arguments)}catch(e){errorObj.e=e;return errorObj}}function tryCatch(fn){if(!isFunction(fn)){throw new TypeError("fn must be a function")}tryCatchTarget=fn;return tryCatcher}function thrower(e){throw e}function IndexedItem(id,value){this.id=id;this.value=value}IndexedItem.prototype.compareTo=function(other){var c=this.value.compareTo(other.value);c===0&&(c=this.id-other.id);return c};var PriorityQueue=Rx.internals.PriorityQueue=function(capacity){this.items=new Array(capacity);this.length=0};var priorityProto=PriorityQueue.prototype;priorityProto.isHigherPriority=function(left,right){return this.items[left].compareTo(this.items[right])<0};priorityProto.percolate=function(index){if(index>=this.length||index<0){return}var parent=index-1>>1;if(parent<0||parent===index){return}if(this.isHigherPriority(index,parent)){var temp=this.items[index];this.items[index]=this.items[parent];this.items[parent]=temp;this.percolate(parent)}};priorityProto.heapify=function(index){+index||(index=0);if(index>=this.length||index<0){return}var left=2*index+1,right=2*index+2,first=index;if(left<this.length&&this.isHigherPriority(left,first)){first=left}if(right<this.length&&this.isHigherPriority(right,first)){first=right}if(first!==index){var temp=this.items[index];this.items[index]=this.items[first];this.items[first]=temp;this.heapify(first)}};priorityProto.peek=function(){return this.items[0].value};priorityProto.removeAt=function(index){this.items[index]=this.items[--this.length];this.items[this.length]=undefined;this.heapify()};priorityProto.dequeue=function(){var result=this.peek();this.removeAt(0);return result};priorityProto.enqueue=function(item){var index=this.length++;this.items[index]=new IndexedItem(PriorityQueue.count++,item);this.percolate(index)};priorityProto.remove=function(item){for(var i=0;i<this.length;i++){if(this.items[i].value===item){this.removeAt(i);return true}}return false};PriorityQueue.count=0;var CompositeDisposable=Rx.CompositeDisposable=function(){var args=[],i,len;if(Array.isArray(arguments[0])){args=arguments[0];len=args.length}else{len=arguments.length;args=new Array(len);for(i=0;i<len;i++){args[i]=arguments[i]}}for(i=0;i<len;i++){if(!isDisposable(args[i])){throw new TypeError("Not a disposable")}}this.disposables=args;this.isDisposed=false;this.length=args.length};var CompositeDisposablePrototype=CompositeDisposable.prototype;CompositeDisposablePrototype.add=function(item){if(this.isDisposed){item.dispose()}else{this.disposables.push(item);this.length++}};CompositeDisposablePrototype.remove=function(item){var shouldDispose=false;if(!this.isDisposed){var idx=this.disposables.indexOf(item);if(idx!==-1){shouldDispose=true;this.disposables.splice(idx,1);this.length--;item.dispose()}}return shouldDispose};CompositeDisposablePrototype.dispose=function(){if(!this.isDisposed){this.isDisposed=true;var len=this.disposables.length,currentDisposables=new Array(len);for(var i=0;i<len;i++){currentDisposables[i]=this.disposables[i]}this.disposables=[];this.length=0;for(i=0;i<len;i++){currentDisposables[i].dispose()}}};var Disposable=Rx.Disposable=function(action){this.isDisposed=false;this.action=action||noop};Disposable.prototype.dispose=function(){if(!this.isDisposed){this.action();this.isDisposed=true}};var disposableCreate=Disposable.create=function(action){return new Disposable(action)};var disposableEmpty=Disposable.empty={dispose:noop};var isDisposable=Disposable.isDisposable=function(d){return d&&isFunction(d.dispose)};var checkDisposed=Disposable.checkDisposed=function(disposable){if(disposable.isDisposed){throw new ObjectDisposedError; }};var SingleAssignmentDisposable=Rx.SingleAssignmentDisposable=function(){function BooleanDisposable(){this.isDisposed=false;this.current=null}var booleanDisposablePrototype=BooleanDisposable.prototype;booleanDisposablePrototype.getDisposable=function(){return this.current};booleanDisposablePrototype.setDisposable=function(value){var shouldDispose=this.isDisposed;if(!shouldDispose){var old=this.current;this.current=value}old&&old.dispose();shouldDispose&&value&&value.dispose()};booleanDisposablePrototype.dispose=function(){if(!this.isDisposed){this.isDisposed=true;var old=this.current;this.current=null}old&&old.dispose()};return BooleanDisposable}();var SerialDisposable=Rx.SerialDisposable=SingleAssignmentDisposable;var RefCountDisposable=Rx.RefCountDisposable=function(){function InnerDisposable(disposable){this.disposable=disposable;this.disposable.count++;this.isInnerDisposed=false}InnerDisposable.prototype.dispose=function(){if(!this.disposable.isDisposed&&!this.isInnerDisposed){this.isInnerDisposed=true;this.disposable.count--;if(this.disposable.count===0&&this.disposable.isPrimaryDisposed){this.disposable.isDisposed=true;this.disposable.underlyingDisposable.dispose()}}};function RefCountDisposable(disposable){this.underlyingDisposable=disposable;this.isDisposed=false;this.isPrimaryDisposed=false;this.count=0}RefCountDisposable.prototype.dispose=function(){if(!this.isDisposed&&!this.isPrimaryDisposed){this.isPrimaryDisposed=true;if(this.count===0){this.isDisposed=true;this.underlyingDisposable.dispose()}}};RefCountDisposable.prototype.getDisposable=function(){return this.isDisposed?disposableEmpty:new InnerDisposable(this)};return RefCountDisposable}();function ScheduledDisposable(scheduler,disposable){this.scheduler=scheduler;this.disposable=disposable;this.isDisposed=false}function scheduleItem(s,self){if(!self.isDisposed){self.isDisposed=true;self.disposable.dispose()}}ScheduledDisposable.prototype.dispose=function(){this.scheduler.scheduleWithState(this,scheduleItem)};var ScheduledItem=Rx.internals.ScheduledItem=function(scheduler,state,action,dueTime,comparer){this.scheduler=scheduler;this.state=state;this.action=action;this.dueTime=dueTime;this.comparer=comparer||defaultSubComparer;this.disposable=new SingleAssignmentDisposable};ScheduledItem.prototype.invoke=function(){this.disposable.setDisposable(this.invokeCore())};ScheduledItem.prototype.compareTo=function(other){return this.comparer(this.dueTime,other.dueTime)};ScheduledItem.prototype.isCancelled=function(){return this.disposable.isDisposed};ScheduledItem.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var Scheduler=Rx.Scheduler=function(){function Scheduler(now,schedule,scheduleRelative,scheduleAbsolute){this.now=now;this._schedule=schedule;this._scheduleRelative=scheduleRelative;this._scheduleAbsolute=scheduleAbsolute}function invokeAction(scheduler,action){action();return disposableEmpty}var schedulerProto=Scheduler.prototype;schedulerProto.schedule=function(action){return this._schedule(action,invokeAction)};schedulerProto.scheduleWithState=function(state,action){return this._schedule(state,action)};schedulerProto.scheduleWithRelative=function(dueTime,action){return this._scheduleRelative(action,dueTime,invokeAction)};schedulerProto.scheduleWithRelativeAndState=function(state,dueTime,action){return this._scheduleRelative(state,dueTime,action)};schedulerProto.scheduleWithAbsolute=function(dueTime,action){return this._scheduleAbsolute(action,dueTime,invokeAction)};schedulerProto.scheduleWithAbsoluteAndState=function(state,dueTime,action){return this._scheduleAbsolute(state,dueTime,action)};Scheduler.now=defaultNow;Scheduler.normalize=function(timeSpan){timeSpan<0&&(timeSpan=0);return timeSpan};return Scheduler}();var normalizeTime=Scheduler.normalize;(function(schedulerProto){function invokeRecImmediate(scheduler,pair){var state=pair[0],action=pair[1],group=new CompositeDisposable;function recursiveAction(state1){action(state1,function(state2){var isAdded=false,isDone=false,d=scheduler.scheduleWithState(state2,function(scheduler1,state3){if(isAdded){group.remove(d)}else{isDone=true}recursiveAction(state3);return disposableEmpty});if(!isDone){group.add(d);isAdded=true}})}recursiveAction(state);return group}function invokeRecDate(scheduler,pair,method){var state=pair[0],action=pair[1],group=new CompositeDisposable;function recursiveAction(state1){action(state1,function(state2,dueTime1){var isAdded=false,isDone=false,d=scheduler[method](state2,dueTime1,function(scheduler1,state3){if(isAdded){group.remove(d)}else{isDone=true}recursiveAction(state3);return disposableEmpty});if(!isDone){group.add(d);isAdded=true}})}recursiveAction(state);return group}function scheduleInnerRecursive(action,self){action(function(dt){self(action,dt)})}schedulerProto.scheduleRecursive=function(action){return this.scheduleRecursiveWithState(action,function(_action,self){_action(function(){self(_action)})})};schedulerProto.scheduleRecursiveWithState=function(state,action){return this.scheduleWithState([state,action],invokeRecImmediate)};schedulerProto.scheduleRecursiveWithRelative=function(dueTime,action){return this.scheduleRecursiveWithRelativeAndState(action,dueTime,scheduleInnerRecursive)};schedulerProto.scheduleRecursiveWithRelativeAndState=function(state,dueTime,action){return this._scheduleRelative([state,action],dueTime,function(s,p){return invokeRecDate(s,p,"scheduleWithRelativeAndState")})};schedulerProto.scheduleRecursiveWithAbsolute=function(dueTime,action){return this.scheduleRecursiveWithAbsoluteAndState(action,dueTime,scheduleInnerRecursive)};schedulerProto.scheduleRecursiveWithAbsoluteAndState=function(state,dueTime,action){return this._scheduleAbsolute([state,action],dueTime,function(s,p){return invokeRecDate(s,p,"scheduleWithAbsoluteAndState")})}})(Scheduler.prototype);(function(schedulerProto){Scheduler.prototype.schedulePeriodic=function(period,action){return this.schedulePeriodicWithState(null,period,action)};Scheduler.prototype.schedulePeriodicWithState=function(state,period,action){if(typeof root.setInterval==="undefined"){throw new NotSupportedError}period=normalizeTime(period);var s=state,id=root.setInterval(function(){s=action(s)},period);return disposableCreate(function(){root.clearInterval(id)})}})(Scheduler.prototype);(function(schedulerProto){schedulerProto.catchError=schedulerProto["catch"]=function(handler){return new CatchScheduler(this,handler)}})(Scheduler.prototype);var SchedulePeriodicRecursive=Rx.internals.SchedulePeriodicRecursive=function(){function tick(command,recurse){recurse(0,this._period);try{this._state=this._action(this._state)}catch(e){this._cancel.dispose();throw e}}function SchedulePeriodicRecursive(scheduler,state,period,action){this._scheduler=scheduler;this._state=state;this._period=period;this._action=action}SchedulePeriodicRecursive.prototype.start=function(){var d=new SingleAssignmentDisposable;this._cancel=d;d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,tick.bind(this)));return d};return SchedulePeriodicRecursive}();var immediateScheduler=Scheduler.immediate=function(){function scheduleNow(state,action){return action(this,state)}return new Scheduler(defaultNow,scheduleNow,notSupported,notSupported)}();var currentThreadScheduler=Scheduler.currentThread=function(){var queue;function runTrampoline(){while(queue.length>0){var item=queue.dequeue();!item.isCancelled()&&item.invoke()}}function scheduleNow(state,action){var si=new ScheduledItem(this,state,action,this.now());if(!queue){queue=new PriorityQueue(4);queue.enqueue(si);var result=tryCatch(runTrampoline)();queue=null;if(result===errorObj){return thrower(result.e)}}else{queue.enqueue(si)}return si.disposable}var currentScheduler=new Scheduler(defaultNow,scheduleNow,notSupported,notSupported);currentScheduler.scheduleRequired=function(){return!queue};return currentScheduler}();var scheduleMethod;var localTimer=function(){var localSetTimeout,localClearTimeout=noop;if("WScript"in this){localSetTimeout=function(fn,time){WScript.Sleep(time);fn()}}else if(!!root.setTimeout){localSetTimeout=root.setTimeout;localClearTimeout=root.clearTimeout}else{throw new NotSupportedError}return{setTimeout:localSetTimeout,clearTimeout:localClearTimeout}}();var localSetTimeout=localTimer.setTimeout,localClearTimeout=localTimer.clearTimeout;(function(){var nextHandle=1,tasksByHandle={},currentlyRunning=false;function clearMethod(handle){delete tasksByHandle[handle]}function runTask(handle){if(currentlyRunning){localSetTimeout(function(){runTask(handle)},0)}else{var task=tasksByHandle[handle];if(task){currentlyRunning=true;var result=tryCatch(task)();clearMethod(handle);currentlyRunning=false;if(result===errorObj){return thrower(result.e)}}}}var reNative=RegExp("^"+String(toString).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$");var setImmediate=typeof(setImmediate=freeGlobal&&moduleExports&&freeGlobal.setImmediate)=="function"&&!reNative.test(setImmediate)&&setImmediate;function postMessageSupported(){if(!root.postMessage||root.importScripts){return false}var isAsync=false,oldHandler=root.onmessage;root.onmessage=function(){isAsync=true};root.postMessage("","*");root.onmessage=oldHandler;return isAsync}if(isFunction(setImmediate)){scheduleMethod=function(action){var id=nextHandle++;tasksByHandle[id]=action;setImmediate(function(){runTask(id)});return id}}else if(typeof process!=="undefined"&&{}.toString.call(process)==="[object process]"){scheduleMethod=function(action){var id=nextHandle++;tasksByHandle[id]=action;process.nextTick(function(){runTask(id)});return id}}else if(postMessageSupported()){var MSG_PREFIX="ms.rx.schedule"+Math.random();function onGlobalPostMessage(event){if(typeof event.data==="string"&&event.data.substring(0,MSG_PREFIX.length)===MSG_PREFIX){runTask(event.data.substring(MSG_PREFIX.length))}}if(root.addEventListener){root.addEventListener("message",onGlobalPostMessage,false)}else{root.attachEvent("onmessage",onGlobalPostMessage,false)}scheduleMethod=function(action){var id=nextHandle++;tasksByHandle[id]=action;root.postMessage(MSG_PREFIX+currentId,"*");return id}}else if(!!root.MessageChannel){var channel=new root.MessageChannel;channel.port1.onmessage=function(e){runTask(e.data)};scheduleMethod=function(action){var id=nextHandle++;tasksByHandle[id]=action;channel.port2.postMessage(id);return id}}else if("document"in root&&"onreadystatechange"in root.document.createElement("script")){scheduleMethod=function(action){var scriptElement=root.document.createElement("script");var id=nextHandle++;tasksByHandle[id]=action;scriptElement.onreadystatechange=function(){runTask(id);scriptElement.onreadystatechange=null;scriptElement.parentNode.removeChild(scriptElement);scriptElement=null};root.document.documentElement.appendChild(scriptElement);return id}}else{scheduleMethod=function(action){var id=nextHandle++;tasksByHandle[id]=action;localSetTimeout(function(){runTask(id)},0);return id}}})();var timeoutScheduler=Scheduler.timeout=Scheduler.default=function(){function scheduleNow(state,action){var scheduler=this,disposable=new SingleAssignmentDisposable;var id=scheduleMethod(function(){if(!disposable.isDisposed){disposable.setDisposable(action(scheduler,state))}});return new CompositeDisposable(disposable,disposableCreate(function(){clearMethod(id)}))}function scheduleRelative(state,dueTime,action){var scheduler=this,dt=Scheduler.normalize(dueTime);if(dt===0){return scheduler.scheduleWithState(state,action)}var disposable=new SingleAssignmentDisposable;var id=localSetTimeout(function(){if(!disposable.isDisposed){disposable.setDisposable(action(scheduler,state))}},dt);return new CompositeDisposable(disposable,disposableCreate(function(){localClearTimeout(id)}))}function scheduleAbsolute(state,dueTime,action){return this.scheduleWithRelativeAndState(state,dueTime-this.now(),action)}return new Scheduler(defaultNow,scheduleNow,scheduleRelative,scheduleAbsolute)}();var CatchScheduler=function(__super__){function scheduleNow(state,action){return this._scheduler.scheduleWithState(state,this._wrap(action))}function scheduleRelative(state,dueTime,action){return this._scheduler.scheduleWithRelativeAndState(state,dueTime,this._wrap(action))}function scheduleAbsolute(state,dueTime,action){return this._scheduler.scheduleWithAbsoluteAndState(state,dueTime,this._wrap(action))}inherits(CatchScheduler,__super__);function CatchScheduler(scheduler,handler){this._scheduler=scheduler;this._handler=handler;this._recursiveOriginal=null;this._recursiveWrapper=null;__super__.call(this,this._scheduler.now.bind(this._scheduler),scheduleNow,scheduleRelative,scheduleAbsolute)}CatchScheduler.prototype._clone=function(scheduler){return new CatchScheduler(scheduler,this._handler)};CatchScheduler.prototype._wrap=function(action){var parent=this;return function(self,state){try{return action(parent._getRecursiveWrapper(self),state)}catch(e){if(!parent._handler(e)){throw e}return disposableEmpty}}};CatchScheduler.prototype._getRecursiveWrapper=function(scheduler){if(this._recursiveOriginal!==scheduler){this._recursiveOriginal=scheduler;var wrapper=this._clone(scheduler);wrapper._recursiveOriginal=scheduler;wrapper._recursiveWrapper=wrapper;this._recursiveWrapper=wrapper}return this._recursiveWrapper};CatchScheduler.prototype.schedulePeriodicWithState=function(state,period,action){var self=this,failed=false,d=new SingleAssignmentDisposable;d.setDisposable(this._scheduler.schedulePeriodicWithState(state,period,function(state1){if(failed){return null}try{return action(state1)}catch(e){failed=true;if(!self._handler(e)){throw e}d.dispose();return null}}));return d};return CatchScheduler}(Scheduler);var Notification=Rx.Notification=function(){function Notification(kind,value,exception,accept,acceptObservable,toString){this.kind=kind;this.value=value;this.exception=exception;this._accept=accept;this._acceptObservable=acceptObservable;this.toString=toString}Notification.prototype.accept=function(observerOrOnNext,onError,onCompleted){return observerOrOnNext&&typeof observerOrOnNext==="object"?this._acceptObservable(observerOrOnNext):this._accept(observerOrOnNext,onError,onCompleted)};Notification.prototype.toObservable=function(scheduler){var self=this;isScheduler(scheduler)||(scheduler=immediateScheduler);return new AnonymousObservable(function(observer){return scheduler.scheduleWithState(self,function(_,notification){notification._acceptObservable(observer);notification.kind==="N"&&observer.onCompleted()})})};return Notification}();var notificationCreateOnNext=Notification.createOnNext=function(){function _accept(onNext){return onNext(this.value)}function _acceptObservable(observer){return observer.onNext(this.value)}function toString(){return"OnNext("+this.value+")"}return function(value){return new Notification("N",value,null,_accept,_acceptObservable,toString)}}();var notificationCreateOnError=Notification.createOnError=function(){function _accept(onNext,onError){return onError(this.exception)}function _acceptObservable(observer){return observer.onError(this.exception)}function toString(){return"OnError("+this.exception+")"}return function(e){return new Notification("E",null,e,_accept,_acceptObservable,toString)}}();var notificationCreateOnCompleted=Notification.createOnCompleted=function(){function _accept(onNext,onError,onCompleted){return onCompleted()}function _acceptObservable(observer){return observer.onCompleted()}function toString(){return"OnCompleted()"}return function(){return new Notification("C",null,null,_accept,_acceptObservable,toString)}}();var Enumerator=Rx.internals.Enumerator=function(next){this._next=next};Enumerator.prototype.next=function(){return this._next()};Enumerator.prototype[$iterator$]=function(){return this};var Enumerable=Rx.internals.Enumerable=function(iterator){this._iterator=iterator};Enumerable.prototype[$iterator$]=function(){return this._iterator()};Enumerable.prototype.concat=function(){var sources=this;return new AnonymousObservable(function(o){var e=sources[$iterator$]();var isDisposed,subscription=new SerialDisposable;var cancelable=immediateScheduler.scheduleRecursive(function(self){if(isDisposed){return}try{var currentItem=e.next()}catch(ex){return o.onError(ex)}if(currentItem.done){return o.onCompleted()}var currentValue=currentItem.value;isPromise(currentValue)&&(currentValue=observableFromPromise(currentValue));var d=new SingleAssignmentDisposable;subscription.setDisposable(d);d.setDisposable(currentValue.subscribe(function(x){o.onNext(x)},function(err){o.onError(err)},self))});return new CompositeDisposable(subscription,cancelable,disposableCreate(function(){isDisposed=true}))})};Enumerable.prototype.catchError=function(){var sources=this;return new AnonymousObservable(function(o){var e=sources[$iterator$]();var isDisposed,subscription=new SerialDisposable;var cancelable=immediateScheduler.scheduleRecursiveWithState(null,function(lastException,self){if(isDisposed){return}try{var currentItem=e.next()}catch(ex){return observer.onError(ex)}if(currentItem.done){if(lastException!==null){o.onError(lastException)}else{o.onCompleted()}return}var currentValue=currentItem.value;isPromise(currentValue)&&(currentValue=observableFromPromise(currentValue));var d=new SingleAssignmentDisposable;subscription.setDisposable(d);d.setDisposable(currentValue.subscribe(function(x){o.onNext(x)},self,function(){o.onCompleted()}))});return new CompositeDisposable(subscription,cancelable,disposableCreate(function(){isDisposed=true}))})};Enumerable.prototype.catchErrorWhen=function(notificationHandler){var sources=this;return new AnonymousObservable(function(o){var exceptions=new Subject,notifier=new Subject,handled=notificationHandler(exceptions),notificationDisposable=handled.subscribe(notifier);var e=sources[$iterator$]();var isDisposed,lastException,subscription=new SerialDisposable;var cancelable=immediateScheduler.scheduleRecursive(function(self){if(isDisposed){return}try{var currentItem=e.next()}catch(ex){return o.onError(ex)}if(currentItem.done){if(lastException){o.onError(lastException)}else{o.onCompleted()}return}var currentValue=currentItem.value;isPromise(currentValue)&&(currentValue=observableFromPromise(currentValue));var outer=new SingleAssignmentDisposable;var inner=new SingleAssignmentDisposable;subscription.setDisposable(new CompositeDisposable(inner,outer));outer.setDisposable(currentValue.subscribe(function(x){o.onNext(x)},function(exn){inner.setDisposable(notifier.subscribe(self,function(ex){o.onError(ex)},function(){o.onCompleted()}));exceptions.onNext(exn)},function(){o.onCompleted()}))});return new CompositeDisposable(notificationDisposable,subscription,cancelable,disposableCreate(function(){isDisposed=true}))})};var enumerableRepeat=Enumerable.repeat=function(value,repeatCount){if(repeatCount==null){repeatCount=-1}return new Enumerable(function(){var left=repeatCount;return new Enumerator(function(){if(left===0){return doneEnumerator}if(left>0){left--}return{done:false,value:value}})})};var enumerableOf=Enumerable.of=function(source,selector,thisArg){if(selector){var selectorFn=bindCallback(selector,thisArg,3)}return new Enumerable(function(){var index=-1;return new Enumerator(function(){return++index<source.length?{done:false,value:!selector?source[index]:selectorFn(source[index],index,source)}:doneEnumerator})})};var Observer=Rx.Observer=function(){};Observer.prototype.toNotifier=function(){var observer=this;return function(n){return n.accept(observer)}};Observer.prototype.asObserver=function(){return new AnonymousObserver(this.onNext.bind(this),this.onError.bind(this),this.onCompleted.bind(this))};Observer.prototype.checked=function(){return new CheckedObserver(this)};var observerCreate=Observer.create=function(onNext,onError,onCompleted){onNext||(onNext=noop);onError||(onError=defaultError);onCompleted||(onCompleted=noop);return new AnonymousObserver(onNext,onError,onCompleted)};Observer.fromNotifier=function(handler,thisArg){return new AnonymousObserver(function(x){return handler.call(thisArg,notificationCreateOnNext(x))},function(e){return handler.call(thisArg,notificationCreateOnError(e))},function(){return handler.call(thisArg,notificationCreateOnCompleted())})};Observer.prototype.notifyOn=function(scheduler){return new ObserveOnObserver(scheduler,this)};Observer.prototype.makeSafe=function(disposable){return new AnonymousSafeObserver(this._onNext,this._onError,this._onCompleted,disposable)};var AbstractObserver=Rx.internals.AbstractObserver=function(__super__){inherits(AbstractObserver,__super__);function AbstractObserver(){this.isStopped=false;__super__.call(this)}AbstractObserver.prototype.next=notImplemented;AbstractObserver.prototype.error=notImplemented;AbstractObserver.prototype.completed=notImplemented;AbstractObserver.prototype.onNext=function(value){if(!this.isStopped){this.next(value)}};AbstractObserver.prototype.onError=function(error){if(!this.isStopped){this.isStopped=true;this.error(error)}};AbstractObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.completed()}};AbstractObserver.prototype.dispose=function(){this.isStopped=true};AbstractObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.error(e);return true}return false};return AbstractObserver}(Observer);var AnonymousObserver=Rx.AnonymousObserver=function(__super__){inherits(AnonymousObserver,__super__);function AnonymousObserver(onNext,onError,onCompleted){__super__.call(this);this._onNext=onNext;this._onError=onError;this._onCompleted=onCompleted}AnonymousObserver.prototype.next=function(value){this._onNext(value)};AnonymousObserver.prototype.error=function(error){this._onError(error)};AnonymousObserver.prototype.completed=function(){this._onCompleted()};return AnonymousObserver}(AbstractObserver);var CheckedObserver=function(__super__){inherits(CheckedObserver,__super__);function CheckedObserver(observer){__super__.call(this);this._observer=observer;this._state=0}var CheckedObserverPrototype=CheckedObserver.prototype;CheckedObserverPrototype.onNext=function(value){this.checkAccess();var res=tryCatch(this._observer.onNext).call(this._observer,value);this._state=0;res===errorObj&&thrower(res.e)};CheckedObserverPrototype.onError=function(err){this.checkAccess();var res=tryCatch(this._observer.onError).call(this._observer,err);this._state=2;res===errorObj&&thrower(res.e)};CheckedObserverPrototype.onCompleted=function(){this.checkAccess();var res=tryCatch(this._observer.onCompleted).call(this._observer);this._state=2;res===errorObj&&thrower(res.e)};CheckedObserverPrototype.checkAccess=function(){if(this._state===1){throw new Error("Re-entrancy detected")}if(this._state===2){throw new Error("Observer completed")}if(this._state===0){this._state=1}};return CheckedObserver}(Observer);var ScheduledObserver=Rx.internals.ScheduledObserver=function(__super__){inherits(ScheduledObserver,__super__);function ScheduledObserver(scheduler,observer){__super__.call(this);this.scheduler=scheduler;this.observer=observer;this.isAcquired=false;this.hasFaulted=false;this.queue=[];this.disposable=new SerialDisposable}ScheduledObserver.prototype.next=function(value){var self=this;this.queue.push(function(){self.observer.onNext(value)})};ScheduledObserver.prototype.error=function(e){var self=this;this.queue.push(function(){self.observer.onError(e)})};ScheduledObserver.prototype.completed=function(){var self=this;this.queue.push(function(){self.observer.onCompleted()})};ScheduledObserver.prototype.ensureActive=function(){var isOwner=false,parent=this;if(!this.hasFaulted&&this.queue.length>0){isOwner=!this.isAcquired;this.isAcquired=true}if(isOwner){this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(self){var work;if(parent.queue.length>0){work=parent.queue.shift()}else{parent.isAcquired=false;return}try{work()}catch(ex){parent.queue=[];parent.hasFaulted=true;throw ex}self()}))}};ScheduledObserver.prototype.dispose=function(){__super__.prototype.dispose.call(this);this.disposable.dispose()};return ScheduledObserver}(AbstractObserver);var ObserveOnObserver=function(__super__){inherits(ObserveOnObserver,__super__);function ObserveOnObserver(scheduler,observer,cancel){__super__.call(this,scheduler,observer);this._cancel=cancel}ObserveOnObserver.prototype.next=function(value){__super__.prototype.next.call(this,value);this.ensureActive()};ObserveOnObserver.prototype.error=function(e){__super__.prototype.error.call(this,e);this.ensureActive()};ObserveOnObserver.prototype.completed=function(){__super__.prototype.completed.call(this);this.ensureActive()};ObserveOnObserver.prototype.dispose=function(){__super__.prototype.dispose.call(this);this._cancel&&this._cancel.dispose();this._cancel=null};return ObserveOnObserver}(ScheduledObserver);var observableProto;var Observable=Rx.Observable=function(){function Observable(subscribe){if(Rx.config.longStackSupport&&hasStacks){try{throw new Error}catch(e){this.stack=e.stack.substring(e.stack.indexOf("\n")+1)}var self=this;this._subscribe=function(observer){var oldOnError=observer.onError.bind(observer);observer.onError=function(err){makeStackTraceLong(err,self);oldOnError(err)};return subscribe.call(self,observer)}}else{this._subscribe=subscribe}}observableProto=Observable.prototype;observableProto.subscribe=observableProto.forEach=function(observerOrOnNext,onError,onCompleted){return this._subscribe(typeof observerOrOnNext==="object"?observerOrOnNext:observerCreate(observerOrOnNext,onError,onCompleted))};observableProto.subscribeOnNext=function(onNext,thisArg){return this._subscribe(observerCreate(typeof thisArg!=="undefined"?function(x){onNext.call(thisArg,x)}:onNext))};observableProto.subscribeOnError=function(onError,thisArg){return this._subscribe(observerCreate(null,typeof thisArg!=="undefined"?function(e){onError.call(thisArg,e)}:onError))};observableProto.subscribeOnCompleted=function(onCompleted,thisArg){return this._subscribe(observerCreate(null,null,typeof thisArg!=="undefined"?function(){onCompleted.call(thisArg)}:onCompleted))};return Observable}();var ObservableBase=Rx.ObservableBase=function(__super__){inherits(ObservableBase,__super__);function fixSubscriber(subscriber){return subscriber&&isFunction(subscriber.dispose)?subscriber:isFunction(subscriber)?disposableCreate(subscriber):disposableEmpty}function setDisposable(s,state){var ado=state[0],self=state[1];var sub=tryCatch(self.subscribeCore).call(self,ado);if(sub===errorObj){if(!ado.fail(errorObj.e)){return thrower(errorObj.e)}}ado.setDisposable(fixSubscriber(sub))}function subscribe(observer){var ado=new AutoDetachObserver(observer),state=[ado,this];if(currentThreadScheduler.scheduleRequired()){currentThreadScheduler.scheduleWithState(state,setDisposable)}else{setDisposable(null,state)}return ado}function ObservableBase(){__super__.call(this,subscribe)}ObservableBase.prototype.subscribeCore=notImplemented;return ObservableBase}(Observable);observableProto.observeOn=function(scheduler){var source=this;return new AnonymousObservable(function(observer){return source.subscribe(new ObserveOnObserver(scheduler,observer))},source)};observableProto.subscribeOn=function(scheduler){var source=this;return new AnonymousObservable(function(observer){var m=new SingleAssignmentDisposable,d=new SerialDisposable;d.setDisposable(m);m.setDisposable(scheduler.schedule(function(){d.setDisposable(new ScheduledDisposable(scheduler,source.subscribe(observer)))}));return d},source)};var observableFromPromise=Observable.fromPromise=function(promise){return observableDefer(function(){var subject=new Rx.AsyncSubject;promise.then(function(value){subject.onNext(value);subject.onCompleted()},subject.onError.bind(subject));return subject})};observableProto.toPromise=function(promiseCtor){promiseCtor||(promiseCtor=Rx.config.Promise);if(!promiseCtor){throw new NotSupportedError("Promise type not provided nor in Rx.config.Promise")}var source=this;return new promiseCtor(function(resolve,reject){var value,hasValue=false;source.subscribe(function(v){value=v;hasValue=true},reject,function(){hasValue&&resolve(value)})})};var ToArrayObservable=function(__super__){inherits(ToArrayObservable,__super__);function ToArrayObservable(source){this.source=source;__super__.call(this)}ToArrayObservable.prototype.subscribeCore=function(observer){return this.source.subscribe(new ToArrayObserver(observer))};return ToArrayObservable}(ObservableBase);function ToArrayObserver(observer){this.observer=observer;this.a=[];this.isStopped=false}ToArrayObserver.prototype.onNext=function(x){if(!this.isStopped){this.a.push(x)}};ToArrayObserver.prototype.onError=function(e){if(!this.isStopped){this.isStopped=true;this.observer.onError(e)}};ToArrayObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.observer.onNext(this.a);this.observer.onCompleted()}};ToArrayObserver.prototype.dispose=function(){this.isStopped=true};ToArrayObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.observer.onError(e);return true}return false};observableProto.toArray=function(){return new ToArrayObservable(this)};Observable.create=Observable.createWithDisposable=function(subscribe,parent){return new AnonymousObservable(subscribe,parent)};var observableDefer=Observable.defer=function(observableFactory){return new AnonymousObservable(function(observer){var result;try{result=observableFactory()}catch(e){return observableThrow(e).subscribe(observer)}isPromise(result)&&(result=observableFromPromise(result));return result.subscribe(observer)})};var observableEmpty=Observable.empty=function(scheduler){isScheduler(scheduler)||(scheduler=immediateScheduler);return new AnonymousObservable(function(observer){return scheduler.schedule(function(){observer.onCompleted()})})};var FromObservable=function(__super__){inherits(FromObservable,__super__);function FromObservable(iterable,mapper,scheduler){this.iterable=iterable;this.mapper=mapper;this.scheduler=scheduler;__super__.call(this)}FromObservable.prototype.subscribeCore=function(observer){var sink=new FromSink(observer,this);return sink.run()};return FromObservable}(ObservableBase);var FromSink=function(){function FromSink(observer,parent){this.observer=observer;this.parent=parent}FromSink.prototype.run=function(){var list=Object(this.parent.iterable),it=getIterable(list),observer=this.observer,mapper=this.parent.mapper;function loopRecursive(i,recurse){try{var next=it.next()}catch(e){return observer.onError(e)}if(next.done){return observer.onCompleted()}var result=next.value;if(mapper){try{result=mapper(result,i)}catch(e){return observer.onError(e)}}observer.onNext(result);recurse(i+1)}return this.parent.scheduler.scheduleRecursiveWithState(0,loopRecursive)};return FromSink}();var maxSafeInteger=Math.pow(2,53)-1;function StringIterable(str){this._s=s}StringIterable.prototype[$iterator$]=function(){return new StringIterator(this._s)};function StringIterator(str){this._s=s;this._l=s.length;this._i=0}StringIterator.prototype[$iterator$]=function(){return this};StringIterator.prototype.next=function(){return this._i<this._l?{done:false,value:this._s.charAt(this._i++)}:doneEnumerator};function ArrayIterable(a){this._a=a}ArrayIterable.prototype[$iterator$]=function(){return new ArrayIterator(this._a)};function ArrayIterator(a){this._a=a;this._l=toLength(a);this._i=0}ArrayIterator.prototype[$iterator$]=function(){return this};ArrayIterator.prototype.next=function(){return this._i<this._l?{done:false,value:this._a[this._i++]}:doneEnumerator};function numberIsFinite(value){return typeof value==="number"&&root.isFinite(value)}function isNan(n){return n!==n}function getIterable(o){var i=o[$iterator$],it;if(!i&&typeof o==="string"){it=new StringIterable(o);return it[$iterator$]()}if(!i&&o.length!==undefined){it=new ArrayIterable(o);return it[$iterator$]()}if(!i){throw new TypeError("Object is not iterable"); }return o[$iterator$]()}function sign(value){var number=+value;if(number===0){return number}if(isNaN(number)){return number}return number<0?-1:1}function toLength(o){var len=+o.length;if(isNaN(len)){return 0}if(len===0||!numberIsFinite(len)){return len}len=sign(len)*Math.floor(Math.abs(len));if(len<=0){return 0}if(len>maxSafeInteger){return maxSafeInteger}return len}var observableFrom=Observable.from=function(iterable,mapFn,thisArg,scheduler){if(iterable==null){throw new Error("iterable cannot be null.")}if(mapFn&&!isFunction(mapFn)){throw new Error("mapFn when provided must be a function")}if(mapFn){var mapper=bindCallback(mapFn,thisArg,2)}isScheduler(scheduler)||(scheduler=currentThreadScheduler);return new FromObservable(iterable,mapper,scheduler)};var FromArrayObservable=function(__super__){inherits(FromArrayObservable,__super__);function FromArrayObservable(args,scheduler){this.args=args;this.scheduler=scheduler;__super__.call(this)}FromArrayObservable.prototype.subscribeCore=function(observer){var sink=new FromArraySink(observer,this);return sink.run()};return FromArrayObservable}(ObservableBase);function FromArraySink(observer,parent){this.observer=observer;this.parent=parent}FromArraySink.prototype.run=function(){var observer=this.observer,args=this.parent.args,len=args.length;function loopRecursive(i,recurse){if(i<len){observer.onNext(args[i]);recurse(i+1)}else{observer.onCompleted()}}return this.parent.scheduler.scheduleRecursiveWithState(0,loopRecursive)};var observableFromArray=Observable.fromArray=function(array,scheduler){isScheduler(scheduler)||(scheduler=currentThreadScheduler);return new FromArrayObservable(array,scheduler)};Observable.generate=function(initialState,condition,iterate,resultSelector,scheduler){isScheduler(scheduler)||(scheduler=currentThreadScheduler);return new AnonymousObservable(function(observer){var first=true,state=initialState;return scheduler.scheduleRecursive(function(self){var hasResult,result;try{if(first){first=false}else{state=iterate(state)}hasResult=condition(state);if(hasResult){result=resultSelector(state)}}catch(exception){observer.onError(exception);return}if(hasResult){observer.onNext(result);self()}else{observer.onCompleted()}})})};function observableOf(scheduler,array){isScheduler(scheduler)||(scheduler=currentThreadScheduler);return new FromArrayObservable(array,scheduler)}Observable.of=function(){var len=arguments.length,args=new Array(len);for(var i=0;i<len;i++){args[i]=arguments[i]}return new FromArrayObservable(args,currentThreadScheduler)};Observable.ofWithScheduler=function(scheduler){var len=arguments.length,args=new Array(len-1);for(var i=1;i<len;i++){args[i-1]=arguments[i]}return new FromArrayObservable(args,scheduler)};Observable.ofArrayChanges=function(array){if(!Array.isArray(array)){throw new TypeError("Array.observe only accepts arrays.")}if(typeof Array.observe!=="function"&&typeof Array.unobserve!=="function"){throw new TypeError("Array.observe is not supported on your platform")}return new AnonymousObservable(function(observer){function observerFn(changes){for(var i=0,len=changes.length;i<len;i++){observer.onNext(changes[i])}}Array.observe(array,observerFn);return function(){Array.unobserve(array,observerFn)}})};Observable.ofObjectChanges=function(obj){if(obj==null){throw new TypeError("object must not be null or undefined.")}if(typeof Object.observe!=="function"&&typeof Object.unobserve!=="function"){throw new TypeError("Array.observe is not supported on your platform")}return new AnonymousObservable(function(observer){function observerFn(changes){for(var i=0,len=changes.length;i<len;i++){observer.onNext(changes[i])}}Object.observe(obj,observerFn);return function(){Object.unobserve(obj,observerFn)}})};var observableNever=Observable.never=function(){return new AnonymousObservable(function(){return disposableEmpty})};Observable.pairs=function(obj,scheduler){scheduler||(scheduler=Rx.Scheduler.currentThread);return new AnonymousObservable(function(observer){var keys=Object.keys(obj),len=keys.length;return scheduler.scheduleRecursiveWithState(0,function(idx,self){if(idx<len){var key=keys[idx];observer.onNext([key,obj[key]]);self(idx+1)}else{observer.onCompleted()}})})};var RangeObservable=function(__super__){inherits(RangeObservable,__super__);function RangeObservable(start,count,scheduler){this.start=start;this.count=count;this.scheduler=scheduler;__super__.call(this)}RangeObservable.prototype.subscribeCore=function(observer){var sink=new RangeSink(observer,this);return sink.run()};return RangeObservable}(ObservableBase);var RangeSink=function(){function RangeSink(observer,parent){this.observer=observer;this.parent=parent}RangeSink.prototype.run=function(){var start=this.parent.start,count=this.parent.count,observer=this.observer;function loopRecursive(i,recurse){if(i<count){observer.onNext(start+i);recurse(i+1)}else{observer.onCompleted()}}return this.parent.scheduler.scheduleRecursiveWithState(0,loopRecursive)};return RangeSink}();Observable.range=function(start,count,scheduler){isScheduler(scheduler)||(scheduler=currentThreadScheduler);return new RangeObservable(start,count,scheduler)};Observable.repeat=function(value,repeatCount,scheduler){isScheduler(scheduler)||(scheduler=currentThreadScheduler);return observableReturn(value,scheduler).repeat(repeatCount==null?-1:repeatCount)};var observableReturn=Observable["return"]=Observable.just=function(value,scheduler){isScheduler(scheduler)||(scheduler=immediateScheduler);return new AnonymousObservable(function(observer){return scheduler.schedule(function(){observer.onNext(value);observer.onCompleted()})})};Observable.returnValue=function(){return observableReturn.apply(null,arguments)};var observableThrow=Observable["throw"]=Observable.throwError=function(error,scheduler){isScheduler(scheduler)||(scheduler=immediateScheduler);return new AnonymousObservable(function(observer){return scheduler.schedule(function(){observer.onError(error)})})};Observable.throwException=function(){return Observable.throwError.apply(null,arguments)};Observable.using=function(resourceFactory,observableFactory){return new AnonymousObservable(function(observer){var disposable=disposableEmpty,resource,source;try{resource=resourceFactory();resource&&(disposable=resource);source=observableFactory(resource)}catch(exception){return new CompositeDisposable(observableThrow(exception).subscribe(observer),disposable)}return new CompositeDisposable(source.subscribe(observer),disposable)})};observableProto.amb=function(rightSource){var leftSource=this;return new AnonymousObservable(function(observer){var choice,leftChoice="L",rightChoice="R",leftSubscription=new SingleAssignmentDisposable,rightSubscription=new SingleAssignmentDisposable;isPromise(rightSource)&&(rightSource=observableFromPromise(rightSource));function choiceL(){if(!choice){choice=leftChoice;rightSubscription.dispose()}}function choiceR(){if(!choice){choice=rightChoice;leftSubscription.dispose()}}leftSubscription.setDisposable(leftSource.subscribe(function(left){choiceL();if(choice===leftChoice){observer.onNext(left)}},function(err){choiceL();if(choice===leftChoice){observer.onError(err)}},function(){choiceL();if(choice===leftChoice){observer.onCompleted()}}));rightSubscription.setDisposable(rightSource.subscribe(function(right){choiceR();if(choice===rightChoice){observer.onNext(right)}},function(err){choiceR();if(choice===rightChoice){observer.onError(err)}},function(){choiceR();if(choice===rightChoice){observer.onCompleted()}}));return new CompositeDisposable(leftSubscription,rightSubscription)})};Observable.amb=function(){var acc=observableNever(),items=[];if(Array.isArray(arguments[0])){items=arguments[0]}else{for(var i=0,len=arguments.length;i<len;i++){items.push(arguments[i])}}function func(previous,current){return previous.amb(current)}for(var i=0,len=items.length;i<len;i++){acc=func(acc,items[i])}return acc};function observableCatchHandler(source,handler){return new AnonymousObservable(function(o){var d1=new SingleAssignmentDisposable,subscription=new SerialDisposable;subscription.setDisposable(d1);d1.setDisposable(source.subscribe(function(x){o.onNext(x)},function(e){try{var result=handler(e)}catch(ex){return o.onError(ex)}isPromise(result)&&(result=observableFromPromise(result));var d=new SingleAssignmentDisposable;subscription.setDisposable(d);d.setDisposable(result.subscribe(o))},function(x){o.onCompleted(x)}));return subscription},source)}observableProto["catch"]=observableProto.catchError=observableProto.catchException=function(handlerOrSecond){return typeof handlerOrSecond==="function"?observableCatchHandler(this,handlerOrSecond):observableCatch([this,handlerOrSecond])};var observableCatch=Observable.catchError=Observable["catch"]=Observable.catchException=function(){var items=[];if(Array.isArray(arguments[0])){items=arguments[0]}else{for(var i=0,len=arguments.length;i<len;i++){items.push(arguments[i])}}return enumerableOf(items).catchError()};observableProto.combineLatest=function(){var len=arguments.length,args=new Array(len);for(var i=0;i<len;i++){args[i]=arguments[i]}if(Array.isArray(args[0])){args[0].unshift(this)}else{args.unshift(this)}return combineLatest.apply(this,args)};var combineLatest=Observable.combineLatest=function(){var len=arguments.length,args=new Array(len);for(var i=0;i<len;i++){args[i]=arguments[i]}var resultSelector=args.pop();Array.isArray(args[0])&&(args=args[0]);return new AnonymousObservable(function(o){var n=args.length,falseFactory=function(){return false},hasValue=arrayInitialize(n,falseFactory),hasValueAll=false,isDone=arrayInitialize(n,falseFactory),values=new Array(n);function next(i){hasValue[i]=true;if(hasValueAll||(hasValueAll=hasValue.every(identity))){try{var res=resultSelector.apply(null,values)}catch(e){return o.onError(e)}o.onNext(res)}else if(isDone.filter(function(x,j){return j!==i}).every(identity)){o.onCompleted()}}function done(i){isDone[i]=true;isDone.every(identity)&&o.onCompleted()}var subscriptions=new Array(n);for(var idx=0;idx<n;idx++){(function(i){var source=args[i],sad=new SingleAssignmentDisposable;isPromise(source)&&(source=observableFromPromise(source));sad.setDisposable(source.subscribe(function(x){values[i]=x;next(i)},function(e){o.onError(e)},function(){done(i)}));subscriptions[i]=sad})(idx)}return new CompositeDisposable(subscriptions)},this)};observableProto.concat=function(){for(var args=[],i=0,len=arguments.length;i<len;i++){args.push(arguments[i])}args.unshift(this);return observableConcat.apply(null,args)};var observableConcat=Observable.concat=function(){var args;if(Array.isArray(arguments[0])){args=arguments[0]}else{args=new Array(arguments.length);for(var i=0,len=arguments.length;i<len;i++){args[i]=arguments[i]}}return enumerableOf(args).concat()};observableProto.concatAll=observableProto.concatObservable=function(){return this.merge(1)};var MergeObservable=function(__super__){inherits(MergeObservable,__super__);function MergeObservable(source,maxConcurrent){this.source=source;this.maxConcurrent=maxConcurrent;__super__.call(this)}MergeObservable.prototype.subscribeCore=function(observer){var g=new CompositeDisposable;g.add(this.source.subscribe(new MergeObserver(observer,this.maxConcurrent,g)));return g};return MergeObservable}(ObservableBase);var MergeObserver=function(){function MergeObserver(o,max,g){this.o=o;this.max=max;this.g=g;this.done=false;this.q=[];this.activeCount=0;this.isStopped=false}MergeObserver.prototype.handleSubscribe=function(xs){var sad=new SingleAssignmentDisposable;this.g.add(sad);isPromise(xs)&&(xs=observableFromPromise(xs));sad.setDisposable(xs.subscribe(new InnerObserver(this,sad)))};MergeObserver.prototype.onNext=function(innerSource){if(this.isStopped){return}if(this.activeCount<this.max){this.activeCount++;this.handleSubscribe(innerSource)}else{this.q.push(innerSource)}};MergeObserver.prototype.onError=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e)}};MergeObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.done=true;this.activeCount===0&&this.o.onCompleted()}};MergeObserver.prototype.dispose=function(){this.isStopped=true};MergeObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e);return true}return false};function InnerObserver(parent,sad){this.parent=parent;this.sad=sad;this.isStopped=false}InnerObserver.prototype.onNext=function(x){if(!this.isStopped){this.parent.o.onNext(x)}};InnerObserver.prototype.onError=function(e){if(!this.isStopped){this.isStopped=true;this.parent.o.onError(e)}};InnerObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;var parent=this.parent;parent.g.remove(this.sad);if(parent.q.length>0){parent.handleSubscribe(parent.q.shift())}else{parent.activeCount--;parent.done&&parent.activeCount===0&&parent.o.onCompleted()}}};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.parent.o.onError(e);return true}return false};return MergeObserver}();observableProto.merge=function(maxConcurrentOrOther){return typeof maxConcurrentOrOther!=="number"?observableMerge(this,maxConcurrentOrOther):new MergeObservable(this,maxConcurrentOrOther)};var observableMerge=Observable.merge=function(){var scheduler,sources=[],i,len=arguments.length;if(!arguments[0]){scheduler=immediateScheduler;for(i=1;i<len;i++){sources.push(arguments[i])}}else if(isScheduler(arguments[0])){scheduler=arguments[0];for(i=1;i<len;i++){sources.push(arguments[i])}}else{scheduler=immediateScheduler;for(i=0;i<len;i++){sources.push(arguments[i])}}if(Array.isArray(sources[0])){sources=sources[0]}return observableOf(scheduler,sources).mergeAll()};var MergeAllObservable=function(__super__){inherits(MergeAllObservable,__super__);function MergeAllObservable(source){this.source=source;__super__.call(this)}MergeAllObservable.prototype.subscribeCore=function(observer){var g=new CompositeDisposable,m=new SingleAssignmentDisposable;g.add(m);m.setDisposable(this.source.subscribe(new MergeAllObserver(observer,g)));return g};return MergeAllObservable}(ObservableBase);var MergeAllObserver=function(){function MergeAllObserver(o,g){this.o=o;this.g=g;this.isStopped=false;this.done=false}MergeAllObserver.prototype.onNext=function(innerSource){if(this.isStopped){return}var sad=new SingleAssignmentDisposable;this.g.add(sad);isPromise(innerSource)&&(innerSource=observableFromPromise(innerSource));sad.setDisposable(innerSource.subscribe(new InnerObserver(this,this.g,sad)))};MergeAllObserver.prototype.onError=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e)}};MergeAllObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.done=true;this.g.length===1&&this.o.onCompleted()}};MergeAllObserver.prototype.dispose=function(){this.isStopped=true};MergeAllObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e);return true}return false};function InnerObserver(parent,g,sad){this.parent=parent;this.g=g;this.sad=sad;this.isStopped=false}InnerObserver.prototype.onNext=function(x){if(!this.isStopped){this.parent.o.onNext(x)}};InnerObserver.prototype.onError=function(e){if(!this.isStopped){this.isStopped=true;this.parent.o.onError(e)}};InnerObserver.prototype.onCompleted=function(){if(!this.isStopped){var parent=this.parent;this.isStopped=true;parent.g.remove(this.sad);parent.done&&parent.g.length===1&&parent.o.onCompleted()}};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.parent.o.onError(e);return true}return false};return MergeAllObserver}();observableProto.mergeAll=observableProto.mergeObservable=function(){return new MergeAllObservable(this)};var CompositeError=Rx.CompositeError=function(errors){this.name="NotImplementedError";this.innerErrors=errors;this.message="This contains multiple errors. Check the innerErrors";Error.call(this)};CompositeError.prototype=Error.prototype;Observable.mergeDelayError=function(){var args;if(Array.isArray(arguments[0])){args=arguments[0]}else{var len=arguments.length;args=new Array(len);for(var i=0;i<len;i++){args[i]=arguments[i]}}var source=observableOf(null,args);return new AnonymousObservable(function(o){var group=new CompositeDisposable,m=new SingleAssignmentDisposable,isStopped=false,errors=[];function setCompletion(){if(errors.length===0){o.onCompleted()}else if(errors.length===1){o.onError(errors[0])}else{o.onError(new CompositeError(errors))}}group.add(m);m.setDisposable(source.subscribe(function(innerSource){var innerSubscription=new SingleAssignmentDisposable;group.add(innerSubscription);isPromise(innerSource)&&(innerSource=observableFromPromise(innerSource));innerSubscription.setDisposable(innerSource.subscribe(function(x){o.onNext(x)},function(e){errors.push(e);group.remove(innerSubscription);isStopped&&group.length===1&&setCompletion()},function(){group.remove(innerSubscription);isStopped&&group.length===1&&setCompletion()}))},function(e){errors.push(e);isStopped=true;group.length===1&&setCompletion()},function(){isStopped=true;group.length===1&&setCompletion()}));return group})};observableProto.onErrorResumeNext=function(second){if(!second){throw new Error("Second observable is required")}return onErrorResumeNext([this,second])};var onErrorResumeNext=Observable.onErrorResumeNext=function(){var sources=[];if(Array.isArray(arguments[0])){sources=arguments[0]}else{for(var i=0,len=arguments.length;i<len;i++){sources.push(arguments[i])}}return new AnonymousObservable(function(observer){var pos=0,subscription=new SerialDisposable,cancelable=immediateScheduler.scheduleRecursive(function(self){var current,d;if(pos<sources.length){current=sources[pos++];isPromise(current)&&(current=observableFromPromise(current));d=new SingleAssignmentDisposable;subscription.setDisposable(d);d.setDisposable(current.subscribe(observer.onNext.bind(observer),self,self))}else{observer.onCompleted()}});return new CompositeDisposable(subscription,cancelable)})};observableProto.skipUntil=function(other){var source=this;return new AnonymousObservable(function(o){var isOpen=false;var disposables=new CompositeDisposable(source.subscribe(function(left){isOpen&&o.onNext(left)},function(e){o.onError(e)},function(){isOpen&&o.onCompleted()}));isPromise(other)&&(other=observableFromPromise(other));var rightSubscription=new SingleAssignmentDisposable;disposables.add(rightSubscription);rightSubscription.setDisposable(other.subscribe(function(){isOpen=true;rightSubscription.dispose()},function(e){o.onError(e)},function(){rightSubscription.dispose()}));return disposables},source)};observableProto["switch"]=observableProto.switchLatest=function(){var sources=this;return new AnonymousObservable(function(observer){var hasLatest=false,innerSubscription=new SerialDisposable,isStopped=false,latest=0,subscription=sources.subscribe(function(innerSource){var d=new SingleAssignmentDisposable,id=++latest;hasLatest=true;innerSubscription.setDisposable(d);isPromise(innerSource)&&(innerSource=observableFromPromise(innerSource));d.setDisposable(innerSource.subscribe(function(x){latest===id&&observer.onNext(x)},function(e){latest===id&&observer.onError(e)},function(){if(latest===id){hasLatest=false;isStopped&&observer.onCompleted()}}))},function(e){observer.onError(e)},function(){isStopped=true;!hasLatest&&observer.onCompleted()});return new CompositeDisposable(subscription,innerSubscription)},sources)};observableProto.takeUntil=function(other){var source=this;return new AnonymousObservable(function(o){isPromise(other)&&(other=observableFromPromise(other));return new CompositeDisposable(source.subscribe(o),other.subscribe(function(){o.onCompleted()},function(e){o.onError(e)},noop))},source)};observableProto.withLatestFrom=function(){var len=arguments.length,args=new Array(len);for(var i=0;i<len;i++){args[i]=arguments[i]}var resultSelector=args.pop(),source=this;if(typeof source==="undefined"){throw new Error("Source observable not found for withLatestFrom().")}if(typeof resultSelector!=="function"){throw new Error("withLatestFrom() expects a resultSelector function.")}if(Array.isArray(args[0])){args=args[0]}return new AnonymousObservable(function(observer){var falseFactory=function(){return false},n=args.length,hasValue=arrayInitialize(n,falseFactory),hasValueAll=false,values=new Array(n);var subscriptions=new Array(n+1);for(var idx=0;idx<n;idx++){(function(i){var other=args[i],sad=new SingleAssignmentDisposable;isPromise(other)&&(other=observableFromPromise(other));sad.setDisposable(other.subscribe(function(x){values[i]=x;hasValue[i]=true;hasValueAll=hasValue.every(identity)},observer.onError.bind(observer),function(){}));subscriptions[i]=sad})(idx)}var sad=new SingleAssignmentDisposable;sad.setDisposable(source.subscribe(function(x){var res;var allValues=[x].concat(values);if(!hasValueAll)return;try{res=resultSelector.apply(null,allValues)}catch(ex){observer.onError(ex);return}observer.onNext(res)},observer.onError.bind(observer),function(){observer.onCompleted()}));subscriptions[n]=sad;return new CompositeDisposable(subscriptions)},this)};function zipArray(second,resultSelector){var first=this;return new AnonymousObservable(function(observer){var index=0,len=second.length;return first.subscribe(function(left){if(index<len){var right=second[index++],result;try{result=resultSelector(left,right)}catch(e){return observer.onError(e)}observer.onNext(result)}else{observer.onCompleted()}},function(e){observer.onError(e)},function(){observer.onCompleted()})},first)}function falseFactory(){return false}function emptyArrayFactory(){return[]}observableProto.zip=function(){if(Array.isArray(arguments[0])){return zipArray.apply(this,arguments)}var len=arguments.length,args=new Array(len);for(var i=0;i<len;i++){args[i]=arguments[i]}var parent=this,resultSelector=args.pop();args.unshift(parent);return new AnonymousObservable(function(observer){var n=args.length,queues=arrayInitialize(n,emptyArrayFactory),isDone=arrayInitialize(n,falseFactory);function next(i){var res,queuedValues;if(queues.every(function(x){return x.length>0})){try{queuedValues=queues.map(function(x){return x.shift()});res=resultSelector.apply(parent,queuedValues)}catch(ex){observer.onError(ex);return}observer.onNext(res)}else if(isDone.filter(function(x,j){return j!==i}).every(identity)){observer.onCompleted()}}function done(i){isDone[i]=true;if(isDone.every(function(x){return x})){observer.onCompleted()}}var subscriptions=new Array(n);for(var idx=0;idx<n;idx++){(function(i){var source=args[i],sad=new SingleAssignmentDisposable;isPromise(source)&&(source=observableFromPromise(source));sad.setDisposable(source.subscribe(function(x){queues[i].push(x);next(i)},function(e){observer.onError(e)},function(){done(i)}));subscriptions[i]=sad})(idx)}return new CompositeDisposable(subscriptions)},parent)};Observable.zip=function(){var len=arguments.length,args=new Array(len);for(var i=0;i<len;i++){args[i]=arguments[i]}var first=args.shift();return first.zip.apply(first,args)};Observable.zipArray=function(){var sources;if(Array.isArray(arguments[0])){sources=arguments[0]}else{var len=arguments.length;sources=new Array(len);for(var i=0;i<len;i++){sources[i]=arguments[i]}}return new AnonymousObservable(function(observer){var n=sources.length,queues=arrayInitialize(n,function(){return[]}),isDone=arrayInitialize(n,function(){return false});function next(i){if(queues.every(function(x){return x.length>0})){var res=queues.map(function(x){return x.shift()});observer.onNext(res)}else if(isDone.filter(function(x,j){return j!==i}).every(identity)){observer.onCompleted();return}}function done(i){isDone[i]=true;if(isDone.every(identity)){observer.onCompleted();return}}var subscriptions=new Array(n);for(var idx=0;idx<n;idx++){(function(i){subscriptions[i]=new SingleAssignmentDisposable;subscriptions[i].setDisposable(sources[i].subscribe(function(x){queues[i].push(x);next(i)},function(e){observer.onError(e)},function(){done(i)}))})(idx)}return new CompositeDisposable(subscriptions)})};observableProto.asObservable=function(){var source=this;return new AnonymousObservable(function(o){return source.subscribe(o)},this)};observableProto.bufferWithCount=function(count,skip){if(typeof skip!=="number"){skip=count}return this.windowWithCount(count,skip).selectMany(function(x){return x.toArray()}).where(function(x){return x.length>0})};observableProto.dematerialize=function(){var source=this;return new AnonymousObservable(function(o){return source.subscribe(function(x){return x.accept(o)},function(e){o.onError(e)},function(){o.onCompleted()})},this)};observableProto.distinctUntilChanged=function(keySelector,comparer){var source=this;comparer||(comparer=defaultComparer);return new AnonymousObservable(function(o){var hasCurrentKey=false,currentKey;return source.subscribe(function(value){var key=value;if(keySelector){try{key=keySelector(value)}catch(e){o.onError(e);return}}if(hasCurrentKey){try{var comparerEquals=comparer(currentKey,key)}catch(e){o.onError(e);return}}if(!hasCurrentKey||!comparerEquals){hasCurrentKey=true;currentKey=key;o.onNext(value)}},function(e){o.onError(e)},function(){o.onCompleted()})},this)};observableProto["do"]=observableProto.tap=observableProto.doAction=function(observerOrOnNext,onError,onCompleted){var source=this,tapObserver=typeof observerOrOnNext==="function"||typeof observerOrOnNext==="undefined"?observerCreate(observerOrOnNext||noop,onError||noop,onCompleted||noop):observerOrOnNext;return new AnonymousObservable(function(observer){return source.subscribe(function(x){try{tapObserver.onNext(x)}catch(e){observer.onError(e)}observer.onNext(x)},function(err){try{tapObserver.onError(err)}catch(e){observer.onError(e)}observer.onError(err)},function(){try{tapObserver.onCompleted()}catch(e){observer.onError(e)}observer.onCompleted()})},this)};observableProto.doOnNext=observableProto.tapOnNext=function(onNext,thisArg){return this.tap(typeof thisArg!=="undefined"?function(x){onNext.call(thisArg,x)}:onNext)};observableProto.doOnError=observableProto.tapOnError=function(onError,thisArg){return this.tap(noop,typeof thisArg!=="undefined"?function(e){onError.call(thisArg,e)}:onError)};observableProto.doOnCompleted=observableProto.tapOnCompleted=function(onCompleted,thisArg){return this.tap(noop,null,typeof thisArg!=="undefined"?function(){onCompleted.call(thisArg)}:onCompleted)};observableProto["finally"]=observableProto.ensure=function(action){var source=this;return new AnonymousObservable(function(observer){var subscription;try{subscription=source.subscribe(observer)}catch(e){action();throw e}return disposableCreate(function(){try{subscription.dispose()}catch(e){throw e}finally{action()}})},this)};observableProto.finallyAction=function(action){return this.ensure(action)};observableProto.ignoreElements=function(){var source=this;return new AnonymousObservable(function(o){return source.subscribe(noop,function(e){o.onError(e)},function(){o.onCompleted()})},source)};observableProto.materialize=function(){var source=this;return new AnonymousObservable(function(observer){return source.subscribe(function(value){observer.onNext(notificationCreateOnNext(value))},function(e){observer.onNext(notificationCreateOnError(e));observer.onCompleted()},function(){observer.onNext(notificationCreateOnCompleted());observer.onCompleted()})},source)};observableProto.repeat=function(repeatCount){return enumerableRepeat(this,repeatCount).concat()};observableProto.retry=function(retryCount){return enumerableRepeat(this,retryCount).catchError()};observableProto.retryWhen=function(notifier){return enumerableRepeat(this).catchErrorWhen(notifier)};observableProto.scan=function(){var hasSeed=false,seed,accumulator,source=this;if(arguments.length===2){hasSeed=true;seed=arguments[0];accumulator=arguments[1]}else{accumulator=arguments[0]}return new AnonymousObservable(function(o){var hasAccumulation,accumulation,hasValue;return source.subscribe(function(x){!hasValue&&(hasValue=true);try{if(hasAccumulation){accumulation=accumulator(accumulation,x)}else{accumulation=hasSeed?accumulator(seed,x):x;hasAccumulation=true}}catch(e){o.onError(e);return}o.onNext(accumulation)},function(e){o.onError(e)},function(){!hasValue&&hasSeed&&o.onNext(seed);o.onCompleted()})},source)};observableProto.skipLast=function(count){if(count<0){throw new ArgumentOutOfRangeError}var source=this;return new AnonymousObservable(function(o){var q=[];return source.subscribe(function(x){q.push(x);q.length>count&&o.onNext(q.shift())},function(e){o.onError(e)},function(){o.onCompleted()})},source)};observableProto.startWith=function(){var values,scheduler,start=0;if(!!arguments.length&&isScheduler(arguments[0])){scheduler=arguments[0];start=1}else{scheduler=immediateScheduler}for(var args=[],i=start,len=arguments.length;i<len;i++){args.push(arguments[i])}return enumerableOf([observableFromArray(args,scheduler),this]).concat()};observableProto.takeLast=function(count){if(count<0){throw new ArgumentOutOfRangeError}var source=this;return new AnonymousObservable(function(o){var q=[];return source.subscribe(function(x){q.push(x);q.length>count&&q.shift()},function(e){o.onError(e)},function(){while(q.length>0){o.onNext(q.shift())}o.onCompleted()})},source)};observableProto.takeLastBuffer=function(count){var source=this;return new AnonymousObservable(function(o){var q=[];return source.subscribe(function(x){q.push(x);q.length>count&&q.shift()},function(e){o.onError(e)},function(){o.onNext(q);o.onCompleted()})},source)};observableProto.windowWithCount=function(count,skip){var source=this;+count||(count=0);Math.abs(count)===Infinity&&(count=0);if(count<=0){throw new ArgumentOutOfRangeError}skip==null&&(skip=count);+skip||(skip=0);Math.abs(skip)===Infinity&&(skip=0);if(skip<=0){throw new ArgumentOutOfRangeError}return new AnonymousObservable(function(observer){var m=new SingleAssignmentDisposable,refCountDisposable=new RefCountDisposable(m),n=0,q=[];function createWindow(){var s=new Subject;q.push(s);observer.onNext(addRef(s,refCountDisposable))}createWindow();m.setDisposable(source.subscribe(function(x){for(var i=0,len=q.length;i<len;i++){q[i].onNext(x)}var c=n-count+1;c>=0&&c%skip===0&&q.shift().onCompleted();++n%skip===0&&createWindow()},function(e){while(q.length>0){q.shift().onError(e)}observer.onError(e)},function(){while(q.length>0){q.shift().onCompleted()}observer.onCompleted()}));return refCountDisposable},source)};function concatMap(source,selector,thisArg){var selectorFunc=bindCallback(selector,thisArg,3);return source.map(function(x,i){var result=selectorFunc(x,i,source);isPromise(result)&&(result=observableFromPromise(result));(isArrayLike(result)||isIterable(result))&&(result=observableFrom(result));return result}).concatAll()}observableProto.selectConcat=observableProto.concatMap=function(selector,resultSelector,thisArg){if(isFunction(selector)&&isFunction(resultSelector)){return this.concatMap(function(x,i){var selectorResult=selector(x,i);isPromise(selectorResult)&&(selectorResult=observableFromPromise(selectorResult));(isArrayLike(selectorResult)||isIterable(selectorResult))&&(selectorResult=observableFrom(selectorResult));return selectorResult.map(function(y,i2){return resultSelector(x,y,i,i2)})})}return isFunction(selector)?concatMap(this,selector,thisArg):concatMap(this,function(){return selector})};observableProto.concatMapObserver=observableProto.selectConcatObserver=function(onNext,onError,onCompleted,thisArg){var source=this,onNextFunc=bindCallback(onNext,thisArg,2),onErrorFunc=bindCallback(onError,thisArg,1),onCompletedFunc=bindCallback(onCompleted,thisArg,0);return new AnonymousObservable(function(observer){var index=0;return source.subscribe(function(x){var result;try{result=onNextFunc(x,index++)}catch(e){observer.onError(e);return}isPromise(result)&&(result=observableFromPromise(result));observer.onNext(result); },function(err){var result;try{result=onErrorFunc(err)}catch(e){observer.onError(e);return}isPromise(result)&&(result=observableFromPromise(result));observer.onNext(result);observer.onCompleted()},function(){var result;try{result=onCompletedFunc()}catch(e){observer.onError(e);return}isPromise(result)&&(result=observableFromPromise(result));observer.onNext(result);observer.onCompleted()})},this).concatAll()};observableProto.defaultIfEmpty=function(defaultValue){var source=this;defaultValue===undefined&&(defaultValue=null);return new AnonymousObservable(function(observer){var found=false;return source.subscribe(function(x){found=true;observer.onNext(x)},function(e){observer.onError(e)},function(){!found&&observer.onNext(defaultValue);observer.onCompleted()})},source)};function arrayIndexOfComparer(array,item,comparer){for(var i=0,len=array.length;i<len;i++){if(comparer(array[i],item)){return i}}return-1}function HashSet(comparer){this.comparer=comparer;this.set=[]}HashSet.prototype.push=function(value){var retValue=arrayIndexOfComparer(this.set,value,this.comparer)===-1;retValue&&this.set.push(value);return retValue};observableProto.distinct=function(keySelector,comparer){var source=this;comparer||(comparer=defaultComparer);return new AnonymousObservable(function(o){var hashSet=new HashSet(comparer);return source.subscribe(function(x){var key=x;if(keySelector){try{key=keySelector(x)}catch(e){o.onError(e);return}}hashSet.push(key)&&o.onNext(x)},function(e){o.onError(e)},function(){o.onCompleted()})},this)};observableProto.groupBy=function(keySelector,elementSelector,comparer){return this.groupByUntil(keySelector,elementSelector,observableNever,comparer)};observableProto.groupByUntil=function(keySelector,elementSelector,durationSelector,comparer){var source=this;elementSelector||(elementSelector=identity);comparer||(comparer=defaultComparer);return new AnonymousObservable(function(observer){function handleError(e){return function(item){item.onError(e)}}var map=new Dictionary(0,comparer),groupDisposable=new CompositeDisposable,refCountDisposable=new RefCountDisposable(groupDisposable);groupDisposable.add(source.subscribe(function(x){var key;try{key=keySelector(x)}catch(e){map.getValues().forEach(handleError(e));observer.onError(e);return}var fireNewMapEntry=false,writer=map.tryGetValue(key);if(!writer){writer=new Subject;map.set(key,writer);fireNewMapEntry=true}if(fireNewMapEntry){var group=new GroupedObservable(key,writer,refCountDisposable),durationGroup=new GroupedObservable(key,writer);try{duration=durationSelector(durationGroup)}catch(e){map.getValues().forEach(handleError(e));observer.onError(e);return}observer.onNext(group);var md=new SingleAssignmentDisposable;groupDisposable.add(md);var expire=function(){map.remove(key)&&writer.onCompleted();groupDisposable.remove(md)};md.setDisposable(duration.take(1).subscribe(noop,function(exn){map.getValues().forEach(handleError(exn));observer.onError(exn)},expire))}var element;try{element=elementSelector(x)}catch(e){map.getValues().forEach(handleError(e));observer.onError(e);return}writer.onNext(element)},function(ex){map.getValues().forEach(handleError(ex));observer.onError(ex)},function(){map.getValues().forEach(function(item){item.onCompleted()});observer.onCompleted()}));return refCountDisposable},source)};var MapObservable=function(__super__){inherits(MapObservable,__super__);function MapObservable(source,selector,thisArg){this.source=source;this.selector=bindCallback(selector,thisArg,3);__super__.call(this)}MapObservable.prototype.internalMap=function(selector,thisArg){var self=this;return new MapObservable(this.source,function(x,i,o){return selector(self.selector(x,i,o),i,o)},thisArg)};MapObservable.prototype.subscribeCore=function(observer){return this.source.subscribe(new MapObserver(observer,this.selector,this))};return MapObservable}(ObservableBase);function MapObserver(observer,selector,source){this.observer=observer;this.selector=selector;this.source=source;this.i=0;this.isStopped=false}MapObserver.prototype.onNext=function(x){if(this.isStopped){return}var result=tryCatch(this.selector).call(this,x,this.i++,this.source);if(result===errorObj){return this.observer.onError(result.e)}this.observer.onNext(result)};MapObserver.prototype.onError=function(e){if(!this.isStopped){this.isStopped=true;this.observer.onError(e)}};MapObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.observer.onCompleted()}};MapObserver.prototype.dispose=function(){this.isStopped=true};MapObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.observer.onError(e);return true}return false};observableProto.map=observableProto.select=function(selector,thisArg){var selectorFn=typeof selector==="function"?selector:function(){return selector};return this instanceof MapObservable?this.internalMap(selectorFn,thisArg):new MapObservable(this,selectorFn,thisArg)};observableProto.pluck=function(){var args=arguments,len=arguments.length;if(len===0){throw new Error("List of properties cannot be empty.")}return this.map(function(x){var currentProp=x;for(var i=0;i<len;i++){var p=currentProp[args[i]];if(typeof p!=="undefined"){currentProp=p}else{return undefined}}return currentProp})};function flatMap(source,selector,thisArg){var selectorFunc=bindCallback(selector,thisArg,3);return source.map(function(x,i){var result=selectorFunc(x,i,source);isPromise(result)&&(result=observableFromPromise(result));(isArrayLike(result)||isIterable(result))&&(result=observableFrom(result));return result}).mergeAll()}observableProto.selectMany=observableProto.flatMap=function(selector,resultSelector,thisArg){if(isFunction(selector)&&isFunction(resultSelector)){return this.flatMap(function(x,i){var selectorResult=selector(x,i);isPromise(selectorResult)&&(selectorResult=observableFromPromise(selectorResult));(isArrayLike(selectorResult)||isIterable(selectorResult))&&(selectorResult=observableFrom(selectorResult));return selectorResult.map(function(y,i2){return resultSelector(x,y,i,i2)})},thisArg)}return isFunction(selector)?flatMap(this,selector,thisArg):flatMap(this,function(){return selector})};observableProto.flatMapObserver=observableProto.selectManyObserver=function(onNext,onError,onCompleted,thisArg){var source=this;return new AnonymousObservable(function(observer){var index=0;return source.subscribe(function(x){var result;try{result=onNext.call(thisArg,x,index++)}catch(e){observer.onError(e);return}isPromise(result)&&(result=observableFromPromise(result));observer.onNext(result)},function(err){var result;try{result=onError.call(thisArg,err)}catch(e){observer.onError(e);return}isPromise(result)&&(result=observableFromPromise(result));observer.onNext(result);observer.onCompleted()},function(){var result;try{result=onCompleted.call(thisArg)}catch(e){observer.onError(e);return}isPromise(result)&&(result=observableFromPromise(result));observer.onNext(result);observer.onCompleted()})},source).mergeAll()};observableProto.selectSwitch=observableProto.flatMapLatest=observableProto.switchMap=function(selector,thisArg){return this.select(selector,thisArg).switchLatest()};observableProto.skip=function(count){if(count<0){throw new ArgumentOutOfRangeError}var source=this;return new AnonymousObservable(function(o){var remaining=count;return source.subscribe(function(x){if(remaining<=0){o.onNext(x)}else{remaining--}},function(e){o.onError(e)},function(){o.onCompleted()})},source)};observableProto.skipWhile=function(predicate,thisArg){var source=this,callback=bindCallback(predicate,thisArg,3);return new AnonymousObservable(function(o){var i=0,running=false;return source.subscribe(function(x){if(!running){try{running=!callback(x,i++,source)}catch(e){o.onError(e);return}}running&&o.onNext(x)},function(e){o.onError(e)},function(){o.onCompleted()})},source)};observableProto.take=function(count,scheduler){if(count<0){throw new ArgumentOutOfRangeError}if(count===0){return observableEmpty(scheduler)}var source=this;return new AnonymousObservable(function(o){var remaining=count;return source.subscribe(function(x){if(remaining-->0){o.onNext(x);remaining===0&&o.onCompleted()}},function(e){o.onError(e)},function(){o.onCompleted()})},source)};observableProto.takeWhile=function(predicate,thisArg){var source=this,callback=bindCallback(predicate,thisArg,3);return new AnonymousObservable(function(o){var i=0,running=true;return source.subscribe(function(x){if(running){try{running=callback(x,i++,source)}catch(e){o.onError(e);return}if(running){o.onNext(x)}else{o.onCompleted()}}},function(e){o.onError(e)},function(){o.onCompleted()})},source)};var FilterObservable=function(__super__){inherits(FilterObservable,__super__);function FilterObservable(source,predicate,thisArg){this.source=source;this.predicate=bindCallback(predicate,thisArg,3);__super__.call(this)}FilterObservable.prototype.subscribeCore=function(observer){return this.source.subscribe(new FilterObserver(observer,this.predicate,this))};FilterObservable.prototype.internalFilter=function(predicate,thisArg){var self=this;return new FilterObservable(this.source,function(x,i,o){return self.predicate(x,i,o)&&predicate(x,i,o)},thisArg)};return FilterObservable}(ObservableBase);function FilterObserver(observer,predicate,source){this.observer=observer;this.predicate=predicate;this.source=source;this.i=0;this.isStopped=false}FilterObserver.prototype.onNext=function(x){if(this.isStopped){return}var shouldYield=tryCatch(this.predicate).call(this,x,this.i++,this.source);if(shouldYield===errorObj){return this.observer.onError(shouldYield.e)}shouldYield&&this.observer.onNext(x)};FilterObserver.prototype.onError=function(e){if(!this.isStopped){this.isStopped=true;this.observer.onError(e)}};FilterObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.observer.onCompleted()}};FilterObserver.prototype.dispose=function(){this.isStopped=true};FilterObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.observer.onError(e);return true}return false};observableProto.filter=observableProto.where=function(predicate,thisArg){return this instanceof FilterObservable?this.internalFilter(predicate,thisArg):new FilterObservable(this,predicate,thisArg)};function extremaBy(source,keySelector,comparer){return new AnonymousObservable(function(o){var hasValue=false,lastKey=null,list=[];return source.subscribe(function(x){var comparison,key;try{key=keySelector(x)}catch(ex){o.onError(ex);return}comparison=0;if(!hasValue){hasValue=true;lastKey=key}else{try{comparison=comparer(key,lastKey)}catch(ex1){o.onError(ex1);return}}if(comparison>0){lastKey=key;list=[]}if(comparison>=0){list.push(x)}},function(e){o.onError(e)},function(){o.onNext(list);o.onCompleted()})},source)}function firstOnly(x){if(x.length===0){throw new EmptyError}return x[0]}observableProto.aggregate=function(){var hasSeed=false,accumulator,seed,source=this;if(arguments.length===2){hasSeed=true;seed=arguments[0];accumulator=arguments[1]}else{accumulator=arguments[0]}return new AnonymousObservable(function(o){var hasAccumulation,accumulation,hasValue;return source.subscribe(function(x){!hasValue&&(hasValue=true);try{if(hasAccumulation){accumulation=accumulator(accumulation,x)}else{accumulation=hasSeed?accumulator(seed,x):x;hasAccumulation=true}}catch(e){return o.onError(e)}},function(e){o.onError(e)},function(){hasValue&&o.onNext(accumulation);!hasValue&&hasSeed&&o.onNext(seed);!hasValue&&!hasSeed&&o.onError(new EmptyError);o.onCompleted()})},source)};observableProto.reduce=function(accumulator){var hasSeed=false,seed,source=this;if(arguments.length===2){hasSeed=true;seed=arguments[1]}return new AnonymousObservable(function(o){var hasAccumulation,accumulation,hasValue;return source.subscribe(function(x){!hasValue&&(hasValue=true);try{if(hasAccumulation){accumulation=accumulator(accumulation,x)}else{accumulation=hasSeed?accumulator(seed,x):x;hasAccumulation=true}}catch(e){return o.onError(e)}},function(e){o.onError(e)},function(){hasValue&&o.onNext(accumulation);!hasValue&&hasSeed&&o.onNext(seed);!hasValue&&!hasSeed&&o.onError(new EmptyError);o.onCompleted()})},source)};observableProto.some=function(predicate,thisArg){var source=this;return predicate?source.filter(predicate,thisArg).some():new AnonymousObservable(function(observer){return source.subscribe(function(){observer.onNext(true);observer.onCompleted()},function(e){observer.onError(e)},function(){observer.onNext(false);observer.onCompleted()})},source)};observableProto.any=function(){return this.some.apply(this,arguments)};observableProto.isEmpty=function(){return this.any().map(not)};observableProto.every=function(predicate,thisArg){return this.filter(function(v){return!predicate(v)},thisArg).some().map(not)};observableProto.all=function(){return this.every.apply(this,arguments)};observableProto.includes=function(searchElement,fromIndex){var source=this;function comparer(a,b){return a===0&&b===0||(a===b||isNaN(a)&&isNaN(b))}return new AnonymousObservable(function(o){var i=0,n=+fromIndex||0;Math.abs(n)===Infinity&&(n=0);if(n<0){o.onNext(false);o.onCompleted();return disposableEmpty}return source.subscribe(function(x){if(i++>=n&&comparer(x,searchElement)){o.onNext(true);o.onCompleted()}},function(e){o.onError(e)},function(){o.onNext(false);o.onCompleted()})},this)};observableProto.contains=function(searchElement,fromIndex){observableProto.includes(searchElement,fromIndex)};observableProto.count=function(predicate,thisArg){return predicate?this.filter(predicate,thisArg).count():this.reduce(function(count){return count+1},0)};observableProto.indexOf=function(searchElement,fromIndex){var source=this;return new AnonymousObservable(function(o){var i=0,n=+fromIndex||0;Math.abs(n)===Infinity&&(n=0);if(n<0){o.onNext(-1);o.onCompleted();return disposableEmpty}return source.subscribe(function(x){if(i>=n&&x===searchElement){o.onNext(i);o.onCompleted()}i++},function(e){o.onError(e)},function(){o.onNext(-1);o.onCompleted()})},source)};observableProto.sum=function(keySelector,thisArg){return keySelector&&isFunction(keySelector)?this.map(keySelector,thisArg).sum():this.reduce(function(prev,curr){return prev+curr},0)};observableProto.minBy=function(keySelector,comparer){comparer||(comparer=defaultSubComparer);return extremaBy(this,keySelector,function(x,y){return comparer(x,y)*-1})};observableProto.min=function(comparer){return this.minBy(identity,comparer).map(function(x){return firstOnly(x)})};observableProto.maxBy=function(keySelector,comparer){comparer||(comparer=defaultSubComparer);return extremaBy(this,keySelector,comparer)};observableProto.max=function(comparer){return this.maxBy(identity,comparer).map(function(x){return firstOnly(x)})};observableProto.average=function(keySelector,thisArg){return keySelector&&isFunction(keySelector)?this.map(keySelector,thisArg).average():this.reduce(function(prev,cur){return{sum:prev.sum+cur,count:prev.count+1}},{sum:0,count:0}).map(function(s){if(s.count===0){throw new EmptyError}return s.sum/s.count})};observableProto.sequenceEqual=function(second,comparer){var first=this;comparer||(comparer=defaultComparer);return new AnonymousObservable(function(o){var donel=false,doner=false,ql=[],qr=[];var subscription1=first.subscribe(function(x){var equal,v;if(qr.length>0){v=qr.shift();try{equal=comparer(v,x)}catch(e){o.onError(e);return}if(!equal){o.onNext(false);o.onCompleted()}}else if(doner){o.onNext(false);o.onCompleted()}else{ql.push(x)}},function(e){o.onError(e)},function(){donel=true;if(ql.length===0){if(qr.length>0){o.onNext(false);o.onCompleted()}else if(doner){o.onNext(true);o.onCompleted()}}});(isArrayLike(second)||isIterable(second))&&(second=observableFrom(second));isPromise(second)&&(second=observableFromPromise(second));var subscription2=second.subscribe(function(x){var equal;if(ql.length>0){var v=ql.shift();try{equal=comparer(v,x)}catch(exception){o.onError(exception);return}if(!equal){o.onNext(false);o.onCompleted()}}else if(donel){o.onNext(false);o.onCompleted()}else{qr.push(x)}},function(e){o.onError(e)},function(){doner=true;if(qr.length===0){if(ql.length>0){o.onNext(false);o.onCompleted()}else if(donel){o.onNext(true);o.onCompleted()}}});return new CompositeDisposable(subscription1,subscription2)},first)};function elementAtOrDefault(source,index,hasDefault,defaultValue){if(index<0){throw new ArgumentOutOfRangeError}return new AnonymousObservable(function(o){var i=index;return source.subscribe(function(x){if(i--===0){o.onNext(x);o.onCompleted()}},function(e){o.onError(e)},function(){if(!hasDefault){o.onError(new ArgumentOutOfRangeError)}else{o.onNext(defaultValue);o.onCompleted()}})},source)}observableProto.elementAt=function(index){return elementAtOrDefault(this,index,false)};observableProto.elementAtOrDefault=function(index,defaultValue){return elementAtOrDefault(this,index,true,defaultValue)};function singleOrDefaultAsync(source,hasDefault,defaultValue){return new AnonymousObservable(function(o){var value=defaultValue,seenValue=false;return source.subscribe(function(x){if(seenValue){o.onError(new Error("Sequence contains more than one element"))}else{value=x;seenValue=true}},function(e){o.onError(e)},function(){if(!seenValue&&!hasDefault){o.onError(new EmptyError)}else{o.onNext(value);o.onCompleted()}})},source)}observableProto.single=function(predicate,thisArg){return predicate&&isFunction(predicate)?this.where(predicate,thisArg).single():singleOrDefaultAsync(this,false)};observableProto.singleOrDefault=function(predicate,defaultValue,thisArg){return predicate&&isFunction(predicate)?this.filter(predicate,thisArg).singleOrDefault(null,defaultValue):singleOrDefaultAsync(this,true,defaultValue)};function firstOrDefaultAsync(source,hasDefault,defaultValue){return new AnonymousObservable(function(o){return source.subscribe(function(x){o.onNext(x);o.onCompleted()},function(e){o.onError(e)},function(){if(!hasDefault){o.onError(new EmptyError)}else{o.onNext(defaultValue);o.onCompleted()}})},source)}observableProto.first=function(predicate,thisArg){return predicate?this.where(predicate,thisArg).first():firstOrDefaultAsync(this,false)};observableProto.firstOrDefault=function(predicate,defaultValue,thisArg){return predicate?this.where(predicate).firstOrDefault(null,defaultValue):firstOrDefaultAsync(this,true,defaultValue)};function lastOrDefaultAsync(source,hasDefault,defaultValue){return new AnonymousObservable(function(o){var value=defaultValue,seenValue=false;return source.subscribe(function(x){value=x;seenValue=true},function(e){o.onError(e)},function(){if(!seenValue&&!hasDefault){o.onError(new EmptyError)}else{o.onNext(value);o.onCompleted()}})},source)}observableProto.last=function(predicate,thisArg){return predicate?this.where(predicate,thisArg).last():lastOrDefaultAsync(this,false)};observableProto.lastOrDefault=function(predicate,defaultValue,thisArg){return predicate?this.where(predicate,thisArg).lastOrDefault(null,defaultValue):lastOrDefaultAsync(this,true,defaultValue)};function findValue(source,predicate,thisArg,yieldIndex){var callback=bindCallback(predicate,thisArg,3);return new AnonymousObservable(function(o){var i=0;return source.subscribe(function(x){var shouldRun;try{shouldRun=callback(x,i,source)}catch(e){o.onError(e);return}if(shouldRun){o.onNext(yieldIndex?i:x);o.onCompleted()}else{i++}},function(e){o.onError(e)},function(){o.onNext(yieldIndex?-1:undefined);o.onCompleted()})},source)}observableProto.find=function(predicate,thisArg){return findValue(this,predicate,thisArg,false)};observableProto.findIndex=function(predicate,thisArg){return findValue(this,predicate,thisArg,true)};observableProto.toSet=function(){if(typeof root.Set==="undefined"){throw new TypeError}var source=this;return new AnonymousObservable(function(o){var s=new root.Set;return source.subscribe(function(x){s.add(x)},function(e){o.onError(e)},function(){o.onNext(s);o.onCompleted()})},source)};observableProto.toMap=function(keySelector,elementSelector){if(typeof root.Map==="undefined"){throw new TypeError}var source=this;return new AnonymousObservable(function(o){var m=new root.Map;return source.subscribe(function(x){var key;try{key=keySelector(x)}catch(e){o.onError(e);return}var element=x;if(elementSelector){try{element=elementSelector(x)}catch(e){o.onError(e);return}}m.set(key,element)},function(e){o.onError(e)},function(){o.onNext(m);o.onCompleted()})},source)};var fnString="function",throwString="throw",isObject=Rx.internals.isObject;function toThunk(obj,ctx){if(Array.isArray(obj)){return objectToThunk.call(ctx,obj)}if(isGeneratorFunction(obj)){return observableSpawn(obj.call(ctx))}if(isGenerator(obj)){return observableSpawn(obj)}if(isObservable(obj)){return observableToThunk(obj)}if(isPromise(obj)){return promiseToThunk(obj)}if(typeof obj===fnString){return obj}if(isObject(obj)||Array.isArray(obj)){return objectToThunk.call(ctx,obj)}return obj}function objectToThunk(obj){var ctx=this;return function(done){var keys=Object.keys(obj),pending=keys.length,results=new obj.constructor,finished;if(!pending){timeoutScheduler.schedule(function(){done(null,results)});return}for(var i=0,len=keys.length;i<len;i++){run(obj[keys[i]],keys[i])}function run(fn,key){if(finished){return}try{fn=toThunk(fn,ctx);if(typeof fn!==fnString){results[key]=fn;return--pending||done(null,results)}fn.call(ctx,function(err,res){if(finished){return}if(err){finished=true;return done(err)}results[key]=res;--pending||done(null,results)})}catch(e){finished=true;done(e)}}}}function observableToThunk(observable){return function(fn){var value,hasValue=false;observable.subscribe(function(v){value=v;hasValue=true},fn,function(){hasValue&&fn(null,value)})}}function promiseToThunk(promise){return function(fn){promise.then(function(res){fn(null,res)},fn)}}function isObservable(obj){return obj&&typeof obj.subscribe===fnString}function isGeneratorFunction(obj){return obj&&obj.constructor&&obj.constructor.name==="GeneratorFunction"}function isGenerator(obj){return obj&&typeof obj.next===fnString&&typeof obj[throwString]===fnString}var observableSpawn=Rx.spawn=function(fn){var isGenFun=isGeneratorFunction(fn);return function(done){var ctx=this,gen=fn;if(isGenFun){for(var args=[],i=0,len=arguments.length;i<len;i++){args.push(arguments[i])}var len=args.length,hasCallback=len&&typeof args[len-1]===fnString;done=hasCallback?args.pop():handleError;gen=fn.apply(this,args)}else{done=done||handleError}next();function exit(err,res){timeoutScheduler.schedule(done.bind(ctx,err,res))}function next(err,res){var ret;if(arguments.length>2){for(var res=[],i=1,len=arguments.length;i<len;i++){res.push(arguments[i])}}if(err){try{ret=gen[throwString](err)}catch(e){return exit(e)}}if(!err){try{ret=gen.next(res)}catch(e){return exit(e)}}if(ret.done){return exit(null,ret.value)}ret.value=toThunk(ret.value,ctx);if(typeof ret.value===fnString){var called=false;try{ret.value.call(ctx,function(){if(called){return}called=true;next.apply(ctx,arguments)})}catch(e){timeoutScheduler.schedule(function(){if(called){return}called=true;next.call(ctx,e)})}return}next(new TypeError("Rx.spawn only supports a function, Promise, Observable, Object or Array."))}}};function handleError(err){if(!err){return}timeoutScheduler.schedule(function(){throw err})}Observable.start=function(func,context,scheduler){return observableToAsync(func,context,scheduler)()};var observableToAsync=Observable.toAsync=function(func,context,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);return function(){var args=arguments,subject=new AsyncSubject;scheduler.schedule(function(){var result;try{result=func.apply(context,args)}catch(e){subject.onError(e);return}subject.onNext(result);subject.onCompleted()});return subject.asObservable()}};Observable.fromCallback=function(func,context,selector){return function(){for(var args=[],i=0,len=arguments.length;i<len;i++){args.push(arguments[i])}return new AnonymousObservable(function(observer){function handler(){var results=arguments;if(selector){try{results=selector(results)}catch(e){return observer.onError(e)}observer.onNext(results)}else{if(results.length<=1){observer.onNext.apply(observer,results)}else{observer.onNext(results)}}observer.onCompleted()}args.push(handler);func.apply(context,args)}).publishLast().refCount()}};Observable.fromNodeCallback=function(func,context,selector){return function(){var len=arguments.length,args=new Array(len);for(var i=0;i<len;i++){args[i]=arguments[i]}return new AnonymousObservable(function(observer){function handler(err){if(err){observer.onError(err);return}var len=arguments.length,results=[];for(var i=1;i<len;i++){results[i-1]=arguments[i]}if(selector){try{results=selector(results)}catch(e){return observer.onError(e)}observer.onNext(results)}else{if(results.length<=1){observer.onNext.apply(observer,results)}else{observer.onNext(results)}}observer.onCompleted()}args.push(handler);func.apply(context,args)}).publishLast().refCount()}};function createListener(element,name,handler){if(element.addEventListener){element.addEventListener(name,handler,false);return disposableCreate(function(){element.removeEventListener(name,handler,false)})}throw new Error("No listener found")}function createEventListener(el,eventName,handler){var disposables=new CompositeDisposable;if(Object.prototype.toString.call(el)==="[object NodeList]"){for(var i=0,len=el.length;i<len;i++){disposables.add(createEventListener(el.item(i),eventName,handler))}}else if(el){disposables.add(createListener(el,eventName,handler))}return disposables}Rx.config.useNativeEvents=false;Observable.fromEvent=function(element,eventName,selector){if(element.addListener){return fromEventPattern(function(h){element.addListener(eventName,h)},function(h){element.removeListener(eventName,h)},selector)}if(!Rx.config.useNativeEvents){if(typeof element.on==="function"&&typeof element.off==="function"){return fromEventPattern(function(h){element.on(eventName,h)},function(h){element.off(eventName,h)},selector)}}return new AnonymousObservable(function(observer){return createEventListener(element,eventName,function handler(e){var results=e;if(selector){try{results=selector(arguments)}catch(err){return observer.onError(err)}}observer.onNext(results)})}).publish().refCount()};var fromEventPattern=Observable.fromEventPattern=function(addHandler,removeHandler,selector){return new AnonymousObservable(function(observer){function innerHandler(e){var result=e;if(selector){try{result=selector(arguments)}catch(err){return observer.onError(err)}}observer.onNext(result)}var returnValue=addHandler(innerHandler);return disposableCreate(function(){if(removeHandler){removeHandler(innerHandler,returnValue)}})}).publish().refCount()};Observable.startAsync=function(functionAsync){var promise;try{promise=functionAsync()}catch(e){return observableThrow(e)}return observableFromPromise(promise)};var PausableObservable=function(__super__){inherits(PausableObservable,__super__);function subscribe(observer){var conn=this.source.publish(),subscription=conn.subscribe(observer),connection=disposableEmpty;var pausable=this.pauser.distinctUntilChanged().subscribe(function(b){if(b){connection=conn.connect()}else{connection.dispose();connection=disposableEmpty}});return new CompositeDisposable(subscription,connection,pausable)}function PausableObservable(source,pauser){this.source=source;this.controller=new Subject;if(pauser&&pauser.subscribe){this.pauser=this.controller.merge(pauser)}else{this.pauser=this.controller}__super__.call(this,subscribe,source)}PausableObservable.prototype.pause=function(){this.controller.onNext(false)};PausableObservable.prototype.resume=function(){this.controller.onNext(true)};return PausableObservable}(Observable);observableProto.pausable=function(pauser){return new PausableObservable(this,pauser)};function combineLatestSource(source,subject,resultSelector){return new AnonymousObservable(function(o){var hasValue=[false,false],hasValueAll=false,isDone=false,values=new Array(2),err;function next(x,i){values[i]=x;var res;hasValue[i]=true;if(hasValueAll||(hasValueAll=hasValue.every(identity))){if(err){o.onError(err);return}try{res=resultSelector.apply(null,values)}catch(ex){o.onError(ex);return}o.onNext(res)}if(isDone&&values[1]){o.onCompleted()}}return new CompositeDisposable(source.subscribe(function(x){next(x,0)},function(e){if(values[1]){o.onError(e)}else{err=e}},function(){isDone=true;values[1]&&o.onCompleted()}),subject.subscribe(function(x){next(x,1)},function(e){o.onError(e)},function(){isDone=true;next(true,1)}))},source)}var PausableBufferedObservable=function(__super__){inherits(PausableBufferedObservable,__super__);function subscribe(o){var q=[],previousShouldFire;var subscription=combineLatestSource(this.source,this.pauser.distinctUntilChanged().startWith(false),function(data,shouldFire){return{data:data,shouldFire:shouldFire}}).subscribe(function(results){if(previousShouldFire!==undefined&&results.shouldFire!=previousShouldFire){previousShouldFire=results.shouldFire;if(results.shouldFire){while(q.length>0){o.onNext(q.shift())}}}else{previousShouldFire=results.shouldFire;if(results.shouldFire){o.onNext(results.data)}else{q.push(results.data)}}},function(err){while(q.length>0){o.onNext(q.shift())}o.onError(err)},function(){while(q.length>0){o.onNext(q.shift())}o.onCompleted()});return subscription}function PausableBufferedObservable(source,pauser){this.source=source;this.controller=new Subject;if(pauser&&pauser.subscribe){this.pauser=this.controller.merge(pauser)}else{this.pauser=this.controller}__super__.call(this,subscribe,source)}PausableBufferedObservable.prototype.pause=function(){this.controller.onNext(false)};PausableBufferedObservable.prototype.resume=function(){this.controller.onNext(true)};return PausableBufferedObservable}(Observable);observableProto.pausableBuffered=function(subject){return new PausableBufferedObservable(this,subject)};var ControlledObservable=function(__super__){inherits(ControlledObservable,__super__);function subscribe(observer){return this.source.subscribe(observer)}function ControlledObservable(source,enableQueue){__super__.call(this,subscribe,source);this.subject=new ControlledSubject(enableQueue);this.source=source.multicast(this.subject).refCount()}ControlledObservable.prototype.request=function(numberOfItems){if(numberOfItems==null){numberOfItems=-1}return this.subject.request(numberOfItems)};return ControlledObservable}(Observable);var ControlledSubject=function(__super__){function subscribe(observer){return this.subject.subscribe(observer)}inherits(ControlledSubject,__super__);function ControlledSubject(enableQueue){enableQueue==null&&(enableQueue=true);__super__.call(this,subscribe);this.subject=new Subject;this.enableQueue=enableQueue;this.queue=enableQueue?[]:null;this.requestedCount=0;this.requestedDisposable=disposableEmpty;this.error=null;this.hasFailed=false;this.hasCompleted=false}addProperties(ControlledSubject.prototype,Observer,{onCompleted:function(){this.hasCompleted=true;if(!this.enableQueue||this.queue.length===0)this.subject.onCompleted();else this.queue.push(Rx.Notification.createOnCompleted())},onError:function(error){this.hasFailed=true;this.error=error;if(!this.enableQueue||this.queue.length===0)this.subject.onError(error);else this.queue.push(Rx.Notification.createOnError(error))},onNext:function(value){var hasRequested=false;if(this.requestedCount===0){this.enableQueue&&this.queue.push(Rx.Notification.createOnNext(value))}else{this.requestedCount!==-1&&this.requestedCount--===0&&this.disposeCurrentRequest();hasRequested=true}hasRequested&&this.subject.onNext(value)},_processRequest:function(numberOfItems){if(this.enableQueue){while(this.queue.length>=numberOfItems&&numberOfItems>0||this.queue.length>0&&this.queue[0].kind!=="N"){var first=this.queue.shift();first.accept(this.subject);if(first.kind==="N")numberOfItems--;else{this.disposeCurrentRequest();this.queue=[]}}return{numberOfItems:numberOfItems,returnValue:this.queue.length!==0}}return{numberOfItems:numberOfItems, returnValue:false}},request:function(number){this.disposeCurrentRequest();var self=this,r=this._processRequest(number);var number=r.numberOfItems;if(!r.returnValue){this.requestedCount=number;this.requestedDisposable=disposableCreate(function(){self.requestedCount=0});return this.requestedDisposable}else{return disposableEmpty}},disposeCurrentRequest:function(){this.requestedDisposable.dispose();this.requestedDisposable=disposableEmpty}});return ControlledSubject}(Observable);observableProto.controlled=function(enableQueue){if(enableQueue==null){enableQueue=true}return new ControlledObservable(this,enableQueue)};var StopAndWaitObservable=function(__super__){function subscribe(observer){this.subscription=this.source.subscribe(new StopAndWaitObserver(observer,this,this.subscription));var self=this;timeoutScheduler.schedule(function(){self.source.request(1)});return this.subscription}inherits(StopAndWaitObservable,__super__);function StopAndWaitObservable(source){__super__.call(this,subscribe,source);this.source=source}var StopAndWaitObserver=function(__sub__){inherits(StopAndWaitObserver,__sub__);function StopAndWaitObserver(observer,observable,cancel){__sub__.call(this);this.observer=observer;this.observable=observable;this.cancel=cancel}var stopAndWaitObserverProto=StopAndWaitObserver.prototype;stopAndWaitObserverProto.completed=function(){this.observer.onCompleted();this.dispose()};stopAndWaitObserverProto.error=function(error){this.observer.onError(error);this.dispose()};stopAndWaitObserverProto.next=function(value){this.observer.onNext(value);var self=this;timeoutScheduler.schedule(function(){self.observable.source.request(1)})};stopAndWaitObserverProto.dispose=function(){this.observer=null;if(this.cancel){this.cancel.dispose();this.cancel=null}__sub__.prototype.dispose.call(this)};return StopAndWaitObserver}(AbstractObserver);return StopAndWaitObservable}(Observable);ControlledObservable.prototype.stopAndWait=function(){return new StopAndWaitObservable(this)};var WindowedObservable=function(__super__){function subscribe(observer){this.subscription=this.source.subscribe(new WindowedObserver(observer,this,this.subscription));var self=this;timeoutScheduler.schedule(function(){self.source.request(self.windowSize)});return this.subscription}inherits(WindowedObservable,__super__);function WindowedObservable(source,windowSize){__super__.call(this,subscribe,source);this.source=source;this.windowSize=windowSize}var WindowedObserver=function(__sub__){inherits(WindowedObserver,__sub__);function WindowedObserver(observer,observable,cancel){this.observer=observer;this.observable=observable;this.cancel=cancel;this.received=0}var windowedObserverPrototype=WindowedObserver.prototype;windowedObserverPrototype.completed=function(){this.observer.onCompleted();this.dispose()};windowedObserverPrototype.error=function(error){this.observer.onError(error);this.dispose()};windowedObserverPrototype.next=function(value){this.observer.onNext(value);this.received=++this.received%this.observable.windowSize;if(this.received===0){var self=this;timeoutScheduler.schedule(function(){self.observable.source.request(self.observable.windowSize)})}};windowedObserverPrototype.dispose=function(){this.observer=null;if(this.cancel){this.cancel.dispose();this.cancel=null}__sub__.prototype.dispose.call(this)};return WindowedObserver}(AbstractObserver);return WindowedObservable}(Observable);ControlledObservable.prototype.windowed=function(windowSize){return new WindowedObservable(this,windowSize)};observableProto.multicast=function(subjectOrSubjectSelector,selector){var source=this;return typeof subjectOrSubjectSelector==="function"?new AnonymousObservable(function(observer){var connectable=source.multicast(subjectOrSubjectSelector());return new CompositeDisposable(selector(connectable).subscribe(observer),connectable.connect())},source):new ConnectableObservable(source,subjectOrSubjectSelector)};observableProto.publish=function(selector){return selector&&isFunction(selector)?this.multicast(function(){return new Subject},selector):this.multicast(new Subject)};observableProto.share=function(){return this.publish().refCount()};observableProto.publishLast=function(selector){return selector&&isFunction(selector)?this.multicast(function(){return new AsyncSubject},selector):this.multicast(new AsyncSubject)};observableProto.publishValue=function(initialValueOrSelector,initialValue){return arguments.length===2?this.multicast(function(){return new BehaviorSubject(initialValue)},initialValueOrSelector):this.multicast(new BehaviorSubject(initialValueOrSelector))};observableProto.shareValue=function(initialValue){return this.publishValue(initialValue).refCount()};observableProto.replay=function(selector,bufferSize,windowSize,scheduler){return selector&&isFunction(selector)?this.multicast(function(){return new ReplaySubject(bufferSize,windowSize,scheduler)},selector):this.multicast(new ReplaySubject(bufferSize,windowSize,scheduler))};observableProto.shareReplay=function(bufferSize,windowSize,scheduler){return this.replay(null,bufferSize,windowSize,scheduler).refCount()};var InnerSubscription=function(subject,observer){this.subject=subject;this.observer=observer};InnerSubscription.prototype.dispose=function(){if(!this.subject.isDisposed&&this.observer!==null){var idx=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(idx,1);this.observer=null}};var BehaviorSubject=Rx.BehaviorSubject=function(__super__){function subscribe(observer){checkDisposed(this);if(!this.isStopped){this.observers.push(observer);observer.onNext(this.value);return new InnerSubscription(this,observer)}if(this.hasError){observer.onError(this.error)}else{observer.onCompleted()}return disposableEmpty}inherits(BehaviorSubject,__super__);function BehaviorSubject(value){__super__.call(this,subscribe);this.value=value,this.observers=[],this.isDisposed=false,this.isStopped=false,this.hasError=false}addProperties(BehaviorSubject.prototype,Observer,{getValue:function(){checkDisposed(this);if(this.hasError){throw this.error}return this.value},hasObservers:function(){return this.observers.length>0},onCompleted:function(){checkDisposed(this);if(this.isStopped){return}this.isStopped=true;for(var i=0,os=cloneArray(this.observers),len=os.length;i<len;i++){os[i].onCompleted()}this.observers.length=0},onError:function(error){checkDisposed(this);if(this.isStopped){return}this.isStopped=true;this.hasError=true;this.error=error;for(var i=0,os=cloneArray(this.observers),len=os.length;i<len;i++){os[i].onError(error)}this.observers.length=0},onNext:function(value){checkDisposed(this);if(this.isStopped){return}this.value=value;for(var i=0,os=cloneArray(this.observers),len=os.length;i<len;i++){os[i].onNext(value)}},dispose:function(){this.isDisposed=true;this.observers=null;this.value=null;this.exception=null}});return BehaviorSubject}(Observable);var ReplaySubject=Rx.ReplaySubject=function(__super__){var maxSafeInteger=Math.pow(2,53)-1;function createRemovableDisposable(subject,observer){return disposableCreate(function(){observer.dispose();!subject.isDisposed&&subject.observers.splice(subject.observers.indexOf(observer),1)})}function subscribe(observer){var so=new ScheduledObserver(this.scheduler,observer),subscription=createRemovableDisposable(this,so);checkDisposed(this);this._trim(this.scheduler.now());this.observers.push(so);for(var i=0,len=this.q.length;i<len;i++){so.onNext(this.q[i].value)}if(this.hasError){so.onError(this.error)}else if(this.isStopped){so.onCompleted()}so.ensureActive();return subscription}inherits(ReplaySubject,__super__);function ReplaySubject(bufferSize,windowSize,scheduler){this.bufferSize=bufferSize==null?maxSafeInteger:bufferSize;this.windowSize=windowSize==null?maxSafeInteger:windowSize;this.scheduler=scheduler||currentThreadScheduler;this.q=[];this.observers=[];this.isStopped=false;this.isDisposed=false;this.hasError=false;this.error=null;__super__.call(this,subscribe)}addProperties(ReplaySubject.prototype,Observer.prototype,{hasObservers:function(){return this.observers.length>0},_trim:function(now){while(this.q.length>this.bufferSize){this.q.shift()}while(this.q.length>0&&now-this.q[0].interval>this.windowSize){this.q.shift()}},onNext:function(value){checkDisposed(this);if(this.isStopped){return}var now=this.scheduler.now();this.q.push({interval:now,value:value});this._trim(now);for(var i=0,os=cloneArray(this.observers),len=os.length;i<len;i++){var observer=os[i];observer.onNext(value);observer.ensureActive()}},onError:function(error){checkDisposed(this);if(this.isStopped){return}this.isStopped=true;this.error=error;this.hasError=true;var now=this.scheduler.now();this._trim(now);for(var i=0,os=cloneArray(this.observers),len=os.length;i<len;i++){var observer=os[i];observer.onError(error);observer.ensureActive()}this.observers.length=0},onCompleted:function(){checkDisposed(this);if(this.isStopped){return}this.isStopped=true;var now=this.scheduler.now();this._trim(now);for(var i=0,os=cloneArray(this.observers),len=os.length;i<len;i++){var observer=os[i];observer.onCompleted();observer.ensureActive()}this.observers.length=0},dispose:function(){this.isDisposed=true;this.observers=null}});return ReplaySubject}(Observable);var ConnectableObservable=Rx.ConnectableObservable=function(__super__){inherits(ConnectableObservable,__super__);function ConnectableObservable(source,subject){var hasSubscription=false,subscription,sourceObservable=source.asObservable();this.connect=function(){if(!hasSubscription){hasSubscription=true;subscription=new CompositeDisposable(sourceObservable.subscribe(subject),disposableCreate(function(){hasSubscription=false}))}return subscription};__super__.call(this,function(o){return subject.subscribe(o)})}ConnectableObservable.prototype.refCount=function(){var connectableSubscription,count=0,source=this;return new AnonymousObservable(function(observer){var shouldConnect=++count===1,subscription=source.subscribe(observer);shouldConnect&&(connectableSubscription=source.connect());return function(){subscription.dispose();--count===0&&connectableSubscription.dispose()}})};return ConnectableObservable}(Observable);var Dictionary=function(){var primes=[1,3,7,13,31,61,127,251,509,1021,2039,4093,8191,16381,32749,65521,131071,262139,524287,1048573,2097143,4194301,8388593,16777213,33554393,67108859,134217689,268435399,536870909,1073741789,2147483647],noSuchkey="no such key",duplicatekey="duplicate key";function isPrime(candidate){if((candidate&1)===0){return candidate===2}var num1=Math.sqrt(candidate),num2=3;while(num2<=num1){if(candidate%num2===0){return false}num2+=2}return true}function getPrime(min){var index,num,candidate;for(index=0;index<primes.length;++index){num=primes[index];if(num>=min){return num}}candidate=min|1;while(candidate<primes[primes.length-1]){if(isPrime(candidate)){return candidate}candidate+=2}return min}function stringHashFn(str){var hash=757602046;if(!str.length){return hash}for(var i=0,len=str.length;i<len;i++){var character=str.charCodeAt(i);hash=(hash<<5)-hash+character;hash=hash&hash}return hash}function numberHashFn(key){var c2=668265261;key=key^61^key>>>16;key=key+(key<<3);key=key^key>>>4;key=key*c2;key=key^key>>>15;return key}var getHashCode=function(){var uniqueIdCounter=0;return function(obj){if(obj==null){throw new Error(noSuchkey)}if(typeof obj==="string"){return stringHashFn(obj)}if(typeof obj==="number"){return numberHashFn(obj)}if(typeof obj==="boolean"){return obj===true?1:0}if(obj instanceof Date){return numberHashFn(obj.valueOf())}if(obj instanceof RegExp){return stringHashFn(obj.toString())}if(typeof obj.valueOf==="function"){var valueOf=obj.valueOf();if(typeof valueOf==="number"){return numberHashFn(valueOf)}if(typeof valueOf==="string"){return stringHashFn(valueOf)}}if(obj.hashCode){return obj.hashCode()}var id=17*uniqueIdCounter++;obj.hashCode=function(){return id};return id}}();function newEntry(){return{key:null,value:null,next:0,hashCode:0}}function Dictionary(capacity,comparer){if(capacity<0){throw new ArgumentOutOfRangeError}if(capacity>0){this._initialize(capacity)}this.comparer=comparer||defaultComparer;this.freeCount=0;this.size=0;this.freeList=-1}var dictionaryProto=Dictionary.prototype;dictionaryProto._initialize=function(capacity){var prime=getPrime(capacity),i;this.buckets=new Array(prime);this.entries=new Array(prime);for(i=0;i<prime;i++){this.buckets[i]=-1;this.entries[i]=newEntry()}this.freeList=-1};dictionaryProto.add=function(key,value){this._insert(key,value,true)};dictionaryProto._insert=function(key,value,add){if(!this.buckets){this._initialize(0)}var index3,num=getHashCode(key)&2147483647,index1=num%this.buckets.length;for(var index2=this.buckets[index1];index2>=0;index2=this.entries[index2].next){if(this.entries[index2].hashCode===num&&this.comparer(this.entries[index2].key,key)){if(add){throw new Error(duplicatekey)}this.entries[index2].value=value;return}}if(this.freeCount>0){index3=this.freeList;this.freeList=this.entries[index3].next;--this.freeCount}else{if(this.size===this.entries.length){this._resize();index1=num%this.buckets.length}index3=this.size;++this.size}this.entries[index3].hashCode=num;this.entries[index3].next=this.buckets[index1];this.entries[index3].key=key;this.entries[index3].value=value;this.buckets[index1]=index3};dictionaryProto._resize=function(){var prime=getPrime(this.size*2),numArray=new Array(prime);for(index=0;index<numArray.length;++index){numArray[index]=-1}var entryArray=new Array(prime);for(index=0;index<this.size;++index){entryArray[index]=this.entries[index]}for(var index=this.size;index<prime;++index){entryArray[index]=newEntry()}for(var index1=0;index1<this.size;++index1){var index2=entryArray[index1].hashCode%prime;entryArray[index1].next=numArray[index2];numArray[index2]=index1}this.buckets=numArray;this.entries=entryArray};dictionaryProto.remove=function(key){if(this.buckets){var num=getHashCode(key)&2147483647,index1=num%this.buckets.length,index2=-1;for(var index3=this.buckets[index1];index3>=0;index3=this.entries[index3].next){if(this.entries[index3].hashCode===num&&this.comparer(this.entries[index3].key,key)){if(index2<0){this.buckets[index1]=this.entries[index3].next}else{this.entries[index2].next=this.entries[index3].next}this.entries[index3].hashCode=-1;this.entries[index3].next=this.freeList;this.entries[index3].key=null;this.entries[index3].value=null;this.freeList=index3;++this.freeCount;return true}else{index2=index3}}}return false};dictionaryProto.clear=function(){var index,len;if(this.size<=0){return}for(index=0,len=this.buckets.length;index<len;++index){this.buckets[index]=-1}for(index=0;index<this.size;++index){this.entries[index]=newEntry()}this.freeList=-1;this.size=0};dictionaryProto._findEntry=function(key){if(this.buckets){var num=getHashCode(key)&2147483647;for(var index=this.buckets[num%this.buckets.length];index>=0;index=this.entries[index].next){if(this.entries[index].hashCode===num&&this.comparer(this.entries[index].key,key)){return index}}}return-1};dictionaryProto.count=function(){return this.size-this.freeCount};dictionaryProto.tryGetValue=function(key){var entry=this._findEntry(key);return entry>=0?this.entries[entry].value:undefined};dictionaryProto.getValues=function(){var index=0,results=[];if(this.entries){for(var index1=0;index1<this.size;index1++){if(this.entries[index1].hashCode>=0){results[index++]=this.entries[index1].value}}}return results};dictionaryProto.get=function(key){var entry=this._findEntry(key);if(entry>=0){return this.entries[entry].value}throw new Error(noSuchkey)};dictionaryProto.set=function(key,value){this._insert(key,value,false)};dictionaryProto.containskey=function(key){return this._findEntry(key)>=0};return Dictionary}();observableProto.join=function(right,leftDurationSelector,rightDurationSelector,resultSelector){var left=this;return new AnonymousObservable(function(observer){var group=new CompositeDisposable;var leftDone=false,rightDone=false;var leftId=0,rightId=0;var leftMap=new Dictionary,rightMap=new Dictionary;group.add(left.subscribe(function(value){var id=leftId++;var md=new SingleAssignmentDisposable;leftMap.add(id,value);group.add(md);var expire=function(){leftMap.remove(id)&&leftMap.count()===0&&leftDone&&observer.onCompleted();group.remove(md)};var duration;try{duration=leftDurationSelector(value)}catch(e){observer.onError(e);return}md.setDisposable(duration.take(1).subscribe(noop,observer.onError.bind(observer),expire));rightMap.getValues().forEach(function(v){var result;try{result=resultSelector(value,v)}catch(exn){observer.onError(exn);return}observer.onNext(result)})},observer.onError.bind(observer),function(){leftDone=true;(rightDone||leftMap.count()===0)&&observer.onCompleted()}));group.add(right.subscribe(function(value){var id=rightId++;var md=new SingleAssignmentDisposable;rightMap.add(id,value);group.add(md);var expire=function(){rightMap.remove(id)&&rightMap.count()===0&&rightDone&&observer.onCompleted();group.remove(md)};var duration;try{duration=rightDurationSelector(value)}catch(e){observer.onError(e);return}md.setDisposable(duration.take(1).subscribe(noop,observer.onError.bind(observer),expire));leftMap.getValues().forEach(function(v){var result;try{result=resultSelector(v,value)}catch(exn){observer.onError(exn);return}observer.onNext(result)})},observer.onError.bind(observer),function(){rightDone=true;(leftDone||rightMap.count()===0)&&observer.onCompleted()}));return group},left)};observableProto.groupJoin=function(right,leftDurationSelector,rightDurationSelector,resultSelector){var left=this;return new AnonymousObservable(function(observer){var group=new CompositeDisposable;var r=new RefCountDisposable(group);var leftMap=new Dictionary,rightMap=new Dictionary;var leftId=0,rightId=0;function handleError(e){return function(v){v.onError(e)}}group.add(left.subscribe(function(value){var s=new Subject;var id=leftId++;leftMap.add(id,s);var result;try{result=resultSelector(value,addRef(s,r))}catch(e){leftMap.getValues().forEach(handleError(e));observer.onError(e);return}observer.onNext(result);rightMap.getValues().forEach(function(v){s.onNext(v)});var md=new SingleAssignmentDisposable;group.add(md);var expire=function(){leftMap.remove(id)&&s.onCompleted();group.remove(md)};var duration;try{duration=leftDurationSelector(value)}catch(e){leftMap.getValues().forEach(handleError(e));observer.onError(e);return}md.setDisposable(duration.take(1).subscribe(noop,function(e){leftMap.getValues().forEach(handleError(e));observer.onError(e)},expire))},function(e){leftMap.getValues().forEach(handleError(e));observer.onError(e)},observer.onCompleted.bind(observer)));group.add(right.subscribe(function(value){var id=rightId++;rightMap.add(id,value);var md=new SingleAssignmentDisposable;group.add(md);var expire=function(){rightMap.remove(id);group.remove(md)};var duration;try{duration=rightDurationSelector(value)}catch(e){leftMap.getValues().forEach(handleError(e));observer.onError(e);return}md.setDisposable(duration.take(1).subscribe(noop,function(e){leftMap.getValues().forEach(handleError(e));observer.onError(e)},expire));leftMap.getValues().forEach(function(v){v.onNext(value)})},function(e){leftMap.getValues().forEach(handleError(e));observer.onError(e)}));return r},left)};observableProto.buffer=function(bufferOpeningsOrClosingSelector,bufferClosingSelector){return this.window.apply(this,arguments).selectMany(function(x){return x.toArray()})};observableProto.window=function(windowOpeningsOrClosingSelector,windowClosingSelector){if(arguments.length===1&&typeof arguments[0]!=="function"){return observableWindowWithBoundaries.call(this,windowOpeningsOrClosingSelector)}return typeof windowOpeningsOrClosingSelector==="function"?observableWindowWithClosingSelector.call(this,windowOpeningsOrClosingSelector):observableWindowWithOpenings.call(this,windowOpeningsOrClosingSelector,windowClosingSelector)};function observableWindowWithOpenings(windowOpenings,windowClosingSelector){return windowOpenings.groupJoin(this,windowClosingSelector,observableEmpty,function(_,win){return win})}function observableWindowWithBoundaries(windowBoundaries){var source=this;return new AnonymousObservable(function(observer){var win=new Subject,d=new CompositeDisposable,r=new RefCountDisposable(d);observer.onNext(addRef(win,r));d.add(source.subscribe(function(x){win.onNext(x)},function(err){win.onError(err);observer.onError(err)},function(){win.onCompleted();observer.onCompleted()}));isPromise(windowBoundaries)&&(windowBoundaries=observableFromPromise(windowBoundaries));d.add(windowBoundaries.subscribe(function(w){win.onCompleted();win=new Subject;observer.onNext(addRef(win,r))},function(err){win.onError(err);observer.onError(err)},function(){win.onCompleted();observer.onCompleted()}));return r},source)}function observableWindowWithClosingSelector(windowClosingSelector){var source=this;return new AnonymousObservable(function(observer){var m=new SerialDisposable,d=new CompositeDisposable(m),r=new RefCountDisposable(d),win=new Subject;observer.onNext(addRef(win,r));d.add(source.subscribe(function(x){win.onNext(x)},function(err){win.onError(err);observer.onError(err)},function(){win.onCompleted();observer.onCompleted()}));function createWindowClose(){var windowClose;try{windowClose=windowClosingSelector()}catch(e){observer.onError(e);return}isPromise(windowClose)&&(windowClose=observableFromPromise(windowClose));var m1=new SingleAssignmentDisposable;m.setDisposable(m1);m1.setDisposable(windowClose.take(1).subscribe(noop,function(err){win.onError(err);observer.onError(err)},function(){win.onCompleted();win=new Subject;observer.onNext(addRef(win,r));createWindowClose()}))}createWindowClose();return r},source)}observableProto.pairwise=function(){var source=this;return new AnonymousObservable(function(observer){var previous,hasPrevious=false;return source.subscribe(function(x){if(hasPrevious){observer.onNext([previous,x])}else{hasPrevious=true}previous=x},observer.onError.bind(observer),observer.onCompleted.bind(observer))},source)};observableProto.partition=function(predicate,thisArg){return[this.filter(predicate,thisArg),this.filter(function(x,i,o){return!predicate.call(thisArg,x,i,o)})]};function enumerableWhile(condition,source){return new Enumerable(function(){return new Enumerator(function(){return condition()?{done:false,value:source}:{done:true,value:undefined}})})}observableProto.letBind=observableProto["let"]=function(func){return func(this)};Observable["if"]=Observable.ifThen=function(condition,thenSource,elseSourceOrScheduler){return observableDefer(function(){elseSourceOrScheduler||(elseSourceOrScheduler=observableEmpty());isPromise(thenSource)&&(thenSource=observableFromPromise(thenSource));isPromise(elseSourceOrScheduler)&&(elseSourceOrScheduler=observableFromPromise(elseSourceOrScheduler));typeof elseSourceOrScheduler.now==="function"&&(elseSourceOrScheduler=observableEmpty(elseSourceOrScheduler));return condition()?thenSource:elseSourceOrScheduler})};Observable["for"]=Observable.forIn=function(sources,resultSelector,thisArg){return enumerableOf(sources,resultSelector,thisArg).concat()};var observableWhileDo=Observable["while"]=Observable.whileDo=function(condition,source){isPromise(source)&&(source=observableFromPromise(source));return enumerableWhile(condition,source).concat()};observableProto.doWhile=function(condition){return observableConcat([this,observableWhileDo(condition,this)])};Observable["case"]=Observable.switchCase=function(selector,sources,defaultSourceOrScheduler){return observableDefer(function(){isPromise(defaultSourceOrScheduler)&&(defaultSourceOrScheduler=observableFromPromise(defaultSourceOrScheduler));defaultSourceOrScheduler||(defaultSourceOrScheduler=observableEmpty());typeof defaultSourceOrScheduler.now==="function"&&(defaultSourceOrScheduler=observableEmpty(defaultSourceOrScheduler));var result=sources[selector()];isPromise(result)&&(result=observableFromPromise(result));return result||defaultSourceOrScheduler})};observableProto.expand=function(selector,scheduler){isScheduler(scheduler)||(scheduler=immediateScheduler);var source=this;return new AnonymousObservable(function(observer){var q=[],m=new SerialDisposable,d=new CompositeDisposable(m),activeCount=0,isAcquired=false;var ensureActive=function(){var isOwner=false;if(q.length>0){isOwner=!isAcquired;isAcquired=true}if(isOwner){m.setDisposable(scheduler.scheduleRecursive(function(self){var work;if(q.length>0){work=q.shift()}else{isAcquired=false;return}var m1=new SingleAssignmentDisposable;d.add(m1);m1.setDisposable(work.subscribe(function(x){observer.onNext(x);var result=null;try{result=selector(x)}catch(e){observer.onError(e)}q.push(result);activeCount++;ensureActive()},observer.onError.bind(observer),function(){d.remove(m1);activeCount--;if(activeCount===0){observer.onCompleted()}}));self()}))}};q.push(source);activeCount++;ensureActive();return d},this)};Observable.forkJoin=function(){var allSources=[];if(Array.isArray(arguments[0])){allSources=arguments[0]}else{for(var i=0,len=arguments.length;i<len;i++){allSources.push(arguments[i])}}return new AnonymousObservable(function(subscriber){var count=allSources.length;if(count===0){subscriber.onCompleted();return disposableEmpty}var group=new CompositeDisposable,finished=false,hasResults=new Array(count),hasCompleted=new Array(count),results=new Array(count);for(var idx=0;idx<count;idx++){(function(i){var source=allSources[i];isPromise(source)&&(source=observableFromPromise(source));group.add(source.subscribe(function(value){if(!finished){hasResults[i]=true;results[i]=value}},function(e){finished=true;subscriber.onError(e);group.dispose()},function(){if(!finished){if(!hasResults[i]){subscriber.onCompleted();return}hasCompleted[i]=true;for(var ix=0;ix<count;ix++){if(!hasCompleted[ix]){return}}finished=true;subscriber.onNext(results);subscriber.onCompleted()}}))})(idx)}return group})};observableProto.forkJoin=function(second,resultSelector){var first=this;return new AnonymousObservable(function(observer){var leftStopped=false,rightStopped=false,hasLeft=false,hasRight=false,lastLeft,lastRight,leftSubscription=new SingleAssignmentDisposable,rightSubscription=new SingleAssignmentDisposable;isPromise(second)&&(second=observableFromPromise(second));leftSubscription.setDisposable(first.subscribe(function(left){hasLeft=true;lastLeft=left},function(err){rightSubscription.dispose();observer.onError(err)},function(){leftStopped=true;if(rightStopped){if(!hasLeft){observer.onCompleted()}else if(!hasRight){observer.onCompleted()}else{var result;try{result=resultSelector(lastLeft,lastRight)}catch(e){observer.onError(e);return}observer.onNext(result);observer.onCompleted()}}}));rightSubscription.setDisposable(second.subscribe(function(right){hasRight=true;lastRight=right},function(err){leftSubscription.dispose();observer.onError(err)},function(){rightStopped=true;if(leftStopped){if(!hasLeft){observer.onCompleted()}else if(!hasRight){observer.onCompleted()}else{var result;try{result=resultSelector(lastLeft,lastRight)}catch(e){observer.onError(e);return}observer.onNext(result);observer.onCompleted()}}}));return new CompositeDisposable(leftSubscription,rightSubscription)},first)};observableProto.manySelect=function(selector,scheduler){isScheduler(scheduler)||(scheduler=immediateScheduler);var source=this;return observableDefer(function(){var chain;return source.map(function(x){var curr=new ChainObservable(x);chain&&chain.onNext(x);chain=curr;return curr}).tap(noop,function(e){chain&&chain.onError(e)},function(){chain&&chain.onCompleted()}).observeOn(scheduler).map(selector)},source)};var ChainObservable=function(__super__){function subscribe(observer){var self=this,g=new CompositeDisposable;g.add(currentThreadScheduler.schedule(function(){observer.onNext(self.head);g.add(self.tail.mergeAll().subscribe(observer))}));return g}inherits(ChainObservable,__super__);function ChainObservable(head){__super__.call(this,subscribe);this.head=head;this.tail=new AsyncSubject}addProperties(ChainObservable.prototype,Observer,{onCompleted:function(){this.onNext(Observable.empty())},onError:function(e){this.onNext(Observable.throwError(e))},onNext:function(v){this.tail.onNext(v);this.tail.onCompleted()}});return ChainObservable}(Observable);var Map=root.Map||function(){function Map(){this._keys=[];this._values=[]}Map.prototype.get=function(key){var i=this._keys.indexOf(key);return i!==-1?this._values[i]:undefined};Map.prototype.set=function(key,value){var i=this._keys.indexOf(key);i!==-1&&(this._values[i]=value);this._values[this._keys.push(key)-1]=value};Map.prototype.forEach=function(callback,thisArg){for(var i=0,len=this._keys.length;i<len;i++){callback.call(thisArg,this._values[i],this._keys[i])}};return Map}();function Pattern(patterns){this.patterns=patterns}Pattern.prototype.and=function(other){return new Pattern(this.patterns.concat(other))};Pattern.prototype.thenDo=function(selector){return new Plan(this,selector)};function Plan(expression,selector){this.expression=expression;this.selector=selector}Plan.prototype.activate=function(externalSubscriptions,observer,deactivate){var self=this;var joinObservers=[];for(var i=0,len=this.expression.patterns.length;i<len;i++){joinObservers.push(planCreateObserver(externalSubscriptions,this.expression.patterns[i],observer.onError.bind(observer)))}var activePlan=new ActivePlan(joinObservers,function(){var result;try{result=self.selector.apply(self,arguments)}catch(e){observer.onError(e);return}observer.onNext(result)},function(){for(var j=0,jlen=joinObservers.length;j<jlen;j++){joinObservers[j].removeActivePlan(activePlan)}deactivate(activePlan)});for(i=0,len=joinObservers.length;i<len;i++){joinObservers[i].addActivePlan(activePlan)}return activePlan};function planCreateObserver(externalSubscriptions,observable,onError){var entry=externalSubscriptions.get(observable);if(!entry){var observer=new JoinObserver(observable,onError);externalSubscriptions.set(observable,observer);return observer}return entry}function ActivePlan(joinObserverArray,onNext,onCompleted){this.joinObserverArray=joinObserverArray;this.onNext=onNext;this.onCompleted=onCompleted;this.joinObservers=new Map;for(var i=0,len=this.joinObserverArray.length;i<len;i++){var joinObserver=this.joinObserverArray[i];this.joinObservers.set(joinObserver,joinObserver)}}ActivePlan.prototype.dequeue=function(){this.joinObservers.forEach(function(v){v.queue.shift()})};ActivePlan.prototype.match=function(){var i,len,hasValues=true;for(i=0,len=this.joinObserverArray.length;i<len;i++){if(this.joinObserverArray[i].queue.length===0){hasValues=false;break}}if(hasValues){var firstValues=[],isCompleted=false;for(i=0,len=this.joinObserverArray.length;i<len;i++){firstValues.push(this.joinObserverArray[i].queue[0]);this.joinObserverArray[i].queue[0].kind==="C"&&(isCompleted=true)}if(isCompleted){this.onCompleted()}else{this.dequeue();var values=[];for(i=0,len=firstValues.length;i<firstValues.length;i++){values.push(firstValues[i].value)}this.onNext.apply(this,values)}}};var JoinObserver=function(__super__){inherits(JoinObserver,__super__);function JoinObserver(source,onError){__super__.call(this);this.source=source;this.onError=onError;this.queue=[];this.activePlans=[];this.subscription=new SingleAssignmentDisposable;this.isDisposed=false}var JoinObserverPrototype=JoinObserver.prototype;JoinObserverPrototype.next=function(notification){if(!this.isDisposed){if(notification.kind==="E"){return this.onError(notification.exception)}this.queue.push(notification);var activePlans=this.activePlans.slice(0);for(var i=0,len=activePlans.length;i<len;i++){activePlans[i].match()}}};JoinObserverPrototype.error=noop;JoinObserverPrototype.completed=noop;JoinObserverPrototype.addActivePlan=function(activePlan){this.activePlans.push(activePlan)};JoinObserverPrototype.subscribe=function(){this.subscription.setDisposable(this.source.materialize().subscribe(this))};JoinObserverPrototype.removeActivePlan=function(activePlan){this.activePlans.splice(this.activePlans.indexOf(activePlan),1); this.activePlans.length===0&&this.dispose()};JoinObserverPrototype.dispose=function(){__super__.prototype.dispose.call(this);if(!this.isDisposed){this.isDisposed=true;this.subscription.dispose()}};return JoinObserver}(AbstractObserver);observableProto.and=function(right){return new Pattern([this,right])};observableProto.thenDo=function(selector){return new Pattern([this]).thenDo(selector)};Observable.when=function(){var len=arguments.length,plans;if(Array.isArray(arguments[0])){plans=arguments[0]}else{plans=new Array(len);for(var i=0;i<len;i++){plans[i]=arguments[i]}}return new AnonymousObservable(function(o){var activePlans=[],externalSubscriptions=new Map;var outObserver=observerCreate(function(x){o.onNext(x)},function(err){externalSubscriptions.forEach(function(v){v.onError(err)});o.onError(err)},function(x){o.onCompleted()});try{for(var i=0,len=plans.length;i<len;i++){activePlans.push(plans[i].activate(externalSubscriptions,outObserver,function(activePlan){var idx=activePlans.indexOf(activePlan);activePlans.splice(idx,1);activePlans.length===0&&o.onCompleted()}))}}catch(e){observableThrow(e).subscribe(o)}var group=new CompositeDisposable;externalSubscriptions.forEach(function(joinObserver){joinObserver.subscribe();group.add(joinObserver)});return group})};function observableTimerDate(dueTime,scheduler){return new AnonymousObservable(function(observer){return scheduler.scheduleWithAbsolute(dueTime,function(){observer.onNext(0);observer.onCompleted()})})}function observableTimerDateAndPeriod(dueTime,period,scheduler){return new AnonymousObservable(function(observer){var d=dueTime,p=normalizeTime(period);return scheduler.scheduleRecursiveWithAbsoluteAndState(0,d,function(count,self){if(p>0){var now=scheduler.now();d=d+p;d<=now&&(d=now+p)}observer.onNext(count);self(count+1,d)})})}function observableTimerTimeSpan(dueTime,scheduler){return new AnonymousObservable(function(observer){return scheduler.scheduleWithRelative(normalizeTime(dueTime),function(){observer.onNext(0);observer.onCompleted()})})}function observableTimerTimeSpanAndPeriod(dueTime,period,scheduler){return dueTime===period?new AnonymousObservable(function(observer){return scheduler.schedulePeriodicWithState(0,period,function(count){observer.onNext(count);return count+1})}):observableDefer(function(){return observableTimerDateAndPeriod(scheduler.now()+dueTime,period,scheduler)})}var observableinterval=Observable.interval=function(period,scheduler){return observableTimerTimeSpanAndPeriod(period,period,isScheduler(scheduler)?scheduler:timeoutScheduler)};var observableTimer=Observable.timer=function(dueTime,periodOrScheduler,scheduler){var period;isScheduler(scheduler)||(scheduler=timeoutScheduler);if(periodOrScheduler!==undefined&&typeof periodOrScheduler==="number"){period=periodOrScheduler}else if(isScheduler(periodOrScheduler)){scheduler=periodOrScheduler}if(dueTime instanceof Date&&period===undefined){return observableTimerDate(dueTime.getTime(),scheduler)}if(dueTime instanceof Date&&period!==undefined){period=periodOrScheduler;return observableTimerDateAndPeriod(dueTime.getTime(),period,scheduler)}return period===undefined?observableTimerTimeSpan(dueTime,scheduler):observableTimerTimeSpanAndPeriod(dueTime,period,scheduler)};function observableDelayTimeSpan(source,dueTime,scheduler){return new AnonymousObservable(function(observer){var active=false,cancelable=new SerialDisposable,exception=null,q=[],running=false,subscription;subscription=source.materialize().timestamp(scheduler).subscribe(function(notification){var d,shouldRun;if(notification.value.kind==="E"){q=[];q.push(notification);exception=notification.value.exception;shouldRun=!running}else{q.push({value:notification.value,timestamp:notification.timestamp+dueTime});shouldRun=!active;active=true}if(shouldRun){if(exception!==null){observer.onError(exception)}else{d=new SingleAssignmentDisposable;cancelable.setDisposable(d);d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime,function(self){var e,recurseDueTime,result,shouldRecurse;if(exception!==null){return}running=true;do{result=null;if(q.length>0&&q[0].timestamp-scheduler.now()<=0){result=q.shift().value}if(result!==null){result.accept(observer)}}while(result!==null);shouldRecurse=false;recurseDueTime=0;if(q.length>0){shouldRecurse=true;recurseDueTime=Math.max(0,q[0].timestamp-scheduler.now())}else{active=false}e=exception;running=false;if(e!==null){observer.onError(e)}else if(shouldRecurse){self(recurseDueTime)}}))}}});return new CompositeDisposable(subscription,cancelable)},source)}function observableDelayDate(source,dueTime,scheduler){return observableDefer(function(){return observableDelayTimeSpan(source,dueTime-scheduler.now(),scheduler)})}observableProto.delay=function(dueTime,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);return dueTime instanceof Date?observableDelayDate(this,dueTime.getTime(),scheduler):observableDelayTimeSpan(this,dueTime,scheduler)};observableProto.debounce=observableProto.throttleWithTimeout=function(dueTime,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);var source=this;return new AnonymousObservable(function(observer){var cancelable=new SerialDisposable,hasvalue=false,value,id=0;var subscription=source.subscribe(function(x){hasvalue=true;value=x;id++;var currentId=id,d=new SingleAssignmentDisposable;cancelable.setDisposable(d);d.setDisposable(scheduler.scheduleWithRelative(dueTime,function(){hasvalue&&id===currentId&&observer.onNext(value);hasvalue=false}))},function(e){cancelable.dispose();observer.onError(e);hasvalue=false;id++},function(){cancelable.dispose();hasvalue&&observer.onNext(value);observer.onCompleted();hasvalue=false;id++});return new CompositeDisposable(subscription,cancelable)},this)};observableProto.throttle=function(dueTime,scheduler){return this.debounce(dueTime,scheduler)};observableProto.windowWithTime=function(timeSpan,timeShiftOrScheduler,scheduler){var source=this,timeShift;timeShiftOrScheduler==null&&(timeShift=timeSpan);isScheduler(scheduler)||(scheduler=timeoutScheduler);if(typeof timeShiftOrScheduler==="number"){timeShift=timeShiftOrScheduler}else if(isScheduler(timeShiftOrScheduler)){timeShift=timeSpan;scheduler=timeShiftOrScheduler}return new AnonymousObservable(function(observer){var groupDisposable,nextShift=timeShift,nextSpan=timeSpan,q=[],refCountDisposable,timerD=new SerialDisposable,totalTime=0;groupDisposable=new CompositeDisposable(timerD),refCountDisposable=new RefCountDisposable(groupDisposable);function createTimer(){var m=new SingleAssignmentDisposable,isSpan=false,isShift=false;timerD.setDisposable(m);if(nextSpan===nextShift){isSpan=true;isShift=true}else if(nextSpan<nextShift){isSpan=true}else{isShift=true}var newTotalTime=isSpan?nextSpan:nextShift,ts=newTotalTime-totalTime;totalTime=newTotalTime;if(isSpan){nextSpan+=timeShift}if(isShift){nextShift+=timeShift}m.setDisposable(scheduler.scheduleWithRelative(ts,function(){if(isShift){var s=new Subject;q.push(s);observer.onNext(addRef(s,refCountDisposable))}isSpan&&q.shift().onCompleted();createTimer()}))}q.push(new Subject);observer.onNext(addRef(q[0],refCountDisposable));createTimer();groupDisposable.add(source.subscribe(function(x){for(var i=0,len=q.length;i<len;i++){q[i].onNext(x)}},function(e){for(var i=0,len=q.length;i<len;i++){q[i].onError(e)}observer.onError(e)},function(){for(var i=0,len=q.length;i<len;i++){q[i].onCompleted()}observer.onCompleted()}));return refCountDisposable},source)};observableProto.windowWithTimeOrCount=function(timeSpan,count,scheduler){var source=this;isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(observer){var timerD=new SerialDisposable,groupDisposable=new CompositeDisposable(timerD),refCountDisposable=new RefCountDisposable(groupDisposable),n=0,windowId=0,s=new Subject;function createTimer(id){var m=new SingleAssignmentDisposable;timerD.setDisposable(m);m.setDisposable(scheduler.scheduleWithRelative(timeSpan,function(){if(id!==windowId){return}n=0;var newId=++windowId;s.onCompleted();s=new Subject;observer.onNext(addRef(s,refCountDisposable));createTimer(newId)}))}observer.onNext(addRef(s,refCountDisposable));createTimer(0);groupDisposable.add(source.subscribe(function(x){var newId=0,newWindow=false;s.onNext(x);if(++n===count){newWindow=true;n=0;newId=++windowId;s.onCompleted();s=new Subject;observer.onNext(addRef(s,refCountDisposable))}newWindow&&createTimer(newId)},function(e){s.onError(e);observer.onError(e)},function(){s.onCompleted();observer.onCompleted()}));return refCountDisposable},source)};observableProto.bufferWithTime=function(timeSpan,timeShiftOrScheduler,scheduler){return this.windowWithTime.apply(this,arguments).selectMany(function(x){return x.toArray()})};observableProto.bufferWithTimeOrCount=function(timeSpan,count,scheduler){return this.windowWithTimeOrCount(timeSpan,count,scheduler).selectMany(function(x){return x.toArray()})};observableProto.timeInterval=function(scheduler){var source=this;isScheduler(scheduler)||(scheduler=timeoutScheduler);return observableDefer(function(){var last=scheduler.now();return source.map(function(x){var now=scheduler.now(),span=now-last;last=now;return{value:x,interval:span}})})};observableProto.timestamp=function(scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);return this.map(function(x){return{value:x,timestamp:scheduler.now()}})};function sampleObservable(source,sampler){return new AnonymousObservable(function(observer){var atEnd,value,hasValue;function sampleSubscribe(){if(hasValue){hasValue=false;observer.onNext(value)}atEnd&&observer.onCompleted()}return new CompositeDisposable(source.subscribe(function(newValue){hasValue=true;value=newValue},observer.onError.bind(observer),function(){atEnd=true}),sampler.subscribe(sampleSubscribe,observer.onError.bind(observer),sampleSubscribe))},source)}observableProto.sample=observableProto.throttleLatest=function(intervalOrSampler,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);return typeof intervalOrSampler==="number"?sampleObservable(this,observableinterval(intervalOrSampler,scheduler)):sampleObservable(this,intervalOrSampler)};observableProto.timeout=function(dueTime,other,scheduler){(other==null||typeof other==="string")&&(other=observableThrow(new Error(other||"Timeout")));isScheduler(scheduler)||(scheduler=timeoutScheduler);var source=this,schedulerMethod=dueTime instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new AnonymousObservable(function(observer){var id=0,original=new SingleAssignmentDisposable,subscription=new SerialDisposable,switched=false,timer=new SerialDisposable;subscription.setDisposable(original);function createTimer(){var myId=id;timer.setDisposable(scheduler[schedulerMethod](dueTime,function(){if(id===myId){isPromise(other)&&(other=observableFromPromise(other));subscription.setDisposable(other.subscribe(observer))}}))}createTimer();original.setDisposable(source.subscribe(function(x){if(!switched){id++;observer.onNext(x);createTimer()}},function(e){if(!switched){id++;observer.onError(e)}},function(){if(!switched){id++;observer.onCompleted()}}));return new CompositeDisposable(subscription,timer)},source)};Observable.generateWithAbsoluteTime=function(initialState,condition,iterate,resultSelector,timeSelector,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(observer){var first=true,hasResult=false,result,state=initialState,time;return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(),function(self){hasResult&&observer.onNext(result);try{if(first){first=false}else{state=iterate(state)}hasResult=condition(state);if(hasResult){result=resultSelector(state);time=timeSelector(state)}}catch(e){observer.onError(e);return}if(hasResult){self(time)}else{observer.onCompleted()}})})};Observable.generateWithRelativeTime=function(initialState,condition,iterate,resultSelector,timeSelector,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(observer){var first=true,hasResult=false,result,state=initialState,time;return scheduler.scheduleRecursiveWithRelative(0,function(self){hasResult&&observer.onNext(result);try{if(first){first=false}else{state=iterate(state)}hasResult=condition(state);if(hasResult){result=resultSelector(state);time=timeSelector(state)}}catch(e){observer.onError(e);return}if(hasResult){self(time)}else{observer.onCompleted()}})})};observableProto.delaySubscription=function(dueTime,scheduler){return this.delayWithSelector(observableTimer(dueTime,isScheduler(scheduler)?scheduler:timeoutScheduler),observableEmpty)};observableProto.delayWithSelector=function(subscriptionDelay,delayDurationSelector){var source=this,subDelay,selector;if(typeof subscriptionDelay==="function"){selector=subscriptionDelay}else{subDelay=subscriptionDelay;selector=delayDurationSelector}return new AnonymousObservable(function(observer){var delays=new CompositeDisposable,atEnd=false,done=function(){if(atEnd&&delays.length===0){observer.onCompleted()}},subscription=new SerialDisposable,start=function(){subscription.setDisposable(source.subscribe(function(x){var delay;try{delay=selector(x)}catch(error){observer.onError(error);return}var d=new SingleAssignmentDisposable;delays.add(d);d.setDisposable(delay.subscribe(function(){observer.onNext(x);delays.remove(d);done()},observer.onError.bind(observer),function(){observer.onNext(x);delays.remove(d);done()}))},observer.onError.bind(observer),function(){atEnd=true;subscription.dispose();done()}))};if(!subDelay){start()}else{subscription.setDisposable(subDelay.subscribe(start,observer.onError.bind(observer),start))}return new CompositeDisposable(subscription,delays)},this)};observableProto.timeoutWithSelector=function(firstTimeout,timeoutdurationSelector,other){if(arguments.length===1){timeoutdurationSelector=firstTimeout;firstTimeout=observableNever()}other||(other=observableThrow(new Error("Timeout")));var source=this;return new AnonymousObservable(function(observer){var subscription=new SerialDisposable,timer=new SerialDisposable,original=new SingleAssignmentDisposable;subscription.setDisposable(original);var id=0,switched=false;function setTimer(timeout){var myId=id;function timerWins(){return id===myId}var d=new SingleAssignmentDisposable;timer.setDisposable(d);d.setDisposable(timeout.subscribe(function(){timerWins()&&subscription.setDisposable(other.subscribe(observer));d.dispose()},function(e){timerWins()&&observer.onError(e)},function(){timerWins()&&subscription.setDisposable(other.subscribe(observer))}))}setTimer(firstTimeout);function observerWins(){var res=!switched;if(res){id++}return res}original.setDisposable(source.subscribe(function(x){if(observerWins()){observer.onNext(x);var timeout;try{timeout=timeoutdurationSelector(x)}catch(e){observer.onError(e);return}setTimer(isPromise(timeout)?observableFromPromise(timeout):timeout)}},function(e){observerWins()&&observer.onError(e)},function(){observerWins()&&observer.onCompleted()}));return new CompositeDisposable(subscription,timer)},source)};observableProto.debounceWithSelector=function(durationSelector){var source=this;return new AnonymousObservable(function(observer){var value,hasValue=false,cancelable=new SerialDisposable,id=0;var subscription=source.subscribe(function(x){var throttle;try{throttle=durationSelector(x)}catch(e){observer.onError(e);return}isPromise(throttle)&&(throttle=observableFromPromise(throttle));hasValue=true;value=x;id++;var currentid=id,d=new SingleAssignmentDisposable;cancelable.setDisposable(d);d.setDisposable(throttle.subscribe(function(){hasValue&&id===currentid&&observer.onNext(value);hasValue=false;d.dispose()},observer.onError.bind(observer),function(){hasValue&&id===currentid&&observer.onNext(value);hasValue=false;d.dispose()}))},function(e){cancelable.dispose();observer.onError(e);hasValue=false;id++},function(){cancelable.dispose();hasValue&&observer.onNext(value);observer.onCompleted();hasValue=false;id++});return new CompositeDisposable(subscription,cancelable)},source)};observableProto.throttleWithSelector=function(){return this.debounceWithSelector.apply(this,arguments)};observableProto.skipLastWithTime=function(duration,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);var source=this;return new AnonymousObservable(function(o){var q=[];return source.subscribe(function(x){var now=scheduler.now();q.push({interval:now,value:x});while(q.length>0&&now-q[0].interval>=duration){o.onNext(q.shift().value)}},function(e){o.onError(e)},function(){var now=scheduler.now();while(q.length>0&&now-q[0].interval>=duration){o.onNext(q.shift().value)}o.onCompleted()})},source)};observableProto.takeLastWithTime=function(duration,scheduler){var source=this;isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(o){var q=[];return source.subscribe(function(x){var now=scheduler.now();q.push({interval:now,value:x});while(q.length>0&&now-q[0].interval>=duration){q.shift()}},function(e){o.onError(e)},function(){var now=scheduler.now();while(q.length>0){var next=q.shift();if(now-next.interval<=duration){o.onNext(next.value)}}o.onCompleted()})},source)};observableProto.takeLastBufferWithTime=function(duration,scheduler){var source=this;isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(o){var q=[];return source.subscribe(function(x){var now=scheduler.now();q.push({interval:now,value:x});while(q.length>0&&now-q[0].interval>=duration){q.shift()}},function(e){o.onError(e)},function(){var now=scheduler.now(),res=[];while(q.length>0){var next=q.shift();now-next.interval<=duration&&res.push(next.value)}o.onNext(res);o.onCompleted()})},source)};observableProto.takeWithTime=function(duration,scheduler){var source=this;isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(o){return new CompositeDisposable(scheduler.scheduleWithRelative(duration,function(){o.onCompleted()}),source.subscribe(o))},source)};observableProto.skipWithTime=function(duration,scheduler){var source=this;isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(observer){var open=false;return new CompositeDisposable(scheduler.scheduleWithRelative(duration,function(){open=true}),source.subscribe(function(x){open&&observer.onNext(x)},observer.onError.bind(observer),observer.onCompleted.bind(observer)))},source)};observableProto.skipUntilWithTime=function(startTime,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);var source=this,schedulerMethod=startTime instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new AnonymousObservable(function(o){var open=false;return new CompositeDisposable(scheduler[schedulerMethod](startTime,function(){open=true}),source.subscribe(function(x){open&&o.onNext(x)},function(e){o.onError(e)},function(){o.onCompleted()}))},source)};observableProto.takeUntilWithTime=function(endTime,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);var source=this,schedulerMethod=endTime instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new AnonymousObservable(function(o){return new CompositeDisposable(scheduler[schedulerMethod](endTime,function(){o.onCompleted()}),source.subscribe(o))},source)};observableProto.throttleFirst=function(windowDuration,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);var duration=+windowDuration||0;if(duration<=0){throw new RangeError("windowDuration cannot be less or equal zero.")}var source=this;return new AnonymousObservable(function(o){var lastOnNext=0;return source.subscribe(function(x){var now=scheduler.now();if(lastOnNext===0||now-lastOnNext>=duration){lastOnNext=now;o.onNext(x)}},function(e){o.onError(e)},function(){o.onCompleted()})},source)};observableProto.transduce=function(transducer){var source=this;function transformForObserver(observer){return{init:function(){return observer},step:function(obs,input){return obs.onNext(input)},result:function(obs){return obs.onCompleted()}}}return new AnonymousObservable(function(observer){var xform=transducer(transformForObserver(observer));return source.subscribe(function(v){try{xform.step(observer,v)}catch(e){observer.onError(e)}},observer.onError.bind(observer),function(){xform.result(observer)})},source)};observableProto.exclusive=function(){var sources=this;return new AnonymousObservable(function(observer){var hasCurrent=false,isStopped=false,m=new SingleAssignmentDisposable,g=new CompositeDisposable;g.add(m);m.setDisposable(sources.subscribe(function(innerSource){if(!hasCurrent){hasCurrent=true;isPromise(innerSource)&&(innerSource=observableFromPromise(innerSource));var innerSubscription=new SingleAssignmentDisposable;g.add(innerSubscription);innerSubscription.setDisposable(innerSource.subscribe(observer.onNext.bind(observer),observer.onError.bind(observer),function(){g.remove(innerSubscription);hasCurrent=false;if(isStopped&&g.length===1){observer.onCompleted()}}))}},observer.onError.bind(observer),function(){isStopped=true;if(!hasCurrent&&g.length===1){observer.onCompleted()}}));return g},this)};observableProto.exclusiveMap=function(selector,thisArg){var sources=this,selectorFunc=bindCallback(selector,thisArg,3);return new AnonymousObservable(function(observer){var index=0,hasCurrent=false,isStopped=true,m=new SingleAssignmentDisposable,g=new CompositeDisposable;g.add(m);m.setDisposable(sources.subscribe(function(innerSource){if(!hasCurrent){hasCurrent=true;innerSubscription=new SingleAssignmentDisposable;g.add(innerSubscription);isPromise(innerSource)&&(innerSource=observableFromPromise(innerSource));innerSubscription.setDisposable(innerSource.subscribe(function(x){var result;try{result=selectorFunc(x,index++,innerSource)}catch(e){observer.onError(e);return}observer.onNext(result)},function(e){observer.onError(e)},function(){g.remove(innerSubscription);hasCurrent=false;if(isStopped&&g.length===1){observer.onCompleted()}}))}},function(e){observer.onError(e)},function(){isStopped=true;if(g.length===1&&!hasCurrent){observer.onCompleted()}}));return g},this)};Rx.VirtualTimeScheduler=function(__super__){function localNow(){return this.toDateTimeOffset(this.clock)}function scheduleNow(state,action){return this.scheduleAbsoluteWithState(state,this.clock,action)}function scheduleRelative(state,dueTime,action){return this.scheduleRelativeWithState(state,this.toRelative(dueTime),action)}function scheduleAbsolute(state,dueTime,action){return this.scheduleRelativeWithState(state,this.toRelative(dueTime-this.now()),action)}function invokeAction(scheduler,action){action();return disposableEmpty}inherits(VirtualTimeScheduler,__super__);function VirtualTimeScheduler(initialClock,comparer){this.clock=initialClock;this.comparer=comparer;this.isEnabled=false;this.queue=new PriorityQueue(1024);__super__.call(this,localNow,scheduleNow,scheduleRelative,scheduleAbsolute)}var VirtualTimeSchedulerPrototype=VirtualTimeScheduler.prototype;VirtualTimeSchedulerPrototype.add=notImplemented;VirtualTimeSchedulerPrototype.toDateTimeOffset=notImplemented;VirtualTimeSchedulerPrototype.toRelative=notImplemented;VirtualTimeSchedulerPrototype.schedulePeriodicWithState=function(state,period,action){var s=new SchedulePeriodicRecursive(this,state,period,action);return s.start()};VirtualTimeSchedulerPrototype.scheduleRelativeWithState=function(state,dueTime,action){var runAt=this.add(this.clock,dueTime);return this.scheduleAbsoluteWithState(state,runAt,action)};VirtualTimeSchedulerPrototype.scheduleRelative=function(dueTime,action){return this.scheduleRelativeWithState(action,dueTime,invokeAction)};VirtualTimeSchedulerPrototype.start=function(){if(!this.isEnabled){this.isEnabled=true;do{var next=this.getNext();if(next!==null){this.comparer(next.dueTime,this.clock)>0&&(this.clock=next.dueTime);next.invoke()}else{this.isEnabled=false}}while(this.isEnabled)}};VirtualTimeSchedulerPrototype.stop=function(){this.isEnabled=false};VirtualTimeSchedulerPrototype.advanceTo=function(time){var dueToClock=this.comparer(this.clock,time);if(this.comparer(this.clock,time)>0){throw new ArgumentOutOfRangeError}if(dueToClock===0){return}if(!this.isEnabled){this.isEnabled=true;do{var next=this.getNext();if(next!==null&&this.comparer(next.dueTime,time)<=0){this.comparer(next.dueTime,this.clock)>0&&(this.clock=next.dueTime);next.invoke()}else{this.isEnabled=false}}while(this.isEnabled);this.clock=time}};VirtualTimeSchedulerPrototype.advanceBy=function(time){var dt=this.add(this.clock,time),dueToClock=this.comparer(this.clock,dt);if(dueToClock>0){throw new ArgumentOutOfRangeError}if(dueToClock===0){return}this.advanceTo(dt)};VirtualTimeSchedulerPrototype.sleep=function(time){var dt=this.add(this.clock,time);if(this.comparer(this.clock,dt)>=0){throw new ArgumentOutOfRangeError}this.clock=dt};VirtualTimeSchedulerPrototype.getNext=function(){while(this.queue.length>0){var next=this.queue.peek();if(next.isCancelled()){this.queue.dequeue()}else{return next}}return null};VirtualTimeSchedulerPrototype.scheduleAbsolute=function(dueTime,action){return this.scheduleAbsoluteWithState(action,dueTime,invokeAction)};VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState=function(state,dueTime,action){var self=this;function run(scheduler,state1){self.queue.remove(si);return action(scheduler,state1)}var si=new ScheduledItem(this,state,run,dueTime,this.comparer);this.queue.enqueue(si);return si.disposable};return VirtualTimeScheduler}(Scheduler);Rx.HistoricalScheduler=function(__super__){inherits(HistoricalScheduler,__super__);function HistoricalScheduler(initialClock,comparer){var clock=initialClock==null?0:initialClock;var cmp=comparer||defaultSubComparer;__super__.call(this,clock,cmp)}var HistoricalSchedulerProto=HistoricalScheduler.prototype;HistoricalSchedulerProto.add=function(absolute,relative){return absolute+relative};HistoricalSchedulerProto.toDateTimeOffset=function(absolute){return new Date(absolute).getTime()};HistoricalSchedulerProto.toRelative=function(timeSpan){return timeSpan};return HistoricalScheduler}(Rx.VirtualTimeScheduler);var AnonymousObservable=Rx.AnonymousObservable=function(__super__){inherits(AnonymousObservable,__super__);function fixSubscriber(subscriber){return subscriber&&isFunction(subscriber.dispose)?subscriber:isFunction(subscriber)?disposableCreate(subscriber):disposableEmpty}function setDisposable(s,state){var ado=state[0],subscribe=state[1];var sub=tryCatch(subscribe)(ado);if(sub===errorObj){if(!ado.fail(errorObj.e)){return thrower(errorObj.e)}}ado.setDisposable(fixSubscriber(sub))}function AnonymousObservable(subscribe,parent){this.source=parent;function s(observer){var ado=new AutoDetachObserver(observer),state=[ado,subscribe];if(currentThreadScheduler.scheduleRequired()){currentThreadScheduler.scheduleWithState(state,setDisposable)}else{setDisposable(null,state)}return ado}__super__.call(this,s)}return AnonymousObservable}(Observable);var AutoDetachObserver=function(__super__){inherits(AutoDetachObserver,__super__);function AutoDetachObserver(observer){__super__.call(this);this.observer=observer;this.m=new SingleAssignmentDisposable}var AutoDetachObserverPrototype=AutoDetachObserver.prototype;AutoDetachObserverPrototype.next=function(value){var result=tryCatch(this.observer.onNext).call(this.observer,value);if(result===errorObj){this.dispose();thrower(result.e)}};AutoDetachObserverPrototype.error=function(err){var result=tryCatch(this.observer.onError).call(this.observer,err);this.dispose();result===errorObj&&thrower(result.e)};AutoDetachObserverPrototype.completed=function(){var result=tryCatch(this.observer.onCompleted).call(this.observer);this.dispose();result===errorObj&&thrower(result.e)};AutoDetachObserverPrototype.setDisposable=function(value){this.m.setDisposable(value)};AutoDetachObserverPrototype.getDisposable=function(){return this.m.getDisposable()};AutoDetachObserverPrototype.dispose=function(){__super__.prototype.dispose.call(this);this.m.dispose()};return AutoDetachObserver}(AbstractObserver);var GroupedObservable=function(__super__){inherits(GroupedObservable,__super__);function subscribe(observer){return this.underlyingObservable.subscribe(observer)}function GroupedObservable(key,underlyingObservable,mergedDisposable){__super__.call(this,subscribe);this.key=key;this.underlyingObservable=!mergedDisposable?underlyingObservable:new AnonymousObservable(function(observer){return new CompositeDisposable(mergedDisposable.getDisposable(),underlyingObservable.subscribe(observer))})}return GroupedObservable}(Observable);var Subject=Rx.Subject=function(__super__){function subscribe(observer){checkDisposed(this);if(!this.isStopped){this.observers.push(observer);return new InnerSubscription(this,observer)}if(this.hasError){observer.onError(this.error);return disposableEmpty}observer.onCompleted();return disposableEmpty}inherits(Subject,__super__);function Subject(){__super__.call(this,subscribe);this.isDisposed=false,this.isStopped=false,this.observers=[];this.hasError=false}addProperties(Subject.prototype,Observer.prototype,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){checkDisposed(this);if(!this.isStopped){this.isStopped=true;for(var i=0,os=cloneArray(this.observers),len=os.length;i<len;i++){os[i].onCompleted()}this.observers.length=0}},onError:function(error){checkDisposed(this);if(!this.isStopped){this.isStopped=true;this.error=error;this.hasError=true;for(var i=0,os=cloneArray(this.observers),len=os.length;i<len;i++){os[i].onError(error)}this.observers.length=0}},onNext:function(value){checkDisposed(this);if(!this.isStopped){for(var i=0,os=cloneArray(this.observers),len=os.length;i<len;i++){os[i].onNext(value)}}},dispose:function(){this.isDisposed=true;this.observers=null}});Subject.create=function(observer,observable){return new AnonymousSubject(observer,observable)};return Subject}(Observable);var AsyncSubject=Rx.AsyncSubject=function(__super__){function subscribe(observer){checkDisposed(this);if(!this.isStopped){this.observers.push(observer);return new InnerSubscription(this,observer)}if(this.hasError){observer.onError(this.error)}else if(this.hasValue){observer.onNext(this.value);observer.onCompleted()}else{observer.onCompleted()}return disposableEmpty}inherits(AsyncSubject,__super__);function AsyncSubject(){__super__.call(this,subscribe);this.isDisposed=false;this.isStopped=false;this.hasValue=false;this.observers=[];this.hasError=false}addProperties(AsyncSubject.prototype,Observer,{hasObservers:function(){checkDisposed(this);return this.observers.length>0},onCompleted:function(){var i,len;checkDisposed(this);if(!this.isStopped){this.isStopped=true;var os=cloneArray(this.observers),len=os.length;if(this.hasValue){for(i=0;i<len;i++){var o=os[i];o.onNext(this.value);o.onCompleted()}}else{for(i=0;i<len;i++){os[i].onCompleted()}}this.observers.length=0}},onError:function(error){checkDisposed(this);if(!this.isStopped){this.isStopped=true;this.hasError=true;this.error=error;for(var i=0,os=cloneArray(this.observers),len=os.length;i<len;i++){os[i].onError(error)}this.observers.length=0}},onNext:function(value){checkDisposed(this);if(this.isStopped){return}this.value=value;this.hasValue=true},dispose:function(){this.isDisposed=true;this.observers=null;this.exception=null;this.value=null}});return AsyncSubject}(Observable);var AnonymousSubject=Rx.AnonymousSubject=function(__super__){inherits(AnonymousSubject,__super__);function subscribe(observer){return this.observable.subscribe(observer)}function AnonymousSubject(observer,observable){this.observer=observer;this.observable=observable;__super__.call(this,subscribe)}addProperties(AnonymousSubject.prototype,Observer.prototype,{onCompleted:function(){this.observer.onCompleted()},onError:function(error){this.observer.onError(error)},onNext:function(value){this.observer.onNext(value)}});return AnonymousSubject}(Observable);Rx.Pauser=function(__super__){inherits(Pauser,__super__); function Pauser(){__super__.call(this)}Pauser.prototype.pause=function(){this.onNext(false)};Pauser.prototype.resume=function(){this.onNext(true)};return Pauser}(Subject);if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){root.Rx=Rx;define(function(){return Rx})}else if(freeExports&&freeModule){if(moduleExports){(freeModule.exports=Rx).Rx=Rx}else{freeExports.Rx=Rx}}else{root.Rx=Rx}var rEndingLine=captureLine()}).call(this)}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{_process:6}],8:[function(require,module,exports){if(!String.prototype.endsWith){(function(){"use strict";var defineProperty=function(){try{var object={};var $defineProperty=Object.defineProperty;var result=$defineProperty(object,object,object)&&$defineProperty}catch(error){}return result}();var toString={}.toString;var endsWith=function(search){if(this==null){throw TypeError()}var string=String(this);if(search&&toString.call(search)=="[object RegExp]"){throw TypeError()}var stringLength=string.length;var searchString=String(search);var searchLength=searchString.length;var pos=stringLength;if(arguments.length>1){var position=arguments[1];if(position!==undefined){pos=position?Number(position):0;if(pos!=pos){pos=0}}}var end=Math.min(Math.max(pos,0),stringLength);var start=end-searchLength;if(start<0){return false}var index=-1;while(++index<searchLength){if(string.charCodeAt(start+index)!=searchString.charCodeAt(index)){return false}}return true};if(defineProperty){defineProperty(String.prototype,"endsWith",{value:endsWith,configurable:true,writable:true})}else{String.prototype.endsWith=endsWith}})()}},{}],9:[function(require,module,exports){var createElement=require("./vdom/create-element.js");module.exports=createElement},{"./vdom/create-element.js":22}],10:[function(require,module,exports){var diff=require("./vtree/diff.js");module.exports=diff},{"./vtree/diff.js":42}],11:[function(require,module,exports){var h=require("./virtual-hyperscript/index.js");module.exports=h},{"./virtual-hyperscript/index.js":29}],12:[function(require,module,exports){var diff=require("./diff.js");var patch=require("./patch.js");var h=require("./h.js");var create=require("./create-element.js");var VNode=require("./vnode/vnode.js");var VText=require("./vnode/vtext.js");module.exports={diff:diff,patch:patch,h:h,create:create,VNode:VNode,VText:VText}},{"./create-element.js":9,"./diff.js":10,"./h.js":11,"./patch.js":20,"./vnode/vnode.js":38,"./vnode/vtext.js":40}],13:[function(require,module,exports){module.exports=function split(undef){var nativeSplit=String.prototype.split,compliantExecNpcg=/()??/.exec("")[1]===undef,self;self=function(str,separator,limit){if(Object.prototype.toString.call(separator)!=="[object RegExp]"){return nativeSplit.call(str,separator,limit)}var output=[],flags=(separator.ignoreCase?"i":"")+(separator.multiline?"m":"")+(separator.extended?"x":"")+(separator.sticky?"y":""),lastLastIndex=0,separator=new RegExp(separator.source,flags+"g"),separator2,match,lastIndex,lastLength;str+="";if(!compliantExecNpcg){separator2=new RegExp("^"+separator.source+"$(?!\\s)",flags)}limit=limit===undef?-1>>>0:limit>>>0;while(match=separator.exec(str)){lastIndex=match.index+match[0].length;if(lastIndex>lastLastIndex){output.push(str.slice(lastLastIndex,match.index));if(!compliantExecNpcg&&match.length>1){match[0].replace(separator2,function(){for(var i=1;i<arguments.length-2;i++){if(arguments[i]===undef){match[i]=undef}}})}if(match.length>1&&match.index<str.length){Array.prototype.push.apply(output,match.slice(1))}lastLength=match[0].length;lastLastIndex=lastIndex;if(output.length>=limit){break}}if(separator.lastIndex===match.index){separator.lastIndex++}}if(lastLastIndex===str.length){if(lastLength||!separator.test("")){output.push("")}}else{output.push(str.slice(lastLastIndex))}return output.length>limit?output.slice(0,limit):output};return self}()},{}],14:[function(require,module,exports){"use strict";var OneVersionConstraint=require("individual/one-version");var MY_VERSION="7";OneVersionConstraint("ev-store",MY_VERSION);var hashKey="__EV_STORE_KEY@"+MY_VERSION;module.exports=EvStore;function EvStore(elem){var hash=elem[hashKey];if(!hash){hash=elem[hashKey]={}}return hash}},{"individual/one-version":16}],15:[function(require,module,exports){(function(global){"use strict";var root=typeof window!=="undefined"?window:typeof global!=="undefined"?global:{};module.exports=Individual;function Individual(key,value){if(key in root){return root[key]}root[key]=value;return value}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],16:[function(require,module,exports){"use strict";var Individual=require("./index.js");module.exports=OneVersion;function OneVersion(moduleName,version,defaultValue){var key="__INDIVIDUAL_ONE_VERSION_"+moduleName;var enforceKey=key+"_ENFORCE_SINGLETON";var versionValue=Individual(enforceKey,version);if(versionValue!==version){throw new Error("Can only have one copy of "+moduleName+".\n"+"You already have version "+versionValue+" installed.\n"+"This means you cannot install version "+version)}return Individual(key,defaultValue)}},{"./index.js":15}],17:[function(require,module,exports){(function(global){var topLevel=typeof global!=="undefined"?global:typeof window!=="undefined"?window:{};var minDoc=require("min-document");if(typeof document!=="undefined"){module.exports=document}else{var doccy=topLevel["__GLOBAL_DOCUMENT_CACHE@4"];if(!doccy){doccy=topLevel["__GLOBAL_DOCUMENT_CACHE@4"]=minDoc}module.exports=doccy}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"min-document":5}],18:[function(require,module,exports){"use strict";module.exports=function isObject(x){return typeof x==="object"&&x!==null}},{}],19:[function(require,module,exports){var nativeIsArray=Array.isArray;var toString=Object.prototype.toString;module.exports=nativeIsArray||isArray;function isArray(obj){return toString.call(obj)==="[object Array]"}},{}],20:[function(require,module,exports){var patch=require("./vdom/patch.js");module.exports=patch},{"./vdom/patch.js":25}],21:[function(require,module,exports){var isObject=require("is-object");var isHook=require("../vnode/is-vhook.js");module.exports=applyProperties;function applyProperties(node,props,previous){for(var propName in props){var propValue=props[propName];if(propValue===undefined){removeProperty(node,propName,propValue,previous)}else if(isHook(propValue)){removeProperty(node,propName,propValue,previous);if(propValue.hook){propValue.hook(node,propName,previous?previous[propName]:undefined)}}else{if(isObject(propValue)){patchObject(node,props,previous,propName,propValue)}else{node[propName]=propValue}}}}function removeProperty(node,propName,propValue,previous){if(previous){var previousValue=previous[propName];if(!isHook(previousValue)){if(propName==="attributes"){for(var attrName in previousValue){node.removeAttribute(attrName)}}else if(propName==="style"){for(var i in previousValue){node.style[i]=""}}else if(typeof previousValue==="string"){node[propName]=""}else{node[propName]=null}}else if(previousValue.unhook){previousValue.unhook(node,propName,propValue)}}}function patchObject(node,props,previous,propName,propValue){var previousValue=previous?previous[propName]:undefined;if(propName==="attributes"){for(var attrName in propValue){var attrValue=propValue[attrName];if(attrValue===undefined){node.removeAttribute(attrName)}else{node.setAttribute(attrName,attrValue)}}return}if(previousValue&&isObject(previousValue)&&getPrototype(previousValue)!==getPrototype(propValue)){node[propName]=propValue;return}if(!isObject(node[propName])){node[propName]={}}var replacer=propName==="style"?"":undefined;for(var k in propValue){var value=propValue[k];node[propName][k]=value===undefined?replacer:value}}function getPrototype(value){if(Object.getPrototypeOf){return Object.getPrototypeOf(value)}else if(value.__proto__){return value.__proto__}else if(value.constructor){return value.constructor.prototype}}},{"../vnode/is-vhook.js":33,"is-object":18}],22:[function(require,module,exports){var document=require("global/document");var applyProperties=require("./apply-properties");var isVNode=require("../vnode/is-vnode.js");var isVText=require("../vnode/is-vtext.js");var isWidget=require("../vnode/is-widget.js");var handleThunk=require("../vnode/handle-thunk.js");module.exports=createElement;function createElement(vnode,opts){var doc=opts?opts.document||document:document;var warn=opts?opts.warn:null;vnode=handleThunk(vnode).a;if(isWidget(vnode)){return vnode.init()}else if(isVText(vnode)){return doc.createTextNode(vnode.text)}else if(!isVNode(vnode)){if(warn){warn("Item is not a valid virtual dom node",vnode)}return null}var node=vnode.namespace===null?doc.createElement(vnode.tagName):doc.createElementNS(vnode.namespace,vnode.tagName);var props=vnode.properties;applyProperties(node,props);var children=vnode.children;for(var i=0;i<children.length;i++){var childNode=createElement(children[i],opts);if(childNode){node.appendChild(childNode)}}return node}},{"../vnode/handle-thunk.js":31,"../vnode/is-vnode.js":34,"../vnode/is-vtext.js":35,"../vnode/is-widget.js":36,"./apply-properties":21,"global/document":17}],23:[function(require,module,exports){var noChild={};module.exports=domIndex;function domIndex(rootNode,tree,indices,nodes){if(!indices||indices.length===0){return{}}else{indices.sort(ascending);return recurse(rootNode,tree,indices,nodes,0)}}function recurse(rootNode,tree,indices,nodes,rootIndex){nodes=nodes||{};if(rootNode){if(indexInRange(indices,rootIndex,rootIndex)){nodes[rootIndex]=rootNode}var vChildren=tree.children;if(vChildren){var childNodes=rootNode.childNodes;for(var i=0;i<tree.children.length;i++){rootIndex+=1;var vChild=vChildren[i]||noChild;var nextIndex=rootIndex+(vChild.count||0);if(indexInRange(indices,rootIndex,nextIndex)){recurse(childNodes[i],vChild,indices,nodes,rootIndex)}rootIndex=nextIndex}}}return nodes}function indexInRange(indices,left,right){if(indices.length===0){return false}var minIndex=0;var maxIndex=indices.length-1;var currentIndex;var currentItem;while(minIndex<=maxIndex){currentIndex=(maxIndex+minIndex)/2>>0;currentItem=indices[currentIndex];if(minIndex===maxIndex){return currentItem>=left&&currentItem<=right}else if(currentItem<left){minIndex=currentIndex+1}else if(currentItem>right){maxIndex=currentIndex-1}else{return true}}return false}function ascending(a,b){return a>b?1:-1}},{}],24:[function(require,module,exports){var applyProperties=require("./apply-properties");var isWidget=require("../vnode/is-widget.js");var VPatch=require("../vnode/vpatch.js");var render=require("./create-element");var updateWidget=require("./update-widget");module.exports=applyPatch;function applyPatch(vpatch,domNode,renderOptions){var type=vpatch.type;var vNode=vpatch.vNode;var patch=vpatch.patch;switch(type){case VPatch.REMOVE:return removeNode(domNode,vNode);case VPatch.INSERT:return insertNode(domNode,patch,renderOptions);case VPatch.VTEXT:return stringPatch(domNode,vNode,patch,renderOptions);case VPatch.WIDGET:return widgetPatch(domNode,vNode,patch,renderOptions);case VPatch.VNODE:return vNodePatch(domNode,vNode,patch,renderOptions);case VPatch.ORDER:reorderChildren(domNode,patch);return domNode;case VPatch.PROPS:applyProperties(domNode,patch,vNode.properties);return domNode;case VPatch.THUNK:return replaceRoot(domNode,renderOptions.patch(domNode,patch,renderOptions));default:return domNode}}function removeNode(domNode,vNode){var parentNode=domNode.parentNode;if(parentNode){parentNode.removeChild(domNode)}destroyWidget(domNode,vNode);return null}function insertNode(parentNode,vNode,renderOptions){var newNode=render(vNode,renderOptions);if(parentNode){parentNode.appendChild(newNode)}return parentNode}function stringPatch(domNode,leftVNode,vText,renderOptions){var newNode;if(domNode.nodeType===3){domNode.replaceData(0,domNode.length,vText.text);newNode=domNode}else{var parentNode=domNode.parentNode;newNode=render(vText,renderOptions);if(parentNode&&newNode!==domNode){parentNode.replaceChild(newNode,domNode)}}return newNode}function widgetPatch(domNode,leftVNode,widget,renderOptions){var updating=updateWidget(leftVNode,widget);var newNode;if(updating){newNode=widget.update(leftVNode,domNode)||domNode}else{newNode=render(widget,renderOptions)}var parentNode=domNode.parentNode;if(parentNode&&newNode!==domNode){parentNode.replaceChild(newNode,domNode)}if(!updating){destroyWidget(domNode,leftVNode)}return newNode}function vNodePatch(domNode,leftVNode,vNode,renderOptions){var parentNode=domNode.parentNode;var newNode=render(vNode,renderOptions);if(parentNode&&newNode!==domNode){parentNode.replaceChild(newNode,domNode)}return newNode}function destroyWidget(domNode,w){if(typeof w.destroy==="function"&&isWidget(w)){w.destroy(domNode)}}function reorderChildren(domNode,moves){var childNodes=domNode.childNodes;var keyMap={};var node;var remove;var insert;for(var i=0;i<moves.removes.length;i++){remove=moves.removes[i];node=childNodes[remove.from];if(remove.key){keyMap[remove.key]=node}domNode.removeChild(node)}var length=childNodes.length;for(var j=0;j<moves.inserts.length;j++){insert=moves.inserts[j];node=keyMap[insert.key];domNode.insertBefore(node,insert.to>=length++?null:childNodes[insert.to])}}function replaceRoot(oldRoot,newRoot){if(oldRoot&&newRoot&&oldRoot!==newRoot&&oldRoot.parentNode){oldRoot.parentNode.replaceChild(newRoot,oldRoot)}return newRoot}},{"../vnode/is-widget.js":36,"../vnode/vpatch.js":39,"./apply-properties":21,"./create-element":22,"./update-widget":26}],25:[function(require,module,exports){var document=require("global/document");var isArray=require("x-is-array");var domIndex=require("./dom-index");var patchOp=require("./patch-op");module.exports=patch;function patch(rootNode,patches){return patchRecursive(rootNode,patches)}function patchRecursive(rootNode,patches,renderOptions){var indices=patchIndices(patches);if(indices.length===0){return rootNode}var index=domIndex(rootNode,patches.a,indices);var ownerDocument=rootNode.ownerDocument;if(!renderOptions){renderOptions={patch:patchRecursive};if(ownerDocument!==document){renderOptions.document=ownerDocument}}for(var i=0;i<indices.length;i++){var nodeIndex=indices[i];rootNode=applyPatch(rootNode,index[nodeIndex],patches[nodeIndex],renderOptions)}return rootNode}function applyPatch(rootNode,domNode,patchList,renderOptions){if(!domNode){return rootNode}var newNode;if(isArray(patchList)){for(var i=0;i<patchList.length;i++){newNode=patchOp(patchList[i],domNode,renderOptions);if(domNode===rootNode){rootNode=newNode}}}else{newNode=patchOp(patchList,domNode,renderOptions);if(domNode===rootNode){rootNode=newNode}}return rootNode}function patchIndices(patches){var indices=[];for(var key in patches){if(key!=="a"){indices.push(Number(key))}}return indices}},{"./dom-index":23,"./patch-op":24,"global/document":17,"x-is-array":19}],26:[function(require,module,exports){var isWidget=require("../vnode/is-widget.js");module.exports=updateWidget;function updateWidget(a,b){if(isWidget(a)&&isWidget(b)){if("name"in a&&"name"in b){return a.id===b.id}else{return a.init===b.init}}return false}},{"../vnode/is-widget.js":36}],27:[function(require,module,exports){"use strict";var EvStore=require("ev-store");module.exports=EvHook;function EvHook(value){if(!(this instanceof EvHook)){return new EvHook(value)}this.value=value}EvHook.prototype.hook=function(node,propertyName){var es=EvStore(node);var propName=propertyName.substr(3);es[propName]=this.value};EvHook.prototype.unhook=function(node,propertyName){var es=EvStore(node);var propName=propertyName.substr(3);es[propName]=undefined}},{"ev-store":14}],28:[function(require,module,exports){"use strict";module.exports=SoftSetHook;function SoftSetHook(value){if(!(this instanceof SoftSetHook)){return new SoftSetHook(value)}this.value=value}SoftSetHook.prototype.hook=function(node,propertyName){if(node[propertyName]!==this.value){node[propertyName]=this.value}}},{}],29:[function(require,module,exports){"use strict";var isArray=require("x-is-array");var VNode=require("../vnode/vnode.js");var VText=require("../vnode/vtext.js");var isVNode=require("../vnode/is-vnode");var isVText=require("../vnode/is-vtext");var isWidget=require("../vnode/is-widget");var isHook=require("../vnode/is-vhook");var isVThunk=require("../vnode/is-thunk");var parseTag=require("./parse-tag.js");var softSetHook=require("./hooks/soft-set-hook.js");var evHook=require("./hooks/ev-hook.js");module.exports=h;function h(tagName,properties,children){var childNodes=[];var tag,props,key,namespace;if(!children&&isChildren(properties)){children=properties;props={}}props=props||properties||{};tag=parseTag(tagName,props);if(props.hasOwnProperty("key")){key=props.key;props.key=undefined}if(props.hasOwnProperty("namespace")){namespace=props.namespace;props.namespace=undefined}if(tag==="INPUT"&&!namespace&&props.hasOwnProperty("value")&&props.value!==undefined&&!isHook(props.value)){props.value=softSetHook(props.value)}transformProperties(props);if(children!==undefined&&children!==null){addChild(children,childNodes,tag,props)}return new VNode(tag,props,childNodes,key,namespace)}function addChild(c,childNodes,tag,props){if(typeof c==="string"){childNodes.push(new VText(c))}else if(isChild(c)){childNodes.push(c)}else if(isArray(c)){for(var i=0;i<c.length;i++){addChild(c[i],childNodes,tag,props)}}else if(c===null||c===undefined){return}else{throw UnexpectedVirtualElement({foreignObject:c,parentVnode:{tagName:tag,properties:props}})}}function transformProperties(props){for(var propName in props){if(props.hasOwnProperty(propName)){var value=props[propName];if(isHook(value)){continue}if(propName.substr(0,3)==="ev-"){props[propName]=evHook(value)}}}}function isChild(x){return isVNode(x)||isVText(x)||isWidget(x)||isVThunk(x)}function isChildren(x){return typeof x==="string"||isArray(x)||isChild(x)}function UnexpectedVirtualElement(data){var err=new Error;err.type="virtual-hyperscript.unexpected.virtual-element";err.message="Unexpected virtual child passed to h().\n"+"Expected a VNode / Vthunk / VWidget / string but:\n"+"got:\n"+errorString(data.foreignObject)+".\n"+"The parent vnode is:\n"+errorString(data.parentVnode);"\n"+"Suggested fix: change your `h(..., [ ... ])` callsite.";err.foreignObject=data.foreignObject;err.parentVnode=data.parentVnode;return err}function errorString(obj){try{return JSON.stringify(obj,null," ")}catch(e){return String(obj)}}},{"../vnode/is-thunk":32,"../vnode/is-vhook":33,"../vnode/is-vnode":34,"../vnode/is-vtext":35,"../vnode/is-widget":36,"../vnode/vnode.js":38,"../vnode/vtext.js":40,"./hooks/ev-hook.js":27,"./hooks/soft-set-hook.js":28,"./parse-tag.js":30,"x-is-array":19}],30:[function(require,module,exports){"use strict";var split=require("browser-split");var classIdSplit=/([\.#]?[a-zA-Z0-9_:-]+)/;var notClassId=/^\.|#/;module.exports=parseTag;function parseTag(tag,props){if(!tag){return"DIV"}var noId=!props.hasOwnProperty("id");var tagParts=split(tag,classIdSplit);var tagName=null;if(notClassId.test(tagParts[1])){tagName="DIV"}var classes,part,type,i;for(i=0;i<tagParts.length;i++){part=tagParts[i];if(!part){continue}type=part.charAt(0);if(!tagName){tagName=part}else if(type==="."){classes=classes||[];classes.push(part.substring(1,part.length))}else if(type==="#"&&noId){props.id=part.substring(1,part.length)}}if(classes){if(props.className){classes.push(props.className)}props.className=classes.join(" ")}return props.namespace?tagName:tagName.toUpperCase()}},{"browser-split":13}],31:[function(require,module,exports){var isVNode=require("./is-vnode");var isVText=require("./is-vtext");var isWidget=require("./is-widget");var isThunk=require("./is-thunk");module.exports=handleThunk;function handleThunk(a,b){var renderedA=a;var renderedB=b;if(isThunk(b)){renderedB=renderThunk(b,a)}if(isThunk(a)){renderedA=renderThunk(a,null)}return{a:renderedA,b:renderedB}}function renderThunk(thunk,previous){var renderedThunk=thunk.vnode;if(!renderedThunk){renderedThunk=thunk.vnode=thunk.render(previous)}if(!(isVNode(renderedThunk)||isVText(renderedThunk)||isWidget(renderedThunk))){throw new Error("thunk did not return a valid node")}return renderedThunk}},{"./is-thunk":32,"./is-vnode":34,"./is-vtext":35,"./is-widget":36}],32:[function(require,module,exports){module.exports=isThunk;function isThunk(t){return t&&t.type==="Thunk"}},{}],33:[function(require,module,exports){module.exports=isHook;function isHook(hook){return hook&&(typeof hook.hook==="function"&&!hook.hasOwnProperty("hook")||typeof hook.unhook==="function"&&!hook.hasOwnProperty("unhook"))}},{}],34:[function(require,module,exports){var version=require("./version");module.exports=isVirtualNode;function isVirtualNode(x){return x&&x.type==="VirtualNode"&&x.version===version}},{"./version":37}],35:[function(require,module,exports){var version=require("./version");module.exports=isVirtualText;function isVirtualText(x){return x&&x.type==="VirtualText"&&x.version===version}},{"./version":37}],36:[function(require,module,exports){module.exports=isWidget;function isWidget(w){return w&&w.type==="Widget"}},{}],37:[function(require,module,exports){module.exports="2"},{}],38:[function(require,module,exports){var version=require("./version");var isVNode=require("./is-vnode");var isWidget=require("./is-widget");var isThunk=require("./is-thunk");var isVHook=require("./is-vhook");module.exports=VirtualNode;var noProperties={};var noChildren=[];function VirtualNode(tagName,properties,children,key,namespace){this.tagName=tagName;this.properties=properties||noProperties;this.children=children||noChildren;this.key=key!=null?String(key):undefined;this.namespace=typeof namespace==="string"?namespace:null;var count=children&&children.length||0;var descendants=0;var hasWidgets=false;var hasThunks=false;var descendantHooks=false;var hooks;for(var propName in properties){if(properties.hasOwnProperty(propName)){var property=properties[propName];if(isVHook(property)&&property.unhook){if(!hooks){hooks={}}hooks[propName]=property}}}for(var i=0;i<count;i++){var child=children[i];if(isVNode(child)){descendants+=child.count||0;if(!hasWidgets&&child.hasWidgets){hasWidgets=true}if(!hasThunks&&child.hasThunks){hasThunks=true}if(!descendantHooks&&(child.hooks||child.descendantHooks)){descendantHooks=true}}else if(!hasWidgets&&isWidget(child)){if(typeof child.destroy==="function"){hasWidgets=true}}else if(!hasThunks&&isThunk(child)){hasThunks=true}}this.count=count+descendants;this.hasWidgets=hasWidgets;this.hasThunks=hasThunks;this.hooks=hooks;this.descendantHooks=descendantHooks}VirtualNode.prototype.version=version;VirtualNode.prototype.type="VirtualNode"},{"./is-thunk":32,"./is-vhook":33,"./is-vnode":34,"./is-widget":36,"./version":37}],39:[function(require,module,exports){var version=require("./version");VirtualPatch.NONE=0;VirtualPatch.VTEXT=1;VirtualPatch.VNODE=2;VirtualPatch.WIDGET=3;VirtualPatch.PROPS=4;VirtualPatch.ORDER=5;VirtualPatch.INSERT=6;VirtualPatch.REMOVE=7;VirtualPatch.THUNK=8;module.exports=VirtualPatch;function VirtualPatch(type,vNode,patch){this.type=Number(type);this.vNode=vNode;this.patch=patch}VirtualPatch.prototype.version=version;VirtualPatch.prototype.type="VirtualPatch"},{"./version":37}],40:[function(require,module,exports){var version=require("./version");module.exports=VirtualText;function VirtualText(text){this.text=String(text)}VirtualText.prototype.version=version;VirtualText.prototype.type="VirtualText"},{"./version":37}],41:[function(require,module,exports){var isObject=require("is-object");var isHook=require("../vnode/is-vhook");module.exports=diffProps;function diffProps(a,b){var diff;for(var aKey in a){if(!(aKey in b)){diff=diff||{};diff[aKey]=undefined}var aValue=a[aKey];var bValue=b[aKey];if(aValue===bValue){continue}else if(isObject(aValue)&&isObject(bValue)){if(getPrototype(bValue)!==getPrototype(aValue)){diff=diff||{};diff[aKey]=bValue}else if(isHook(bValue)){diff=diff||{};diff[aKey]=bValue}else{var objectDiff=diffProps(aValue,bValue);if(objectDiff){diff=diff||{};diff[aKey]=objectDiff}}}else{diff=diff||{};diff[aKey]=bValue}}for(var bKey in b){if(!(bKey in a)){diff=diff||{};diff[bKey]=b[bKey]}}return diff}function getPrototype(value){if(Object.getPrototypeOf){return Object.getPrototypeOf(value)}else if(value.__proto__){return value.__proto__}else if(value.constructor){return value.constructor.prototype}}},{"../vnode/is-vhook":33,"is-object":18}],42:[function(require,module,exports){var isArray=require("x-is-array");var VPatch=require("../vnode/vpatch");var isVNode=require("../vnode/is-vnode");var isVText=require("../vnode/is-vtext");var isWidget=require("../vnode/is-widget");var isThunk=require("../vnode/is-thunk");var handleThunk=require("../vnode/handle-thunk");var diffProps=require("./diff-props");module.exports=diff;function diff(a,b){var patch={a:a};walk(a,b,patch,0);return patch}function walk(a,b,patch,index){if(a===b){return}var apply=patch[index];var applyClear=false;if(isThunk(a)||isThunk(b)){thunks(a,b,patch,index)}else if(b==null){if(!isWidget(a)){clearState(a,patch,index);apply=patch[index]}apply=appendPatch(apply,new VPatch(VPatch.REMOVE,a,b))}else if(isVNode(b)){if(isVNode(a)){if(a.tagName===b.tagName&&a.namespace===b.namespace&&a.key===b.key){var propsPatch=diffProps(a.properties,b.properties);if(propsPatch){apply=appendPatch(apply,new VPatch(VPatch.PROPS,a,propsPatch))}apply=diffChildren(a,b,patch,apply,index)}else{apply=appendPatch(apply,new VPatch(VPatch.VNODE,a,b));applyClear=true}}else{apply=appendPatch(apply,new VPatch(VPatch.VNODE,a,b));applyClear=true}}else if(isVText(b)){if(!isVText(a)){apply=appendPatch(apply,new VPatch(VPatch.VTEXT,a,b));applyClear=true}else if(a.text!==b.text){apply=appendPatch(apply,new VPatch(VPatch.VTEXT,a,b))}}else if(isWidget(b)){if(!isWidget(a)){applyClear=true}apply=appendPatch(apply,new VPatch(VPatch.WIDGET,a,b))}if(apply){patch[index]=apply}if(applyClear){clearState(a,patch,index)}}function diffChildren(a,b,patch,apply,index){var aChildren=a.children;var orderedSet=reorder(aChildren,b.children);var bChildren=orderedSet.children;var aLen=aChildren.length;var bLen=bChildren.length;var len=aLen>bLen?aLen:bLen;for(var i=0;i<len;i++){var leftNode=aChildren[i];var rightNode=bChildren[i];index+=1;if(!leftNode){if(rightNode){apply=appendPatch(apply,new VPatch(VPatch.INSERT,null,rightNode))}}else{walk(leftNode,rightNode,patch,index)}if(isVNode(leftNode)&&leftNode.count){index+=leftNode.count}}if(orderedSet.moves){apply=appendPatch(apply,new VPatch(VPatch.ORDER,a,orderedSet.moves))}return apply}function clearState(vNode,patch,index){unhook(vNode,patch,index);destroyWidgets(vNode,patch,index)}function destroyWidgets(vNode,patch,index){if(isWidget(vNode)){if(typeof vNode.destroy==="function"){patch[index]=appendPatch(patch[index],new VPatch(VPatch.REMOVE,vNode,null))}}else if(isVNode(vNode)&&(vNode.hasWidgets||vNode.hasThunks)){var children=vNode.children;var len=children.length;for(var i=0;i<len;i++){var child=children[i];index+=1;destroyWidgets(child,patch,index);if(isVNode(child)&&child.count){index+=child.count}}}else if(isThunk(vNode)){thunks(vNode,null,patch,index)}}function thunks(a,b,patch,index){var nodes=handleThunk(a,b);var thunkPatch=diff(nodes.a,nodes.b);if(hasPatches(thunkPatch)){patch[index]=new VPatch(VPatch.THUNK,null,thunkPatch)}}function hasPatches(patch){for(var index in patch){if(index!=="a"){return true}}return false}function unhook(vNode,patch,index){if(isVNode(vNode)){if(vNode.hooks){patch[index]=appendPatch(patch[index],new VPatch(VPatch.PROPS,vNode,undefinedKeys(vNode.hooks)))}if(vNode.descendantHooks||vNode.hasThunks){var children=vNode.children;var len=children.length;for(var i=0;i<len;i++){var child=children[i];index+=1;unhook(child,patch,index);if(isVNode(child)&&child.count){index+=child.count}}}}else if(isThunk(vNode)){thunks(vNode,null,patch,index)}}function undefinedKeys(obj){var result={};for(var key in obj){result[key]=undefined}return result}function reorder(aChildren,bChildren){var bChildIndex=keyIndex(bChildren);var bKeys=bChildIndex.keys;var bFree=bChildIndex.free;if(bFree.length===bChildren.length){return{children:bChildren,moves:null}}var aChildIndex=keyIndex(aChildren);var aKeys=aChildIndex.keys;var aFree=aChildIndex.free;if(aFree.length===aChildren.length){return{children:bChildren,moves:null}}var newChildren=[];var freeIndex=0;var freeCount=bFree.length;var deletedItems=0;for(var i=0;i<aChildren.length;i++){var aItem=aChildren[i];var itemIndex;if(aItem.key){if(bKeys.hasOwnProperty(aItem.key)){itemIndex=bKeys[aItem.key];newChildren.push(bChildren[itemIndex])}else{itemIndex=i-deletedItems++;newChildren.push(null)}}else{if(freeIndex<freeCount){itemIndex=bFree[freeIndex++];newChildren.push(bChildren[itemIndex])}else{itemIndex=i-deletedItems++;newChildren.push(null)}}}var lastFreeIndex=freeIndex>=bFree.length?bChildren.length:bFree[freeIndex];for(var j=0;j<bChildren.length;j++){var newItem=bChildren[j];if(newItem.key){if(!aKeys.hasOwnProperty(newItem.key)){newChildren.push(newItem)}}else if(j>=lastFreeIndex){newChildren.push(newItem)}}var simulate=newChildren.slice();var simulateIndex=0;var removes=[];var inserts=[];var simulateItem;for(var k=0;k<bChildren.length;){var wantedItem=bChildren[k];simulateItem=simulate[simulateIndex];while(simulateItem===null&&simulate.length){removes.push(remove(simulate,simulateIndex,null));simulateItem=simulate[simulateIndex]}if(!simulateItem||simulateItem.key!==wantedItem.key){if(wantedItem.key){if(simulateItem&&simulateItem.key){if(bKeys[simulateItem.key]!==k+1){removes.push(remove(simulate,simulateIndex,simulateItem.key));simulateItem=simulate[simulateIndex];if(!simulateItem||simulateItem.key!==wantedItem.key){inserts.push({key:wantedItem.key,to:k})}else{simulateIndex++}}else{inserts.push({key:wantedItem.key,to:k})}}else{inserts.push({key:wantedItem.key,to:k})}k++}else if(simulateItem&&simulateItem.key){removes.push(remove(simulate,simulateIndex,simulateItem.key))}}else{simulateIndex++;k++}}while(simulateIndex<simulate.length){simulateItem=simulate[simulateIndex];removes.push(remove(simulate,simulateIndex,simulateItem&&simulateItem.key))}if(removes.length===deletedItems&&!inserts.length){return{children:newChildren,moves:null}}return{children:newChildren,moves:{removes:removes,inserts:inserts}}}function remove(arr,index,key){arr.splice(index,1);return{from:index,key:key}}function keyIndex(children){var keys={};var free=[];var length=children.length;for(var i=0;i<length;i++){var child=children[i];if(child.key){keys[child.key]=i}else{free.push(i)}}return{keys:keys,free:free}}function appendPatch(apply,patch){if(apply){if(isArray(apply)){apply.push(patch)}else{apply=[apply,patch]}return apply}else{return patch}}},{"../vnode/handle-thunk":31,"../vnode/is-thunk":32,"../vnode/is-vnode":34,"../vnode/is-vtext":35,"../vnode/is-widget":36,"../vnode/vpatch":39,"./diff-props":41,"x-is-array":19}],43:[function(require,module,exports){"use strict";var _createClass=function(){function defineProperties(target,props){for(var key in props){var prop=props[key];prop.configurable=true;if(prop.value)prop.writable=true}Object.defineProperties(target,props)}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _classCallCheck=function(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}};var Rx=require("rx");var _require=require("./stream");var createStream=_require.createStream;require("string.prototype.endswith");function makeDispatchFunction(element,eventName){return function dispatchCustomEvent(evData){var event;try{event=new Event(eventName)}catch(err){ event=document.createEvent("Event");event.initEvent(eventName,true,true)}event.data=evData;element.dispatchEvent(event)}}function subscribeDispatchers(element,eventStreams){if(!eventStreams||typeof eventStreams!=="object"){return}var disposables=new Rx.CompositeDisposable;for(var streamName in eventStreams){if(eventStreams.hasOwnProperty(streamName)){if(streamName.endsWith("$")&&typeof eventStreams[streamName].subscribe==="function"){var eventName=streamName.slice(0,-1);var disposable=eventStreams[streamName].subscribe(makeDispatchFunction(element,eventName));disposables.add(disposable)}}}return disposables}function subscribeDispatchersWhenRootChanges(widget,eventStreams){if(!eventStreams||typeof eventStreams!=="object"){return}widget._rootElem$.distinctUntilChanged(Rx.helpers.identity,function(x,y){return x&&y&&x.isEqualNode&&x.isEqualNode(y)}).subscribe(function(rootElem){if(widget.eventStreamsSubscriptions){widget.eventStreamsSubscriptions.dispose()}widget.eventStreamsSubscriptions=subscribeDispatchers(rootElem,eventStreams)})}var PropertiesProxy=function(){function PropertiesProxy(){_classCallCheck(this,PropertiesProxy);this.type="PropertiesProxy";this.proxiedProps={}}_createClass(PropertiesProxy,{get:{value:function get(streamKey){if(typeof this.proxiedProps[streamKey]==="undefined"){this.proxiedProps[streamKey]=new Rx.Subject}return this.proxiedProps[streamKey].distinctUntilChanged()}}});return PropertiesProxy}();function createContainerElement(tagName,vtreeProperties){var element=document.createElement("div");element.id=vtreeProperties.id||"";element.className=vtreeProperties.className||"";element.className+=" cycleCustomElement-"+tagName.toUpperCase();return element}function replicate(origin,destination){origin.subscribe(function(elem){return destination.onNext(elem)})}function warnIfVTreeHasNoKey(vtree){if(typeof vtree.key==="undefined"){console.warn("Missing `key` property for Cycle custom element "+vtree.tagName)}}function throwIfVTreeHasPropertyChildren(vtree){if(typeof vtree.properties.children!=="undefined"){throw new Error("Custom element should not have property `children`. This is "+"reserved for children elements nested into this custom element.")}}function makeConstructor(){return function customElementConstructor(vtree){warnIfVTreeHasNoKey(vtree);this.type="Widget";this.properties=vtree.properties;throwIfVTreeHasPropertyChildren(vtree);this.properties.children=vtree.children;this.key=vtree.key;this._rootElem$=new Rx.ReplaySubject(1)}}function makeInit(tagName,definitionFn){var _require2=require("./render");var render=_require2.render;return function initCustomElement(){var widget=this;var element=createContainerElement(tagName,widget.properties);element.cycleCustomElementRoot$=createStream(function(vtree$){return render(vtree$,element)});element.cycleCustomElementProperties=new PropertiesProxy;var eventStreams=definitionFn(element.cycleCustomElementRoot$,element.cycleCustomElementProperties);widget.eventStreamsSubscriptions=subscribeDispatchers(element,eventStreams);subscribeDispatchersWhenRootChanges(widget,eventStreams);widget.update(null,element);return element}}function makeUpdate(){return function updateCustomElement(previous,element){if(!element){return}if(!element.cycleCustomElementProperties){return}if(element.cycleCustomElementProperties.type!=="PropertiesProxy"){return}if(!element.cycleCustomElementProperties.proxiedProps){return}replicate(element.cycleCustomElementRoot$,this._rootElem$);var proxiedProps=element.cycleCustomElementProperties.proxiedProps;for(var prop in proxiedProps){if(proxiedProps.hasOwnProperty(prop)){var propStreamName=prop;var propName=prop.slice(0,-1);if(this.properties.hasOwnProperty(propName)){proxiedProps[propStreamName].onNext(this.properties[propName])}}}}}module.exports={makeConstructor:makeConstructor,makeInit:makeInit,makeUpdate:makeUpdate}},{"./render":47,"./stream":48,rx:7,"string.prototype.endswith":8}],44:[function(require,module,exports){"use strict";var VirtualDOM=require("virtual-dom");var Rx=require("rx");var Stream=require("./stream");var PropertyHook=require("./property-hook");var Rendering=require("./render");var Cycle={createStream:function createStream(definitionFn){return new Stream.createStream(definitionFn)},render:Rendering.render,registerCustomElement:Rendering.registerCustomElement,vdomPropHook:function vdomPropHook(fn){return new PropertyHook(fn)},Rx:Rx,h:VirtualDOM.h};module.exports=Cycle},{"./property-hook":46,"./render":47,"./stream":48,rx:7,"virtual-dom":12}],45:[function(require,module,exports){"use strict";var _createClass=function(){function defineProperties(target,props){for(var key in props){var prop=props[key];prop.configurable=true;if(prop.value)prop.writable=true}Object.defineProperties(target,props)}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _get=function get(object,property,receiver){var desc=Object.getOwnPropertyDescriptor(object,property);if(desc===undefined){var parent=Object.getPrototypeOf(object);if(parent===null){return undefined}else{return get(parent,property,receiver)}}else if("value"in desc&&desc.writable){return desc.value}else{var getter=desc.get;if(getter===undefined){return undefined}return getter.call(receiver)}};var _inherits=function(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+typeof superClass)}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)subClass.__proto__=superClass};var _classCallCheck=function(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}};var Rx=require("rx");var InputProxy=function(_Rx$Subject){function InputProxy(){_classCallCheck(this,InputProxy);_get(Object.getPrototypeOf(InputProxy.prototype),"constructor",this).call(this);this.type="InputProxy";this._userEvent$={}}_inherits(InputProxy,_Rx$Subject);_createClass(InputProxy,{choose:{value:function choose(selector,eventName){if(typeof this._userEvent$[selector]==="undefined"){this._userEvent$[selector]={}}if(typeof this._userEvent$[selector][eventName]==="undefined"){this._userEvent$[selector][eventName]=new Rx.Subject}return this._userEvent$[selector][eventName]}}});return InputProxy}(Rx.Subject);module.exports=InputProxy},{rx:7}],46:[function(require,module,exports){"use strict";var _createClass=function(){function defineProperties(target,props){for(var key in props){var prop=props[key];prop.configurable=true;if(prop.value)prop.writable=true}Object.defineProperties(target,props)}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _classCallCheck=function(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}};var PropertyHook=function(){function PropertyHook(fn){_classCallCheck(this,PropertyHook);this.fn=fn}_createClass(PropertyHook,{hook:{value:function hook(){this.fn.apply(this,arguments)}}});return PropertyHook}();module.exports=PropertyHook},{}],47:[function(require,module,exports){"use strict";var _slicedToArray=function(arr,i){if(Array.isArray(arr)){return arr}else if(Symbol.iterator in Object(arr)){var _arr=[];for(var _iterator=arr[Symbol.iterator](),_step;!(_step=_iterator.next()).done;){_arr.push(_step.value);if(i&&_arr.length===i)break}return _arr}else{throw new TypeError("Invalid attempt to destructure non-iterable instance")}};var VDOM={h:require("virtual-dom").h,diff:require("virtual-dom/diff"),patch:require("virtual-dom/patch")};var Rx=require("rx");var CustomElements=require("./custom-elements");require("babel/polyfill");var CustomElementsRegistry=new Map;function isElement(obj){return typeof HTMLElement==="object"?obj instanceof HTMLElement||obj instanceof DocumentFragment:obj&&typeof obj==="object"&&obj!==null&&(obj.nodeType===1||obj.nodeType===11)&&typeof obj.nodeName==="string"}function fixRootElem$(rawRootElem$,domContainer){var originalClasses=(domContainer.className||"").trim().split(/\s+/);return rawRootElem$.map(function fixRootElemClassName(rootElem){var previousClasses=rootElem.className.trim().split(/\s+/);var missingClasses=originalClasses.filter(function(clss){return previousClasses.indexOf(clss)<0});rootElem.className=previousClasses.concat(missingClasses).join(" ");return rootElem}).shareReplay(1)}function isVtreeCustomElement(vtree){return vtree.type==="Widget"&&!!vtree._rootElem$}function replaceCustomElements(vtree){if(!vtree||vtree.type==="VirtualText"){return vtree}var tagName=(vtree.tagName||"").toUpperCase();if(tagName&&CustomElementsRegistry.has(tagName)){var WidgetClass=CustomElementsRegistry.get(tagName);return new WidgetClass(vtree)}if(Array.isArray(vtree.children)){for(var i=vtree.children.length-1;i>=0;i--){vtree.children[i]=replaceCustomElements(vtree.children[i])}}return vtree}function getArrayOfAllWidgetRootElemStreams(vtree){if(vtree.type==="Widget"&&vtree._rootElem$){return[vtree._rootElem$]}var array=[];if(Array.isArray(vtree.children)){for(var i=vtree.children.length-1;i>=0;i--){array=array.concat(getArrayOfAllWidgetRootElemStreams(vtree.children[i]))}}return array}function renderRawRootElem$(vtree$,domContainer){var rootElem=undefined;if(/cycleCustomElement-[^\b]+/.exec(domContainer.className)!==null){rootElem=domContainer}else{rootElem=document.createElement("div");domContainer.innerHTML="";domContainer.appendChild(rootElem)}return vtree$.startWith(VDOM.h()).map(function renderingPreprocessing(vtree){return replaceCustomElements(vtree)}).map(function checkDOMUserVtreeNotCustomElement(vtree){if(isVtreeCustomElement(vtree)){throw new Error("Illegal to use a Cycle custom element as the root of a View.")}return vtree}).pairwise().flatMap(function renderDiffAndPatch(_ref){var _ref2=_slicedToArray(_ref,2);var oldVTree=_ref2[0];var newVTree=_ref2[1];if(typeof newVTree==="undefined"){return}var arrayOfAll=getArrayOfAllWidgetRootElemStreams(newVTree);var rootElemAfterChildren$=Rx.Observable.combineLatest(arrayOfAll,function(){return rootElem}).first();var cycleCustomElementRoot$=rootElem.cycleCustomElementRoot$;var cycleCustomElementProperties=rootElem.cycleCustomElementProperties;try{rootElem=VDOM.patch(rootElem,VDOM.diff(oldVTree,newVTree))}catch(err){console.error(err)}if(!!cycleCustomElementRoot$){rootElem.cycleCustomElementRoot$=cycleCustomElementRoot$}if(!!cycleCustomElementProperties){rootElem.cycleCustomElementProperties=cycleCustomElementProperties}if(arrayOfAll.length===0){return Rx.Observable.just(rootElem)}else{return rootElemAfterChildren$}}).startWith(rootElem)}function makeInteraction$(rootElem$){return{subscribe:function subscribe(){throw new Error("Cannot subscribe to interaction$ without first calling "+"choose(selector, eventName)")},choose:function choose(selector,eventName){if(typeof selector!=="string"){throw new Error("interaction$.choose() expects first argument to be a "+"string as a CSS selector")}if(typeof eventName!=="string"){throw new Error("interaction$.choose() expects second argument to be a "+"string representing the event type to listen for.")}return rootElem$.flatMapLatest(function flatMapDOMUserEventStream(rootElem){if(!rootElem){return Rx.Observable.empty()}var klass=selector.replace(".","");if(rootElem.className.search(new RegExp("\\b"+klass+"\\b"))>=0){return Rx.Observable.fromEvent(rootElem,eventName)}var targetElements=rootElem.querySelectorAll(selector);if(targetElements&&targetElements.length>0){return Rx.Observable.fromEvent(targetElements,eventName)}else{return Rx.Observable.empty()}})}}}function publishConnectRootElem$(rootElem$){var subscription=rootElem$.publish().connect();rootElem$.dispose=function dispose(){subscription.dispose()};return rootElem$}function render(vtree$,container){var domContainer=typeof container==="string"?document.querySelector(container):container;if(typeof container==="string"&&domContainer===null){throw new Error("Cannot render into unknown element '"+container+"'")}else if(!isElement(domContainer)){throw new Error("Given container is not a DOM element neither a selector string.")}var rawRootElem$=renderRawRootElem$(vtree$,domContainer);var rootElem$=fixRootElem$(rawRootElem$,domContainer);rootElem$.interaction$=makeInteraction$(rootElem$);rootElem$=publishConnectRootElem$(rootElem$);return rootElem$}function registerCustomElement(tagName,definitionFn){if(typeof tagName!=="string"||typeof definitionFn!=="function"){throw new Error("registerCustomElement requires parameters `tagName` and "+"`definitionFn`.")}tagName=tagName.toUpperCase();if(CustomElementsRegistry.has(tagName)){throw new Error("Cannot register custom element `"+tagName+"` "+"for the DOMUser because that tagName is already registered.")}var WidgetClass=CustomElements.makeConstructor();WidgetClass.prototype.init=CustomElements.makeInit(tagName,definitionFn);WidgetClass.prototype.update=CustomElements.makeUpdate();CustomElementsRegistry.set(tagName,WidgetClass)}function unregisterAllCustomElements(){CustomElementsRegistry.clear()}module.exports={render:render,registerCustomElement:registerCustomElement,unregisterAllCustomElements:unregisterAllCustomElements}},{"./custom-elements":43,"babel/polyfill":4,rx:7,"virtual-dom":12,"virtual-dom/diff":10,"virtual-dom/patch":20}],48:[function(require,module,exports){"use strict";var Rx=require("rx");var InputProxy=require("./input-proxy");function throwIfNotObservable(thing){if(typeof thing==="undefined"||typeof thing.subscribe!=="function"){throw new Error("Stream function should always return an Rx.Observable.")}}function replicate(source,subject){if(typeof source==="undefined"){throw new Error("Cannot replicate() if source is undefined.")}return source.subscribe(function replicationOnNext(x){subject.onNext(x)},function replicationOnError(err){subject.onError(err);console.error(err)})}function replicateAllInteraction$(input,proxy){var subscriptions=new Rx.CompositeDisposable;var selectors=proxy._userEvent$;for(var selector in selectors){if(selectors.hasOwnProperty(selector)){var elemEvents=selectors[selector];for(var eventName in elemEvents){if(elemEvents.hasOwnProperty(eventName)){var event$=input.choose(selector,eventName);if(event$!==null){var subscription=replicate(event$,elemEvents[eventName]);subscriptions.add(subscription)}}}}}return subscriptions}function replicateAll(input,proxy){if(!input||!proxy){return}if(typeof input.choose==="function"){return replicateAllInteraction$(input,proxy)}else if(typeof input.subscribe==="function"&&proxy.type==="InputProxy"){return replicate(input,proxy)}else{throw new Error("Cycle Stream got injected with invalid inputs.")}}function makeInjectFn(stream){return function inject(){if(stream._wasInjected){console.warn("Stream has already been injected an input.")}if(stream._definitionFn.length!==arguments.length){console.warn("The call to inject() should provide the inputs that this "+"Stream expects according to its definition function.")}for(var i=0;i<stream._definitionFn.length;i++){var subscription=replicateAll(arguments[i],stream._proxies[i]);stream._subscription.add(subscription)}stream._wasInjected=true;if(arguments.length===1){return arguments[0]}else if(arguments.length>1){return Array.prototype.slice.call(arguments)}else{return null}}}function makeDisposeFn(stream){return function dispose(){if(stream._subscription&&typeof stream._subscription.dispose==="function"){stream._subscription.dispose()}}}function createStream(definitionFn){if(arguments.length!==1||typeof definitionFn!=="function"){throw new Error("Stream expects the definitionFn as the only argument.")}var proxies=[];for(var i=0;i<definitionFn.length;i++){proxies[i]=new InputProxy}var stream=definitionFn.apply({},proxies);throwIfNotObservable(stream);stream._proxies=proxies;stream._definitionFn=definitionFn;stream._wasInjected=false;stream._subscription=new Rx.CompositeDisposable;stream.inject=makeInjectFn(stream);stream.dispose=makeDisposeFn(stream);return stream}module.exports={createStream:createStream}},{"./input-proxy":45,rx:7}]},{},[44])(44)});
app/javascript/mastodon/components/logo.js
Ryanaka/mastodon
import React from 'react'; const Logo = () => ( <svg viewBox='0 0 216.4144 232.00976' className='logo'> <use xlinkHref='#mastodon-svg-logo' /> </svg> ); export default Logo;
app/components/Register.js
GongDexing/work-board
/*jshint esversion:6*/ import React, { Component } from 'react'; import { Modal, Button, Form, Input, Checkbox } from 'antd'; import AlertMsg from './AlertMsg'; import { NameRule, EmailRuleWithCheck, PasswdRule } from '../validate/rules'; import { register } from '../actions/auth'; const createForm = Form.create; const FormItem = Form.Item; class Register extends Component{ constructor(props){ super(props); this.handleOk = this.handleOk.bind(this); this.handleCancel = this.handleCancel.bind(this); } handleOk(e) { e.preventDefault(); const { dispatch } = this.props; this.props.form.validateFields((errs, values) => { if(!!errs){ return; } dispatch(register(values)); }); } handleCancel(e) { const { hide } = this.props; hide(); } render(){ const { alert, btnStatus } = this.props; const { getFieldProps, getFieldError, isFieldValidating } = this.props.form; const formItemLayout = { labelCol: { span: 7 }, wrapperCol: { span: 12 }, }; return( <Modal ref="modal" visible={true} title="注册" onOk={this.handleOk} onCancel={this.handleCancel} closable={false} footer={[ <Button key="submit" type="primary" size="large" onClick={this.handleOk} disabled={!btnStatus}>注册</Button>, <Button key="back" type="ghost" size="large" onClick={this.handleCancel} disabled={!btnStatus}>取消</Button> ]} > <AlertMsg alert={alert}/> <Form horizontal> <FormItem {...formItemLayout} label='姓名' hasFeedback help={isFieldValidating('name') ? '校验中...' : (getFieldError('name') || []).join(', ')}> <Input {...getFieldProps('name', NameRule)}/> </FormItem> <FormItem {...formItemLayout} label='邮箱' required> <Input {...getFieldProps('email', EmailRuleWithCheck)} type='email'/> </FormItem> <FormItem {...formItemLayout} label='密码' required> <Input {...getFieldProps('passwd', PasswdRule)} type="password"/> </FormItem> </Form> </Modal> ); } } export default createForm()(Register);